Auto Boxing in Java

How is the following expression evaluated?

Student class:

public class Student
{
    private Integer id;
    // few fields here

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id=id;
    }

    //setters and getters
}

And in some method:

{
    int studentId;

    // few lines here

    if(studentId==student.getId())  // **1. what about auto-unboxing here? Would it compare correctly? I am not sure.**
    {
        //some operation here
    }
}
+5
source share
6 answers

Yes it will work, it is equivalent

studentId==student.getId().intValue()  

since long student.id is not null.

+4
source

Yes, it will work, but mind you!

If Student's Integer value is null, when evaluating

you will have a NullPointerException,
studentId == student.getId();

Also note that autoboxing will have some performance, so you should use it if you need to.

More details here: http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

+3
source

, . -, .

+1

studentId==student.getId()

, NullPointerException, student null.

, autoboxing , .. Integer int, , . , . :

studentId==student.getId().intValue()  

,

new Integer(studentId)==student.getId()

, , , .

+1

, , java language:

, , (. 5.1.8) , (§5.6.2).

jls

, java autounbox .

§5.1.8 , . jls

+1

http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

, autoboxing unboxing? " " , , . . int; autoboxing unboxing , .

- (Integer ..) , , null . .

NullPointerException .

+1
source

All Articles