Saturday 11 November 2017

java - Is there difference between variable defined outside loop and inside loop?






Possible
Duplicate:

href="https://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop">Difference
between declaring variables before or in loop?






String
str;
for (int i = 0; i < 10; i++) {
str = "Hello, World"; // Is
str created only 1
time?

}


What
is difference between above and below?
And if they are different, which one is
better?



for (int i = 0; i < 10;
i++) {
String str = "Hello, World"; // Is str created 10
times?
}



Answer




If you didn't write up your example with a
string literal, which is basically a singleton constant, then the answer would be that
in both cases 10 objects are created. In your specific example, no objects
are created
.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...