9

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?

wvdz
  • 16,251
  • 4
  • 53
  • 90
  • 1
    I assume that you are especially referring to the combination with `final`, so that http://stackoverflow.com/questions/4565653/java-static-transient-fields would not be a reasonable duplicate, right? – Andreas Fester Jan 29 '16 at 12:00
  • please have a look here :) [transient variables](http://stackoverflow.com/questions/910374/why-does-java-have-transient-variables) – Ruthi Ruth – Ruth Jan 29 '16 at 12:01
  • Who uses serialization anyway? Remove all transients ! :) – ZhongYu Jan 29 '16 at 12:05
  • My question is why you have these VERSION-variables. My guess is that they were hardcoded to "1.0" when the class was created, and then remained unchanged for the years after this. Remove the whole thing if you ask me. – Tobb Jan 29 '16 at 12:12
  • @Tobb: VERSION was just an example. It's basically used for all String constants – wvdz Jan 29 '16 at 12:13

3 Answers3

11

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

Gaël J
  • 11,274
  • 4
  • 17
  • 32
  • Would be great if you could add a source, but it looks like it's the correct answer anyway. – wvdz Jan 29 '16 at 12:22
  • 2
    When you say the value is lost, does the field be part of the serialization without a value(say null) or does the field never feature as a property ? – Biscuit Coder Sep 04 '17 at 07:36
2

The transient keyword on a variable will ensure that the variable is not part of the serialized object when serializing. If your class is not serializable, nor a JPA entity (which uses the transient keyword to avoid storing variables in the database), removing it should be fine.

Tobb
  • 11,850
  • 6
  • 52
  • 77
  • Most of these classes do implement Serializable – wvdz Jan 29 '16 at 12:16
  • Ok, as the other answer states, static members aren't serialized anyways. http://stackoverflow.com/questions/11000975/are-static-variables-serialized-in-serialization-process – Tobb Jan 29 '16 at 12:20
1

static members are associated with a class not with the object, hence on deserialization you will see the value you passed on, as opposed to the default values shown while using transient. To have a better understanding try to change the value of the variables after serialization and then on deserialization you will see that the values of serialized members are same but static one has changed. As per the transient final ,final variables do participate in serialization directly by thier values,hence no use of declaring a final variable as transient.