No the reference cannot be change, but the data in that object can be changed.
In Java, when a reference variable is declared as final
, it means that the reference cannot be changed to point to a different object. However, the state of the object itself (i.e., the data within the object) can be modified if the object is mutable.
Here’s an example to illustrate:
public class Example {
public static void main(String[] args) {
final StringBuilder stringBuilder = new StringBuilder("Hello");
// This is allowed because we are modifying the internal state of the object, not changing the referencestringBuilder.append(” World”);
// This is not allowed, as it attempts to change the reference to point to a different object
// Uncommenting the line below will result in a compilation error
// stringBuilder = new StringBuilder(“New Object”);
System.out.println(stringBuilder.toString()); // Output: Hello World
}
}
In this example, stringBuilder
is declared as final
, so you cannot reassign it to a new StringBuilder
object. However, you can modify the content of the existing StringBuilder
object.
If you are dealing with an immutable object (e.g., String
), you cannot change its state, and therefore, you cannot modify the object itself, even if the reference is declared as final
.