Java Core: data type for variable of changing value

it's a bit of a nooby question, but say I've got a variable that keeps getting re-initialized within a loop, what would be the best data-type to store that data temporarily?

for example:

String value = "";
while(file.hasNext()){
   value = file.readLine();
}

The reason I ask is that I know that Strings are immutable, which suggests that there is a more efficient alternative, am I right?

Jon Skeet
people
quotationmark

The reason I ask is that I know that Strings are immutable, which suggests that there is a more efficient alternative, am I right?

Nope. You're calling readLine multiple times, that's going to give you a different string reference each time. Just because the string content itself can't be changed doesn't mean that it's inefficient to change the value of a String variable. That variable value is just a reference... it's not like it's going to copy the string content on each iteration.

Do you even need the variable to be declared in the loop? Generally, I prefer to declare variables with the narrowest scope possible:

while (file.hasNext()) {
    String line = file.readLine();
    // Use line here
}

people

See more on this question at Stackoverflow