In this code, Each time i am calling goodMethod(), it is going to use the unique object created in the Heap Space with static word.
MY QUESTION is : when i am calling badMethod(), is it going to create a new String object in the Heap Space each time i am calling this method ? So if i am calling my method 1_200_000 time, is it going to create 1_200_000 string object in the heap Space ?
There is no doubt that the first method is better (for readability and maintainability of code). I am only asking here about number of object created in memory
Thanks
I have read a lot about this on google but didn't find an response with argument or proof. Please also if you know how i can test this, thanks to share.
public class Main {
private static final String HELLO = "hello";
private static final String WORLD = "world";
public static void main(String[] args) {
for (int i = 0; i < 1_200_000; i++) {
goodMethod();
badMethod();
}
}
private static void goodMethod(){
System.out.println(HELLO);
System.out.println(WORLD);
}
private static void badMethod(){
System.out.println("hello");
System.out.println("world");
}
}
// an other example
Map<String, Object> map = new HashMap<>();
map.put("myKey", xxx.getYYY());
// somewhere else
map.put("myKey", zzz.getYYY());
// instead of :
private static final String MY_KEY = "myKey"
map.put(MY_KEY, xxx.getYYY());
map.put(MY_KEY, zzz.getYYY());
EDIT : I am not asking about concatenation, i have remove the concatenation from the sample code