Akku
Akku

Reputation: 29

Inside for-loop, how many objects will be created in java?

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

Answers (6)

Vivek Swansi
Vivek Swansi

Reputation: 419

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

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

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

Upvotes: 0

niemar
niemar

Reputation: 642

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

Upvotes: 0

Malay Shah
Malay Shah

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

NiVeR
NiVeR

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

petacreepers23
petacreepers23

Reputation: 184

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

Upvotes: -1

Related Questions