Home > Java > javaTutorial > Java Tutorial—The Difference Between Int and Integer

Java Tutorial—The Difference Between Int and Integer

高洛峰
Release: 2016-12-02 16:22:39
Original
2002 people have browsed it

First let’s talk about the difference between int and Integer:

int is the basic data type, and Integer is the wrapper class of int. Note: The type of the latter is "class". For example, using generics, List numList;

int has an initial value of 0, and integer is null.

Look at the specific example below:

package syswar.cc;

public class IntegerCompare {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Integer a1 = 2;
        Integer a2 = 2;

        Integer b1 = 150;
        Integer b2 = 150;

        Integer c1 = new Integer(2);
        Integer c2 = new Integer(2);

        Integer d1 = new Integer(150);
        Integer d2 = new Integer(150);

        System.out.println("a1==a2?" + (a1==a2));
        System.out.println("b1==b2?" + (b1==b2));
        System.out.println("c1==c2?" + (c1==c2));
        System.out.println("d1==d2?" + (d1==d2));
    }

}
Copy after login

Running result:

a1==a2?true
b1==b2?false
c1==c2?false
d1==d2?false>
Copy after login

Why is this result? Let's first compare the two groups a and b. When Integer is initialized, Integer object data is cached. The int values ​​corresponding to these Integer objects are in the byte range, that is, [-128,127].

When assigning an int value directly to Integer, if the value range is [-128,127], Integer directly takes the Integer object from the cache. Therefore, when the directly assigned int value is in [-128,127], the Integer object is the same object. .

The Integer object obtained through the new method is an object allocated directly from the heap. Therefore, no matter what the specific int value is, the result of the == judgment is false


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template