This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

type conversion  RSS feed

 
sandeep dhingra
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can some one plz help me
look at this
byte b=2;
b += 10; //1
b = b+10; //2

1. works fine but 2. does not.

i know that we have to explicitly narrow the conversion in 2. by adding byte on RHS but but how come 1. works as both are one and the same thing.
 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sandeep,

byte b=2;
b += 10; //1
b = b+10; //2

1 and 2 are not same thing.
1 is identical to b=(byte) b+10; works fine.
2 does not compile because b is converted to int (due to + operator) and after adding 10, the result(int) can not be assigned to byte value.
 
srikanth reddy
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Areca ...
b=(byte)b+10;wont work ...will give loss of precision ...i think u mean to say b=(byte)(b+10)..this will work fine .....

thanks & regards

srikanth
 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ha, i meaned b=(byte)(b+10) you are right.
Thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!