A comparison of strings in Java

Source: Internet
Author: User

About the various = = and equals of string, some people do not understand

Nutshell

String S1 = "Hello" declares a constant, which is in a constant pool.

String s2 = new String ("Hello"), which declares an object that has a separate space in memory.

= = Compares the address of a string

Equals compares the contents of a string

 Public classteststring{ Public Static voidMain (string[] args) {String str1=NewString ("Hello"); String str2=NewString ("Hello"); String STR3= "Hello"; String STR4= "Hello";        System.out.println (Str1.hashcode ());        System.out.println (Str2.hashcode ());        System.out.println (Str1.equals (str2)); System.out.println (str1==str2);        System.out.println (Str1.equals (STR3)); System.out.println (str1==STR3);        System.out.println (Str3.equals (STR4)); System.out.println (STR3==STR4); }}

The output is:

6960965069609650truefalse true True False

A comparison of strings 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.