I am facing a confusion hope anyone might answer. Please see the code below
for(int i = 0; i < 40; i++){
if(i < 20){ //Does this 20 here is initialized again and again
System.out.println("less than 20");
}else{
System.out.println("greater than 20");
}
}
So my question is: Does the 20 in i < 20 gets initialized to an integer again and again causing allocation of memory again and again or does java uses similar kind of concept like a STRING POOL it uses for string.
According to knowledge it takes memory, but I still want to be sure. The reason for that is:
I am working on a code which is too much performance intensive, hence I cannot add conditional code in it. Something like below
for(int p = 0; p < 10; p++){
if(p < 20){
System.out.println("ABC");
}
if(p < 20 && "SomeValue".equals("SomeValue")){
System.out.println("SomeValue");
}
if(p < 20 && "ABC".equals("ABC")){
System.out.println("ABCDEF");
}
}
so if the answer is yes that 20 is taking the memory then I can make the code something like below
int value = ("Coldrink".equals("coca cola"))?10:20;
for(int p = 0; p < 10; p++){
if(p < value){
System.out.println("ABC");
}
if(p < value && "SomeValue".equals("SomeValue")){
System.out.println("SomeValue");
}
if(p < value && "ABC".equals("ABC")){
System.out.println("ABCDEF");
}
}
as you can see the variable value is initialized once and I have put my own condition which might have some performance issue, but then I have reduced the memory consumption, which could make things even.
EDIT: Thanks @ T.J Crowder got my confusions cleared up. People who have the same issues please read the accepted answer as well as Click on this resource too