Java you may not know about the series 1

Source: Internet
Author: User

Overview

This type of article will not be updated analysis of the classic interview topics, recorded in this easy to understand. Suppose there is an incorrect place and ask the audience to shoot bricks.
Today, I'll share some of the topics of frequently used strings. I believe that the small partners learn Java is more familiar with the string class is just, today we come and she met again. Okay, here's the start.

First, the string feature.

String is immutable constant whenever we create a string object. Assume that the string does not exist in the constant pool of the heap area. Creates a store in a constant dominant (called String pool where the string is stored), assuming that the variable's address is directly directed to the constant pool. For example: String b = "ABC" This sentence of memory performance sample is shown below.

Start the question below

1.1
StringnewString("abc");StringnewString("abc"); System.out.println(s1 == s2);

What is the result of the output?
From the above figure it is probably said that the JVM has a stack area, heap area. Local variables are mainly stored in the stack area. New objects are stored in the heap area. = = is the address for the object type. So in S1 and S1 are the addresses of the different objects that are referenced in the heap, respectively, and the graphic understanding is as follows

The answer is obvious. Address different output false.

1.2
String"abc"new StringBuffer(s1); System.out.println(s1.equals(s2));

Is this true or false? The answer is false.

First the S1 variable refers to the string "abc" and then StringBuffer s2 = new StringBuffer (S1). A new StringBuffer object called the Append () method returns itself.

Call the Equals method of string. The point is that the Equals method has a instance of, which must be the same type to be compared otherwise directly return false.


Take a look at the source code:

/** * Compares ThisString to the specified object. The result is{@code*true}if  andOnlyifThe argument is  not{@code NULL} and  isA@code* String} object that represents the same sequence ofCharacters as This* object. *     *@paramAnObject * The object to compare This{@codeString} against * *@return{@code true}ifThe given object represents a {@codeString} * equivalent to ThisString, {@code false} otherwise * *@see  #compareTo (String)*@see  #equalsIgnoreCase (String)*/public Boolean equals (Object anobject) {if( This= = AnObject) {return true; }//The point is right here.if(AnObjectinstanceofString) {String anotherstring = (string) anobject; int n = value.length;if(n = = anotherString.value.length)                {char v1[] = value;                Char v2[] = Anotherstring.value; int i =0; while(n--! =0) {if(V1[i]! = V2[i])return false;                i++; }return true; }        }return false; }
1.3

How many objects does the following code produce in memory?
string S1 = new String ("abc");
String s2 = new String ("abc");

Answer: 3
With the above analysis. I believe everyone is clear, new two objects. Add an "ABC" in the String pool.

1.4

What is the result of the following code output?

String"abc";StringnewString("abc");s2.intern();System.out.println(s1 ==s2);

We may not be familiar with the intern () approach. First look at the gaze:

/** * Returns a canonical representation for  the stringObject. * <p> * A Pool ofstrings, initially empty, isMaintained privately by  the*class<code>string</code>. * <p> * When theIntern method isInvoked,if  thePool alreadycontainsAstring Equal  toThis <code>String</code> object asDetermined by* the{@link#equals (Object)} method, then the string from the pool is* Returned. Otherwise, this <code>String</code> object isAdded to  the* Pool and a reference  toThis <code>String</code> object isReturned. * <p> * It follows that  forAny strings <code>s</code> and<code>t</code>, * <code>s.intern () &nbsp;==&nbsp;t.intern () </code> is<code>true</code> *if  andOnlyif<code>s.equals(t) </code> is<code>true</code>. * <p> * all literal strings and string-valuedconstantExpressions is * interned. String literals is definedinchSection3.10. 5  of  the* <cite>the java&trade;     Language Specification</cite>. *     * @returnAstring  thatHas theSameContents  asThisstring, but  is* Guaranteed toBe fromPool A ofUnique strings. */Public native String intern ();

Staring at a lot of my grass, the key is the phrase: When the Intern method is invoked, if the pool already contains a string equal to this String object as deter Mined by
The {@link #equals (Object)} method, then the string from the pool is
Returned. Otherwise, this String object was added to the
Pool and a reference to this String object is returned.
Basically, assuming that the string does not exist in the constant pool, it creates one and returns the address. Otherwise, the address is returned directly.

The preceding code is the second line of string s2 = new String ("abc"); S2 actually refers to the object of new, although the Intern method is called in the third row, but is not assigned to S2, so the S2 reference remains unchanged. So return false.
Assuming that the third line of code is changed to S2 = S2.intern (), it returns true.

String"abc"StringnewString("abc"); s2 = s2.intern(); System.out.println(s1==s2);

All right, here we go today. The analysis will continue afterwards.

If you like my article, please follow me. All of you crossing's support is my greatest motivation!!

Java you may not know about the series 1

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.