Why use the `transient` keyword in java? [duplicate]

transient variables are never serialized in java.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be ‘serialized’. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

please have a look at what serialization is.? and also refer this

Example

public class Foo implements Serializable
{
  private String saveMe;
  private transient String dontSaveMe;
  private transient String password;
  //...
}

In above example dontSaveMe & password are never get serialize as they are declare as a transient variables.

Leave a Comment