Can someone please tell me how many objects will be created on executing the System.out.println
statement in the below code
int i=0;
int j=1;
System.out.print("i value is "+ i + "j value is "+j);
concat() method takes concatenates two strings and returns a new string object only string length is greater than 0, otherwise, it returns the same object. + operator creates a new String object every time irrespective of the length of the string.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
Two objects are there in heap memory for each new operator and no objects would be created in the string constant pool as the ”Java” string is already present in the string pool constant. Hence you will see a total of 3 objects.
Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.
If you really want to know what's going on, why not look at the bytecode?
I wrapped your code in a main function, compiled it and then disassembled it with javap -c Test.class
. Here's the output (using a Oracle Java 7 compiler):
Compiled from "Test.java"
class Test {
Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iconst_1
3: istore_2
4: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
7: new #3 // class java/lang/StringBuilder
10: dup
11: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
14: ldc #5 // String i value is
16: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
19: iload_1
20: invokevirtual #7 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
23: ldc #8 // String j value is
25: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
28: iload_2
29: invokevirtual #7 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
32: invokevirtual #9 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
35: invokevirtual #10 // Method java/io/PrintStream.print:(Ljava/lang/String;)V
38: return
}
The only object that gets allocated in this method is the StringBuilder
(by the new
instruction at position 7). However, the other methods that are invoke
d might allocated something themselves, and I have a very strong suspicion that StringBuilder.toString will allocate a String
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With