• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

variable assignment

 
sumi rankan
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//possible loss of precision
int i=10;
byte b=i;

//compiles fine
final int i=10;
byte b=i;

I thought both of them will give possible loss of precision error...obviously not why? can someone kindly explain?
Is it because i is final ,so b is assigned with i during compiletime?
 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final int i=10;

when you declare a variable final and initialize it then compiler is sure that its value will not change.

and when you assign that variable value to byte like below it will not produce any error as it is sure that value of i is 10.

byte b=i;
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose we dont mark i as final, then later on assign a value i=129, then it cant be cast as a byte, which will generate a compiler error.
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you use

final int i = 10;
byte b = i;

then the compiler replaces the value of i wherever the constant i is used. so the above two statements will become

final int i = 10;
byte b = 10;

infact if i is declared in a method, then the compiler will replace every occurrence of i with the value of i and will delete the declaration for i...
 
M Srilatha
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One point to be remembered:
even if the variable i is declared as final, the value of i should be able to fit in byte variable.

final int i = 128;
byte b = i; //doesnt compile
 
vipin jain
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

I agreed with M SRILATHA.

Byte range is 0 to 127 so if you store >=127 in byte reference varible it's not problem because it's easy fix there but if you use>127 is not compile.
 
sumi rankan
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic