Can we declare list as final?

4 Answers. You’re right that declaring the list final means that you cannot reassign the list variable to another object. This means that this class ( SomeClass ) and other classes in the same package can access the variable.

People also ask, can we declare ArrayList as final?

It doesn’t effect what you can do with the ArrayList as you rightfully observe – the ArrayList itself is still mutable. You have just made the reference immutable. But making a variable final does have other benefits: It prevents the variable from being changed if it is expected to stay constant.

Also, can object be final in Java? In Java, we know that String objects are immutable means we cant change anything to the existing String objects. final means that you can‘t change the object’s reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g).

Correspondingly, can final list be modified?

The final arrayList can still be modified, refer to the example below and run it to see for your self. As you can see, the main method is adding (modifying) the list. So the only thing to note is that the “reference” to the object of the collection type can‘t be re-assigned to another such object.

What is a final class in Java?

A final class is simply a class that can’t be extended. (This does not mean that all references to objects of the class would act as if they were declared as final .) When it’s useful to declare a class as final is covered in the answers of this question: Good reasons to prohibit inheritance in Java?

20 Related Question Answers

Similar Asks