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

前端 未结 20 3053
再見小時候
再見小時候 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:22

    There are two ways to create string objects in Java:

    1. Using the new operator, i.e.

      String s1 = new String("abc");
      
    2. Using a string literal, i.e.

      String s2 = "abc";
      

    Now string allocation is costly in both time and memory so the JVM (Java Virtual Machine) performs some tasks. WHAT TASKS?

    See, whenever you are using the new operator the object is created, and the JVM will not look in the string pool. It is just going to create the object, but when you are using the string literals for creating string objects then the JVM will perform the task of looking in the string pool

    I.e., when you write

    String s2 = "abc";
    

    the JVM will look in the string pool and check if "abc" already exists or not. If it exists then a reference is returned to the already existing string "abc" and a new object is not created and if it doesn't exists then an object is created.

    So in your case (a)

    String s1 = new String("abc");
    
    • Since new is used the object is created

    (b)

    String s2 = "abc";
    
    • using a string literal an object is created and "abc" is not in the string pool and therefore the object is created.

    (c)

    String s2 = "abc";
    
    • Again using a string literal and "abc" is in the string pool, and therefore the object is not created.

    You can also check it out by using the following code:

    class String_Check
    {
        public static void main(String[] n)
        {
            String s1 = new String("abc");
            String s2 = "abc";
            String s3 = "abc";
            if (s1==s2)
                System.out.println("s1==s2");
            if(s1==s3)
                System.out.println("s1==s3");
            if(s2==s3)
                System.out.println("s2==s3");
        }
    }
    

    I hope this helps... Note that == is used to see if the objects are equal and the equals(Object) method is used to see if content are equal.

提交回复
热议问题