Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoboxing in Java

How does 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
    }
}
like image 663
Nandkumar Tekale Avatar asked Dec 13 '11 11:12

Nandkumar Tekale


People also ask

Why do we need Autoboxing in Java?

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

What is unboxing Java?

Unboxing in Java is an automatic conversion of an object of a wrapper class to the value of its respective primitive data type by the compiler. It is the opposite technique of Autoboxing. For example converting Integer class to int datatype, converting Double class into double data type, etc.

What is the difference between boxing and Autoboxing?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.


1 Answers

Yes, this will work it is equivalent to

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

as long student.id is not null.

like image 152
stacker Avatar answered Oct 28 '22 10:10

stacker