Traps for string constant pools in Java

Source: Internet
Author: User

 Public classtestcase{StaticString AB = "AB"; StaticString Geta () {returnA; }    StaticString Getab () {return"AB"; }     Public Static voidMain (string[] args) {//1String _ab =NewString ("AB"); System.out.printf ("Ab==_ab%b\n", ab==_ab); //2String S1 = "a" + "B"; System.out.printf ("Ab==s1%b\n", ab==S1); //3String s2 = geta () + "B"; System.out.printf ("Ab==s2%b\n", ab==S2); //4System.out.printf ("Ab==getab ()%b\n", ab==Getab ()); //5String s3 =NewString ("AB"); System.out.printf ("Ab==s3%b\n", ab==S3); }}

Output Result:

Ab==_ab false
AB==S1 true
Ab==s2 false
Ab==getab () True
AB==S3 false

First output:

Although there is a string "AB" inside the constant pool, _ab is a reference to another string object in memory.

The second output:

Compiler optimizations, because the + around is an explicit character constant, so the plus operator does not request a new string variable, but points to the constant pool of "AB". If there is no "ab" in the constant pool, then the plus operator adds "AB" to the constant pool

The third output:

The compiler does not optimize because the compiler considers the left operand to be string rather than a string constant (who calls it not a dominant 2333). The plus operator will request a new string.

Fourth output:

Since AB and Getab () point to the same string constant "AB", the address must be the same.

Fifth output:

It's like repeating the first one. 233

Traps for string constant pools 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.