File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes int x = 10 VS. int x; x = 10 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "int x = 10 VS. int x; x = 10" Watch "int x = 10 VS. int x; x = 10" New topic
Author

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

Vopli Vidoplyasova
Greenhorn

Joined: Jun 05, 2008
Posts: 26
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

Joined: Aug 03, 2008
Posts: 9304
    
  17

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....


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Vopli Vidoplyasova
Greenhorn

Joined: Jun 05, 2008
Posts: 26
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

Joined: Nov 07, 2000
Posts: 242
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: int x = 10 VS. int x; x = 10