File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes variable assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "variable assignment" Watch "variable assignment" New topic
Author

variable assignment

sumi rankan
Ranch Hand

Joined: Apr 07, 2008
Posts: 46
//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

Joined: Mar 15, 2008
Posts: 210

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;


SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.
Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
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

Joined: Aug 03, 2008
Posts: 9280
    
  17

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


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
M Srilatha
Ranch Hand

Joined: Aug 27, 2008
Posts: 137
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


Thanks,<br />Srilatha M
vipin jain
Ranch Hand

Joined: Aug 24, 2008
Posts: 122
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.


Best Regards,<br />Vipin<br />MCA, SCJP5, SCWCD in progress
sumi rankan
Ranch Hand

Joined: Apr 07, 2008
Posts: 46
Thank you all...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: variable assignment
 
Similar Threads
FINAL VARIABLE
Implicit Widening aka Conversions ???
strange casting and conversions
WidenBoxing Confusion
Conversion of negative binary number to decimal number