Forums Register Login

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

+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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....
+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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.
Heroic work plunger man. Please allow me to introduce you to this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 3892 times.
Similar Threads
Specific Method
Help on this SCJP question
Final Variable Behavior
Boxing confusion
Expanations os scjp code
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:30:52.