0

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"; 
}
Akku
  • 29
  • 6

6 Answers6

1

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.

NiVeR
  • 9,644
  • 4
  • 30
  • 35
1

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).

Malay Shah
  • 412
  • 3
  • 9
0

0 because string a is not used so jvm will skip the statements

niemar
  • 612
  • 1
  • 7
  • 16
  • Not guaranteed. JVM won't necessarily push the analysis to the point that it knows that just calling the constructor of String will not have any effect if the resulting String is never used. It will typically do build the Strings even though not doing so would have the same result. I know in my tests, the JVM never tried to optimize that away. – kumesana Sep 27 '18 at 09:42
0
  1. String "abc" will be created and put into string pool
  2. String a = new String("abc") will find "abc" string in the string pool, create new object string and do not put it into string pool

Total 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"); 
}

  1. String "abc" will be created and put into string pool.
  2. 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"; 
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

Total 11 objects would be created 10 in heap and 1 in string pool.

Vivek Swansi
  • 409
  • 1
  • 4
  • 13
-1

2, garbage collector will take out the duplicates, and after each for loop, no one

petacreepers23
  • 164
  • 1
  • 9