Why is the String class declared final in Java?
It is very useful to have strings implemented as immutable objects. You should read about immutability to understand more about it.
One advantage of immutable objects is that
You can share duplicates by pointing them to a single instance.
(from here).
If String were not final, you could create a subclass and have two strings that look alike when "seen as Strings", but that are actually different.
Why is String class final?
String is an immutable class which means if you cannot modify its state after you create it. If you could modify a string after it has entered another library, or a Map for instance the result would be unpredictable.
One mistake of the Java API is that BigInteger
and BigDecimal
are not final which means you need to perform a defensive copy of these objects when receiving them from non trusted code. Conversely, you can always trust that a String
will remain consistent.
Untrustworthy BigInteger:
public class DestructiveBigInteger extends BigInteger {
public DestructiveBigInteger(String value) {
super(value);
}
public BigInteger add(BigInteger val) {
return BigInteger.ONE; // add() method does not behave correctly
}
public BigInteger subtract(BigInteger val) {
throw new UnsupportedOperationException("subtract is broken");
}
}
The same thing is not possible with String
. As stated in Effective Java, you need to make defensive copies of these types of objects:
public void setValue(BigInteger value) {
this.value = new BigInteger(value.toByteArray());
}
What is the point of final class in Java?
First of all, I recommend this article: Java: When to create a final class
If they do, when do they use it so I can understand it better and know when to use it.
A final
class is simply a class that can't be extended.
(It 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?
If Java is object oriented, and you declare a class
final
, doesn't it stop the idea of class having the characteristics of objects?
In some sense yes.
By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)
final String class vs final methods of Non-final String class
Final classes cannot be extended.
Non final classes with final methods, can be extended (new methods can be added in subclasses) but the the existing final methods cannot be overridden.
Does it make sense to define a final String in Java?
The String
object is immutable but what it is is actually a reference to a String
object which could be changed.
For example:
String someString = "Lala";
You can reassign the value held by this variable (to make it reference a different string):
someString = "asdf";
However, with this:
final String someString = "Lala";
Then the above reassignment would not be possible and would result in a compile-time error.
String and Final
final
in this context means that the variable name
can only be assigned once. Assigning a different String
object to it again results in a compile error.
I think the source of the confusion here is that the final
keyword can be used in several different contexts:
- final class: The class cannot be subclassed.
- final method: The method cannot be overridden.
- final variable: The variable can only be assigned once.
See the Wikipedia article on final in Java for examples on each case.
Why String is immutable or final in Java
It is mainly for security reasons. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable
Immutability of String
solves some synchronization issues, it makes the String
thread safe
To support StringPool facility
To cache the hashcode
of String
To support class loading mechanism in which String
is used as arguments. String being mutable results in wrong class being loaded
How does the final keyword in Java work? (I can still modify an object.)
You are always allowed to initialize a final
variable. The compiler makes sure that you can do it only once.
Note that calling methods on an object stored in a final
variable has nothing to do with the semantics of final
. In other words: final
is only about the reference itself, and not about the contents of the referenced object.
Java has no concept of object immutability; this is achieved by carefully designing the object, and is a far-from-trivial endeavor.
When to use final keyword before a class?
A final
class cannot be subclassed. This is done for reasons of security and efficiency. Some of the classes in Java API are final
, for example java.lang.System. Sometimes security and immutability is of far more importance than re usability.
According to this IBM developerWorks article :
The common perception is that declaring classes or methods final makes it easier for the compiler to inline method calls, but this perception is incorrect (or at the very least, greatly overstated).
final classes and methods can be a significant inconvenience when programming -- they limit your options for reusing existing code and extending the functionality of existing classes. While sometimes a class is made final for a good reason, such as to enforce immutability, the benefits of using final should outweigh the inconvenience. Performance enhancement is almost always a bad reason to compromise good object-oriented design principles, and when the performance enhancement is small or nonexistent, this is a bad trade-off indeed.
Also read this Open Closed Principle:
Software Entities (Classes, Modules, Functions, etc.) should be open for Extension, but closed for Modification.
when exactly are we supposed to use public static final String ?
final
indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.
Use public final static String
when you want to create a String
that:
- belongs to the class (
static
: no instance necessary to use it), that - won't change (
final
), for instance when you want to define aString
constant that will be available to all instances of the class, and to other objects using the class, and that - will be a publicly accessible part of the interface that the class shows the world.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)
Similarly:
public static final int ERROR_CODE = 127;
It isn't required to use final
, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.
Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final
: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.
Furthermore using final
may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
Finally note that final
will only make truly constant values out of primitive types, String
which is immutable, or other immutable types. Applying final
to an object (for instance a HashMap
) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.
Related Topics
Does Python Have an Equivalent to Java Class.Forname()
How to Connect to Ftps Server with Data Connection Using Same Tls Session
Cannot Issue Data Manipulation Statements with Executequery()
Java Method to Swap Primitives
Exception in Thread "Main" Java.Lang.Noclassdeffounderror: Org/Openqa/Selenium/Webdriver
How to Add a Shortcut Key for a Jbutton in Java
Comparing Two Integer Arrays in Java
How to Store More Than One String in a Map
Creating an Array of Objects in Java
Do Interfaces Inherit from Object Class in Java
What Does Statement.Setfetchsize(Nsize) Method Really Do in SQL Server Jdbc Driver
Generate All Combinations from Multiple Lists
Relationship Between Hashcode and Equals Method in Java
Java Split() Method Strips Empty Strings at the End
Should One Call .Close() on Httpservletresponse.Getoutputstream()/.Getwriter()