In the code base I am working on, nearly all variables that are declared static final String
are also declared transient
.
So I have fields like:
public static final transient String VERSION = "1.0";
I am tempted to remove these transient
keywords whenever I spot them, because I think it doesn't serve any purpose.
Is there any difference in behaviour between using transient
or not in this case?
transient and static : Since static fields are not part of state of the object, there is no use/impact of using transient keyword with static variables.
The main difference between the two ( static versus transient ) is that static variables exist only once per transaction, but transient variables can exist many times. In other words, static variables have a global scope, while transient variables have a local scope.
The final variable in Java will be participated in the serialization directly by their values and hence declaring a final variable as transient there is no use. It is considered a good practice not to use static and transient together. Also, do not use transient and final together.
In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.
A static
field is implicitly transient
(when serializing a static
field, its value will be lost anyway). So indeed, no need to declare both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With