Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the effect of static final transient in Java?

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?

like image 232
wvdz Avatar asked Jan 29 '16 11:01

wvdz


People also ask

What is the impact of static final keyword with transient keyword?

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.

Can transient variables be static?

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.

Can we use transient with static variable in Java?

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.

What happens to static variables during serialization?

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.


1 Answers

A static field is implicitly transient (when serializing a static field, its value will be lost anyway). So indeed, no need to declare both.

like image 154
Gaël J Avatar answered Oct 15 '22 07:10

Gaël J