String comparisons in Java

Source: Internet
Author: User

When comparing two objects of type string in Java:

1.

1 string s1=new string ("123"); 2 string s2=new string ("123");  System.out.println (S1==S2);
System.out.println (s1.equals (S2));

At this point the S1,S2 is a reference to the string object, and if it is compared directly with = =, because the comparison is a reference to the object, and although both are string objects, S1,S2 represents a different reference, so the result is false.

However, using the Equals () method, you can directly compare the actual contents of two objects, so the result is true;

2.

1 String s3= "ASD"; 2 String s4= "ASD"; 3 System.out.println (S3==S4);

This defines the two basic type S1,s2, at which point the = = is used to compare whether their values are the same (also available equals (), the result is the same), and the final result is true.

3.

1Publicclasscandy{2     Static{3System.out.println ("Loading Candy");4     }5          Public Static voidMain (string[] args) {6Candy c1=NewCandy ();7Candy c2=NewCandy ();8 System.out.println (c1.equals (C2));9         }Ten } One  A                

This is the two different reference c1,c2 for the object of the custom class candy, but the result is still false because the Equals () default comparison reference. So if you want to compare the contents of the objects referred to by the two references (the classes you define), you need to override the Equals () function in your own class to produce the result we expect.

String comparisons 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.