This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
When the int is -128 to 127,the compiler will treat it as an byte. Just like code in line 1 is OK,but why line 2 is complie error?
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35253
7
posted
0
Because you can't assign an object of type Integer to a reference of type Byte. Autoboxing doesn't mean that the left side is unboxed to "byte", it means that the right side is boxed to Integer.
Originally posted by Ulf Dittmer: Because you can't assign an object of type Integer to a reference of type Byte. Autoboxing doesn't mean that the left side is unboxed to "byte", it means that the right side is boxed to Integer.
Hi Ulf Somehow I am unable to replicate the compilation error mentioned. The following code is compiling just fine for me.
I am using JDK 1.6 . Could you please point me if I am missing something here? [ July 07, 2008: Message edited by: Satya Maheshwari ]
Thanks and Regards
Jack Crifer
Greenhorn
Joined: May 18, 2008
Posts: 29
posted
0
and Byte b = new Byte(2); is complie error too.
who can explian it .
kapil kumar
Greenhorn
Joined: May 22, 2008
Posts: 25
posted
0
final int i = 1;// Byte b = new Byte(i); //Here is complie error Byte b = i; //Here is runtime error
Hi... Here i is a compile time constant.. When you say Byte b = new Byte(i);,here i is an integer literal while Byte() expects either a byte value or a string val... So when we change this to:
Byte b = new Byte((byte)i); or Byte b = new Byte("10");it works fine but for Byte b = new Byte(10); it does not since 10 is an integer literal...
for Byte b = i; it compiles n runs fine....
If you can't be the Sun ..<br /> Be a star ..............
Sunny Mattas
Ranch Hand
Joined: Apr 22, 2008
Posts: 45
posted
0
public class Demo { public static void main(String args[]) { final int i =100; byte b = i; Byte b1 = i;//runtime error. } }
Somebody please explain why......... Byte b = i is giving runtime error/exception. error/exception is: Exception in thread "main" java.lang.VerifyError: (class: Demo, method: main signature: ([Ljava/lang/String V) Register 1 contains wrong type
Regards Sunny
Regards
Sunny Mattas
SCJP5
Raphael Rabadan
Ranch Hand
Joined: Jul 05, 2008
Posts: 141
posted
0
The following code won't give any error using a 1.5/1.6 jre:
a final int between -128 and 127 will be seen as a byte, therefore making the code above correct.
Please, those with error take a look what jre you'r using to compile. [ July 09, 2008: Message edited by: Raphael Rabadan ]