Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

int x = 10 VS. int x; x = 10

 
Vopli Vidoplyasova
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just found these two examples on Cameron's blog:


While the first one compiles and runs, the second one throws loss of precision error when I try to compile it. What's the deal? I always thought

and

are pretty much same thing
[ August 19, 2008: Message edited by: Slava Golovachenko ]
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well
int x = 10;

and

int x;
x = 10;

are the same but
final int x = 10;

and
final int x;
x = 10;

are not the same

that's because the value of final variables are replaced with the value of the variable after compilation...

eg-
final int x = 10;
short s = x;

will look like this after compilation-
final int x = 10;
short s = 10;

but when you assign the value after declaration, the compiler is not able to determine the value of the variable x at compile time so it is not able to replace the value of the final variable with the name of the final variable everywhere the final variable is used.

so
final int x;
x = 10;
short s = x;

after compilation would remain the same so it gives an error that an int is being assigned to a short....
 
Vopli Vidoplyasova
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit! Help me understand though. Is it like both variables are declared first, and then x is given the value, so at the moment of declaration s doesn't know yet that x is 10, not 86245, so it's concerned about possible precision loss?
 
Santhosh Kumar
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right. If the value is known at the compile time (via final variable), then compiler can do the range check to make sure value is in range and allow the compilation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic