The question of whether two strings are equal in Java

Source: Internet
Author: User

I recently learned Java, and today I'm programming with a tricky question about judging whether two strings are equal. In programming, expressions that typically compare two strings for the same expression are "= =", but cannot be written in Java. In Java, Equals () is used;

String name = new String ("Sunzhiyan"); String age =  New String ("Sunzhiyan"), if (name ==age) {System.out.print ("equal");} Else{system.out.print ("unequal");}

The output here is: Not equal, because new comes out will apply a different address, and the = = number is to compare their address (Java no pointer, assuming the address)

String name = "Sunzhiyan"; String age = "Sunzhiyan", if (name.equals (age)) {System.out.print ("equal");} Else{system.out.print ("unequal");}

This will be equal, because the Java default string is constant, that is, the address of A and B (Java without pointers, assuming addresses) consistent

and using

Attention:

Equals () compares the contents of the object (which distinguishes the case of letters), but is not equal if you compare two objects with "= =", compared to the memory addresses of two objects. Even though their contents are equal, the memory addresses of different objects are not the same.

The question of whether two strings are equal in Java

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.