Results 1 to 2 of 2
Thread: int to byte
- 01-13-2008, 07:11 PM #1
Senior Member
- Join Date
- Nov 2007
- Posts
- 115
- Rep Power
- 0
int to byte
I found something strange. Please review the code below:
Output:Java Code:final int i = 100; byte b = i; System.out.println(b);
Removing the final keywords, causes exception.Java Code:100
Output:Java Code:int i = 100; byte b = i; System.out.println(b);
What is the reason? What role final keywords plays here?Java Code:Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte
Thanks.
- 01-13-2008, 07:22 PM #2
Member
- Join Date
- Jan 2008
- Posts
- 24
- Rep Power
- 0
This is because once you marked a variable as final, it is now immutable, cannot be changed after the declaration. compiler is intelligent enough to make the decision by allowing it to be set to a byte variable if the value is in range.
the other case, compiler cannot guarantee if there will not be a change on the int before it is assigned to the byte so it does not allow the setting it. Otherwise this code would create a runtime error:
int i = 100;
... lots of code here and i may be altered and set to 10000...
byte b=i; <-- error!!
Similar Threads
-
Byte Array
By sandor in forum New To JavaReplies: 12Last Post: 01-15-2009, 03:31 AM -
Byte Values
By javaplus in forum New To JavaReplies: 1Last Post: 06-23-2008, 12:08 AM -
using Byte arrays
By mew in forum New To JavaReplies: 2Last Post: 01-30-2008, 03:54 AM -
BufferedImage to Byte
By Java Tip in forum Java TipReplies: 0Last Post: 01-22-2008, 08:17 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks