Comparison of = = between Java integer and int. Ask for an explanation

Source: Internet
Author: User

public static void Main (string[] args) {
		//TODO auto-generated method Stub
		Integer a = new integer (1);
		Integer b = new integer (1);
		int c=1;
		Integer e = 1;
		System.out.println ("A==b:" + (a==b));
		System.out.println ("A==c:" + (A==c));
		System.out.println ("A==e:" + (a==e));
		System.out.println ("C==e:" + (c==e));
	}
Results:
a==b:false
a==c:true
a==e:false
c==e:true


Integer is the encapsulated object of int, two objects = = the value of the stack is
integer a = new integer (1);
Integer b = new integer (1);
A and B are the addresses in the integer heap, not the value
A, b the address in the heap is obviously different so a==b is false

int c = 1; int is a value type, and reference type integer is
obviously compared to value type int. Because int in the heap does not open memory, his value in the stack is his own value
so a==c compares their respective values, A==c is true

Integer e=1; This is special, directly assigned to  it has independent memory, Each assignment will check if there is a value in memory that matches him, and if so, pay the memory address to E, if not, open up new memory

You can try the following example:
Integer t = 1;
Integer t1 = 1;
T==t1 is true, as stated above, when T and T1 point to the same memory new

must be to open up new memory, direct assignment is not necessarily open up new memory
because a reference to the heap, and e point to store memory specifically, so their memory address is not the same
so a==e is false

c==e equivalent to A==c, a reference type is a value type

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.