You are missunderstanding the concept of Immutability
.
An immutable object is an object with non-updatedable properties.
String line = "abcd";
What is not mutable is the char[]
into the String object. But you can reasign line
reference to another String later.
But there is also final references in java.
final String line = "abcd"
Final means you would never be able to change the reference of line
. And in this case, since String
is immutable as well, you won't be able to change the String value nor the String reference.
Immutable vs final
Immutable
Let's consider the following class.
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() { return this.name; }
}
As you can see, once a person instance has been initialized, there is no way to change his name, there is no setter, and a string value cannot be updated.
Owether, this code will work:
Person person = new Person("John");
person = new Person("Jack"); // of course, at this point John is lost
// But nothing prevent me from reassigning the person value.
When talking about immutablility, we are talker at the class level.
Final reference
Let's consider the following class.
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() { return this.name; }
public String setName(String name) { this.name = name; }
}
As you can see, once a person instance has been initialized, is still can change his name.
But if i declare my person instance as final, i won't be able to assign a new perso to this reference.
final Person person = new Person("John");
person = new Person("Jack"); // THIS WILL FAIL !!
// But i can update my person name if i want to, since the class is not immutable.
person.setName("Alice");
I hope this might help you.
What happen in your case
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// The value of line appears to be reset after each iteration
}
}
At each loop's round, you are reasigning the line
reference, not the line
value. This is why the text in line
change at each round, because the reference is updated.