search

Home  >  Q&A  >  body text

In Gao Qi's Java video, how can this statement that directly assigns an int type value to an Integer object pass compilation?

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!

ringa_leeringa_lee2726 days ago993

reply all(4)I'll reply

  • 学习ing

    学习ing2017-06-15 09:23:19

    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?

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-15 09:23:19

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

    reply
    0
  • 滿天的星座

    滿天的星座2017-06-15 09:23:19

    After JDK1.5, automatic boxing and unboxing are possible

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-15 09:23:19

    The teacher’s code is an automatic boxing process, and Integer is the packaging class of int. Your JDK version should be older.

    reply
    0
  • Cancelreply