The difference between = = and equal of reference types and basic types in Java

Source: Internet
Author: User
1, Java in the "Basic type" and "basic type" comparison = = = Comparison is the value
2, the comparison of "basic type" and "reference type" in Java is also a comparison between the base type and the base type. Long j= 10000l; Long i= New Long (10000);
System. Out. println (I==J); True
So the reference type and the base type are compared, and when compiled into the underlying instruction, the reference type is converted to the base type and the value of the comparison.

System. Out. println (K.equals (j)); True all classes in Java referencing a type inherit from object, and if there is no equal method to override object, then "= =" and "equal" between reference types are the object addresses of the comparisons. For string, the wrapper type of the base type Boolean, Character, Byte, Shot, Integer, Long, Float, Double, applies 1 = = = Table comparison address, equal represents the comparison content
StringBuffer and StringBuilder special, = = and equal are comparison addresses because there is no equal method to rewrite the object.
3. Comparison of "reference type" and "reference type" in Java because the Java privilege mode caches the value of-128 ~ 127 Returns an integer object that is not a new one. Instead, it's an object that's already cached in the heap, so the following two ways to declare it are cached in the objects in the heap , which points to the same address: the object is not re-created. Long m= long.valueof (127); Long n= 127;
Long mk= 128L; Long nk= 128L; So m and n are equal (restricted range -128~127) System for both equal and = = comparisons. Out. println (m==n); True System. Out. println (M.equal (kn);//true
System. Out. println (MK==NK); False System. Out. println (Mk.equal (NK)); True but the new object will still be reassigned in the Java heap, so it is not equal to the above; long M2=new long (127); Long N2=new Long (127); System. Out. println (M2==N2); False System. Out. println (M2.equals (N2)); True

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.