Java tutorial -- difference between int and Integer: javaintinteger

Source: Internet
Author: User

Java tutorial -- difference between int and Integer: javaintinteger

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

The following is an example:

 1 package syswar.cc; 2  3 public class IntegerCompare { 4  5     public static void main(String[] args) { 6         // TODO Auto-generated method stub 7         Integer a1 = 2; 8         Integer a2 = 2; 9 10         Integer b1 = 150;11         Integer b2 = 150;12 13         Integer c1 = new Integer(2);14         Integer c2 = new Integer(2);15 16         Integer d1 = new Integer(150);17         Integer d2 = new Integer(150);18 19         System.out.println("a1==a2?" + (a1==a2));20         System.out.println("b1==b2?" + (b1==b2));21         System.out.println("c1==c2?" + (c1==c2));22         System.out.println("d1==d2?" + (d1==d2));23     }24 25 }                

 

Running result:

a1==a2?trueb1==b2?falsec1==c2?falsed1==d2?false

 

Why is this result? We first compare the two groups a and B. During Integer initialization, the Integer object data is cached. The int value corresponding to these Integer objects is in the byte range, that is, [-128,127].

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

The Integer object obtained through the new method is directly allocated from the heap. Therefore, no matter how many int values are, the result of = is false.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.