Counting String objects created by Java code

前端 未结 13 1688
失恋的感觉
失恋的感觉 2020-12-05 14:04

How many String objects are created by the following code?

String x = new String(\"xyz\");
String y = \"abc\";
x = x + y;

I have visited ma

相关标签:
13条回答
  • 2020-12-05 14:43

    The answer is 5

    1. xyz in non pool memory
    2. xyz in pool memory with no reference
    3. abc in pool memory with reference
    4. xyz still in non pool memory, reference changed to xyzabc in non pool memory
    5. xyzabc in pool memory with no reference
    0 讨论(0)
  • 2020-12-05 14:45

    Sometime it's better to let byte code speak Examining the code using JAVAP

    public static void main(java.lang.String[]);
        flags: ACC_PUBLIC, ACC_STATIC
        Code:
          stack=3, locals=3, args_size=1
             0: new           #16                 // class java/lang/String
             3: dup
             4: ldc           #18                 // String xyz
             6: invokespecial #20                 // Method java/lang/String."<init>":(Ljava/lang/String;)V
             9: astore_1
            10: ldc           #23                 // String abc
            12: astore_2
            13: new           #25                 // class java/lang/StringBuilder
            16: dup
            17: aload_1
            18: invokestatic  #27                 // Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
            21: invokespecial #31                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
            24: aload_2
            25: invokevirtual #32                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/St
    ringBuilder;
            28: invokevirtual #36                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
            31: astore_1
            32: return
          LineNumberTable:
            line 6: 0
            line 7: 10
            line 8: 13
            line 9: 32
          LocalVariableTable:
            Start  Length  Slot  Name   Signature
                   0      33     0  args   [Ljava/lang/String;
                  10      23     1     x   Ljava/lang/String;
                  13      20     2     y   Ljava/lang/String;
    }
    

    Now as seen form the code

    At `0: new` Creates a new String Object 
    At `3:dup` ; make an extra reference to the new instance
    
        At `4:ldc #18` as seen literal "xyz" has been placed in the pool (one string Object) 
    At `6: invokespecial;` ; now call an instance initialization method with parameter and creates a object in nonpool memory.
    At `9: astore_1` Stores the above reference in local variable 1(i.e x)
    

    So by this time we have two String object

    At `10:ldc #23` as seen literal "abc" has been placed in the pool (third string ) 
    
        At `12: astore_2` Stores the above reference in local variable (i.e y)
    

    so By this time we have three String Object

        28: invokevirtual #36 // Method java/lang/StringBuilder.toString:
    ()Ljava/lang/String;;(fourth String Object is Created)
    

    So we have total of four String Object in this code.

    As i'm new to programming and have started it learning only few months back point me if i went wrong somewhere and what is the correct version of it. Thanks :)

    0 讨论(0)
  • 2020-12-05 14:48

    By the end of the run there will be four String objects:

    1. A String that corresponds to the interned "xyz" literal
    2. Its copy created by new String("xyz")
    3. A String that corresponds to the interned "abc" literal
    4. A String that corresponds to concatenation "xyz" + "abc"

    The real question is attributing some or all of these objects to your program. One can reasonably claim that as few as two or as many as four Strings are created by your code. Even though there are four String objects in total, objects 1 and 3 may not necessarily be created by your code, because they are in a constant pool, so they get created outside your code's direct control.

    0 讨论(0)
  • 2020-12-05 14:48

    If you want to test for instances, run this code snippet and look at the output:

    import static java.lang.System.identityHashCode;
    
    public class Program {
        public static void main(String... args) {
            String x = new String("xyz");
            String y = "abc";
            String z = x + y;
    
            System.out.printf("x: %d | %d\n", identityHashCode(x), identityHashCode(x.intern()));
            System.out.printf("y: %d | %d\n", identityHashCode(y), identityHashCode(y.intern()));
            System.out.printf("z: %d | %d\n", identityHashCode(z), identityHashCode(z.intern()));
        }
    }
    

    I have the following output using jdk1.7.0_67:

    x: 414853995 | 1719175803
    y: 1405489012 | 1405489012
    z: 1881191331 | 1881191331

    That's a total of 4 String instances...

    0 讨论(0)
  • 2020-12-05 14:51

    1.objects created in heap area "xyz" //created by 'String x' and xyzabc //created by 'x+y'(concatenation)

    2.objects created in scp(string constant pool) "xyz" //created for future purpose which is not available for garbage collection and "abc" //created by 'String y' literal

    so total objects created in this case is 4

    0 讨论(0)
  • 2020-12-05 14:53

    new String(”xyz“) for sure creates a new instance. "abc" and "xyz" are stored in the class constant pool, x = x + y creates a StringBuilder under the hood and therefore creates a new String, so the count of strings are 4 here.


    The compiler might substitute x + y with a constant ("xyzabc"), though.

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