Reputation: 29
How many object will created in below codes:
for (int i= 0;i<10; i++){
String a = new String("abc");
}
for (int i= 0;i<10; i++){
String a = "abc";
}
Upvotes: 0
Views: 389
Reputation: 419
Total 11 objects would be created 10 in heap and 1 in string pool.
Upvotes: 0
Reputation: 18245
"abc"
will be created and put into string poolString a = new String("abc")
will find "abc"
string in the string pool, create new object string and do not put it into string poolTotal 11 strings will be created and only one "abc"
will be put into string pool
for (int i= 0;i<10; i++){
String a = new String("abc");
}
"abc"
will be created and put into string pool.String a = "abc"
will find existed string "abc"
in the string pool and reference a
will be point to the same string object "abc"
.Total 1 string will be created put into string pool
for (int i= 0;i<10; i++){
String a = "abc";
}
Upvotes: 0
Reputation: 452
As answered in Difference between string object and string literal
In first for loop(since have used new String) 10 Objects will be created and In second for-loop only one object will be created and will be reused(as it will be stored in String pool).
Upvotes: 1
Reputation: 9786
First loop will create 10 different objects, the second one will have just one because the literal object string is created only once at compile-time and each time is requested the compiler will return the same reference.
Upvotes: 1
Reputation: 184
2, garbage collector will take out the duplicates, and after each for loop, no one
Upvotes: -1