String s = new String(“xyz”). How many objects has been made after this line of code execute?

前端 未结 20 2982
再見小時候
再見小時候 2020-11-27 02:45

The commonly agreed answer to this interview question is that two objects are created by the code. But I don\'t think so; I wrote some code to confirm.

publi         


        
相关标签:
20条回答
  • 2020-11-27 03:09
    public String(String original) {
        int size = original.count;
        char[] originalValue = original.value;
        char[] v;
        if (originalValue.length > size) {
            // The array representing the String is bigger than the new
            // String itself.  Perhaps this constructor is being called
            // in order to trim the baggage, so make a copy of the array.
            int off = original.offset;
            v = Arrays.copyOfRange(originalValue, off, off+size);
        } else {
            // The array representing the String is the same
            // size as the String, so no point in making a copy.
            v = originalValue;
        }
        this.offset = 0;
        this.count = size;
        this.value = v;
    }
    

    If we see the code , we can see it will just create a char[] and it will get copied every time with same content get instantiated and yes it will store data in String Constant Pool . 1)Will take from SCP String s1 = "a" String s2 = "a"; 2)Creates a new object String s3 = new String("a"); Curiosity , New Object String s2=new String("a"); In all above code same char[] will get copied.i:e char[] value You can check here

    0 讨论(0)
  • 2020-11-27 03:10

    @Giulio, You are right. String s3 = new String("abc"); creates two objects one in heap with reference s3 and another in SCP(Without reference). and now String s2 = "abc"; doesn't create any new object in SCP because "abc" is already there in SCP.

        String s1 = "abc";
        String s2 = "abc";
        String s3 = new String("abc");
        String s4 = s3.intern();
        System.out.println("s1: "+System.identityHashCode(s1));
        System.out.println("s2: "+System.identityHashCode(s2));
        System.out.println("s3: "+System.identityHashCode(s3));
        System.out.println("s4: "+System.identityHashCode(s4));
    

    O/P:s1: 366712642, s2: 366712642, s3: 1829164700, s4: 366712642

    As i am not eligible for commenting i wrote it here.

    0 讨论(0)
  • 2020-11-27 03:15

    I ran it in the Eclipse debugger. In that context, two objects are created, one with the id 17, the other 22:

    enter image description here

    0 讨论(0)
  • 2020-11-27 03:16

    If we execute String s = new String("Brajesh"); , two objects shall be created. One object will be created in string literal pool and another one in heap area. But if we have already same string literal object, then only one object is created. like

    String s1  ="Brajesh"; 
    String s = new String("Brajesh");//it will create only one object in heap area
    

    Apart from this one additional object is also created in heap area that is char[]'s object. I have attached here snapshot of heap memory.

    0 讨论(0)
  • 2020-11-27 03:16

    java.lang.String overrides the hashCode() method so that the value depends on the content of the string.

    As a result, hashCode() does not tell you anything about the number of instances. It may be the same string or may be another instance with no single byte shared. Same about equals(). This explains your output.

    Use System.identityHashCode(..) for this kind of research.

    And may the source be with you.

    0 讨论(0)
  • 2020-11-27 03:17
    1. String s = new String("xyz");

    The above line will create two object one is in heap and another is in String constant pool.

    now if we do this

    1. String s = new String("xyz");
    2. String s1 ="xyz";

    the above two statement will create two object. The first line String s = new String("xyz");will create two object as mentioned in 1st line and , When String s = "xyz";executes it checks in string constant pool if there is same content object is there or not, since the first line made an entry in string constant pool with "xyz" it returns the same reference and does not create other object.

    What if we have these four line together as mentioned bellow.

    1. String s2 = new String("xyz");
    2. String s3 ="xyz";
    3. String s4 = new String("xyz");
    4. String s5 ="xyz";

    If we execute the above line we will have three object.

    • The first and as mentioned will create two object one in heap and another in String constant poll.
    • When the second line executes it checks in the string constant poll
      and find with "xyz" so it returns the same object, so till second line we have two objects.
    • when the third line executes it will create a new object in the heap since new operator creates object in the heap so till third line will have 3 objects.
    • When the fourth line executes it checks in the string constant poll
      and find with "xyz" so it returns the same object, so fourth line we have three objects.

    Bonus about the intern() method

    When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    public class TestString {
    
        public static void main(String[] args) {
            String s1 = "Test";
            String s2 = "Test";
            String s3 = new String("Test");
            final String s4 = s3.intern();
            System.out.println(s1 == s2);
            System.out.println(s2 == s3);
            System.out.println(s3 == s4);
            System.out.println(s1 == s3);
            System.out.println(s1 == s4);
            System.out.println(s1.equals(s2));
            System.out.println(s2.equals(s3));
            System.out.println(s3.equals(s4));
            System.out.println(s1.equals(s4));
            System.out.println(s1.equals(s3));
        }
    
    }

    //Output
    true
    false
    false
    false
    true
    true
    true
    true
    true
    true

    See the magic of intern by applying intern method on new string object. intern is applied here so it will check if "Test" is available in String Constant pool or not since "Test" is available in String constant pool and it will return the same object so s3 has the same reference as s1 and s2 and will get all the result as true

    public class TestString {
    
        public static void main(String[] args) {
              String s1 = "Test";
    	        String s2 = "Test";
    	        String s3 = new String("Test").intern(); 
    	        final String s4 = s3.intern();
    	        System.out.println(s1 == s2);
    	        System.out.println(s2 == s3);
    	        System.out.println(s3 == s4);
    	       System.out.println(s1 == s3);
    	        System.out.println(s1 == s4);
    	        System.out.println(s1.equals(s2));
    	        System.out.println(s2.equals(s3));
    	        System.out.println(s3.equals(s4));
    	        System.out.println(s1.equals(s4));
    	        System.out.println(s1.equals(s3));
        }
    
    }

    true
    true
    true
    true
    true
    true
    true
    true
    true
    true

    0 讨论(0)
提交回复
热议问题