I recently read Gao Qi’s Java 300 tutorial, and there was a line of code in it that Teacher Gao briefly mentioned, but upon closer inspection, I felt that I didn’t understand the knowledge points contained in it. The code is as follows:
public class Test063 { public static void main(String[] args){ Integer i = Integer.parseInt("234"); System.out.println(i); } }
In the second sentence, Interger.parseInt("234"), I checked the source code,
It is clearly stated above that the parseInt method returns a value of type int, but how can it be directly assigned to an Integer object?
I did another experiment
Integer a = 1;//报错 Integer b = Integer.parseInt("1");//编译通过
The result made me very confused. Why is this happening?
Mengxin asks for answers. Thank you!
I am new to you, which version of JDK do you have? I wrote Integer i = 1; on my IDE and it was no problem. I recently updated it to JDK8, but I think JDK7 should also be OK. I don’t know about the previous version. What are the limitations on autoboxing. Why don't you try upgrading?
After JDK 1.5, there is an automatic packaging and automatic unpacking feature, which will automatically convert this primitive data type and its object type. Official document:
https://docs.oracle.com/javas...
After JDK1.5, automatic boxing and unboxing are possible
The teacher’s code is an automatic boxing process, and Integer is the packaging class of int. Your JDK version should be older.