Does Java replace an object if was the same name?

Does Java replace an object if was the same name? This question comes to my mind daily.

Example 1: If I create an object 500 million times with the same object name, Does Java will create 500 million objects or will replace it and stay there in 1 object?

for (int x = 0; x < 500000000; x++) {
    TestObject testObject = new TestObject();
}

Example 2: Which way is better to avoid creating new object every click

//Using this way?
List < ActivityManager.RunningServiceInfo > runningServiceInfoList = getRunningService();
activityMainBinding.activityMainConstraintLayout19.setOnClickListener(v - > {
    runningServiceInfoList.clear();
    runningServiceInfoList = getRunningService();
    if (...)
});

//Or this way?
activityMainBinding.activityMainConstraintLayout19.setOnClickListener(v - > {
    List < ActivityManager.RunningServiceInfo > runningServiceInfoList = getRunningService();
    if (...)
});

Answer

Does Java will create 500 million objects

It might create no objects at all, if escape analysis determines that it doesn’t need to, since it can just work with the field values on the heap instead.

Worrying about the number of objects created is worrying about things at the wrong level. Think about correctness first, speed later:

  • If TestObject is immutable, there is no reason to create it in the loop: you can create it inside the loop if you want, or move it outside and reuse the instance.

  • If TestObject is mutable, is there a risk that you will unintentionally leave state from previous iterations, which will corrupt the calculation in the current iteration? If so, unless creating a new TestObject is really expensive, just create new instances in the loop, because it’s then more obviously correct. The JVM is really good at optimizing the life cycle of short-lived objects.