简体   繁体   中英

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

第一个循环将创建10个不同的对象,第二个循环将仅具有一个对象,因为文字对象字符串在编译时仅创建一次,并且每次请求编译器都将返回相同的引用。

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

0,因为未使用字符串a,因此jvm将跳过语句

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

总共11个对象将在堆中创建10个,在字符串池中创建1个。

2,垃圾收集器将取出重复项,并且在每个for循环之后,没有一个

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM