intellij - why serialversionuid is static in java

What is a serialVersionUID and why should I use it? (14)

Eclipse issues warnings when a serialVersionUID is missing.

The serializable class Foo does not declare a static final serialVersionUID field of type long

What is serialVersionUID and why is it important? Please show an example where missing serialVersionUID will cause a problem.

What is a serialVersionUID and why should I use it?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization.

Specifying one gives more control, though JVM does generate one if you don't specify. The value generated can differ between different compilers. Furthermore, sometimes you just want for some reason to forbid deserialization of old serialized objects [backward incompatibility], and in this case you just have to change the serialVersionUID.

The javadocs for Serializable say:

the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

Therefore, you must declare serialVersionUID because it give us more control.

This article has some good points on the topic.

serialVersionUID facilitates versioning of serialized data. Its value is stored with the data when serializing. When de-serializing, the same version is checked to see how the serialized data matches the current code.

If you want to version your data, you normally start with a serialVersionUID of 0, and bump it with every structural change to your class which alters the serialized data (adding or removing non-transient fields).

The built-in de-serialization mechanism (in.defaultReadObject()) will refuse to de-serialize from old versions of the data. But if you want to you can define your own readObject()-function which can read back old data. This custom code can then check the serialVersionUID in order to know which version the data is in and decide how to de-serialize it. This versioning technique is useful if you store serialized data which survives several versions of your code.

But storing serialized data for such a long time span is not very common. It is far more common to use the serialization mechanism to temporarily write data to for instance a cache or send it over the network to another program with the same version of the relevant parts of the codebase.

In this case you are not interested in maintaining backwards compatibility. You are only concerned with making sure that the code bases which are communicating indeed have the same versions of relevant classes. In order to facilitate such a check, you must maintain the serialVersionUID just like before and not forget to update it when making changes to your classes.

If you do forget to update the field, you might end up with two different versions of a class with different structure but with the same serialVersionUID. If this happens, the default mechanism (in.defaultReadObject()) will not detect any difference, and try to de-serialize incompatible data. Now you might end up with a cryptic runtime error or silent failure (null fields). These types of errors might be hard to find.

So to help this usecase, the Java platform offers you a choice of not setting the serialVersionUID manually. Instead, a hash of the class structure will be generated at compile-time and used as id. This mechanism will make sure that you never have different class structures with the same id, and so you will not get these hard-to-trace runtime serialization failures mentioned above.

But there is a backside to the auto-generated id strategy. Namely that the generated ids for the same class might differ between compilers (as mentioned by Jon Skeet above). So if you communicate serialized data between code compiled with different compilers, it is recommended to maintain the ids manually anyway.

And if you are backwards-compatible with your data like in the first use case mentioned, you also probably want to maintain the id yourself. This in order to get readable ids and have greater control over when and how they change.

As for an example where the missing serialVersionUID might cause a problem:

I'm working on this Java EE application that is composed of a Web module that uses an EJB module. The web module calls the EJB module remotely and passes a POJO that implements Serializable as an argument.

This POJO's class was packaged inside the EJB jar and inside it's own jar in the WEB-INF/lib of the web module. They're actually the same class, but when I package the EJB module I unpack this POJO's jar to pack it together with the EJB module.

The call to the EJB was failing with the Exception below because I hadn't declared its serialVersionUID:

Caused by: Mismatched serialization UIDs : Source
 = 04A3FEBED5DA4588 whereas Target (Rep. ID RMI:com.hordine.pedra.softbudget.domain.Budget:7AF5ED7A7CFDFF31:6227F23FA74A9A52)
 = 6227F23FA74A9A52

Don't bother, the default calculation is really good and suffice for 99,9999% of the cases. And if you run into problems, you can - as already stated - introduce UID's as the need arrise (which is highly unlikely)

Field data represents some information stored in the class. Class implements the Serializable interface, so eclipse automatically offered to declare the serialVersionUID field. Lets start with value 1 set there.

If you don't want that warning to come, use this:


First I need to explain the serialization.
Serialization allows to convert the object to stream,for sending that object over the network OR Save to file OR save into DB for letter usage.

There are some rules for serialization.

  • An object is serializable only if its class or its superclass implements the Serializable interface

  • An object is serializable (itself implements the Serializable interface) even if its superclass is not. However, the first superclass in the hierarchy of the serializable class, that does not implements Serializable interface, MUST have a no-arg constructor. If this is violated, readObject() will produce a in runtime

  • All primitive types are serializable.

  • Transient fields (with transient modifier) are NOT serialized, (i.e., not saved or restored). A class that implements Serializable must mark transient fields of classes that do not support serialization (e.g., a file stream).

  • Static fields (with static modifier) are Not serialized.

When Object is Serialized JAVA Runtime Associates the serial version number that is called the serialVersionID.

Where we need serialVersionID : During the deserialization to verify that sender and receiver are compatible with respect to serialization.If receiver loaded the class with different serialVersionID then deserialization will end with InvalidClassCastException.
A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long:.

Let's try this with an example.

public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String empname;
private byte empage;

public String getEmpName() {
    return name;
public void setEmpName(String empname) {
    this.empname = empname;
public byte getEmpAge() {
    return empage;
public void setEmpAge(byte empage) {
    this.empage = empage;

public String whoIsThis() {
    StringBuffer employee = new StringBuffer();
    employee.append(getEmpName()).append(" is ).append(getEmpAge()).append("
years old  "));
    return employee.toString();

Create Serialize Object

public class Writer {
public static void main(String[] args) throws IOException {
    Employee employee = new Employee();
    employee.setEmpAge((byte) 30);

    FileOutputStream fout = new 
    ObjectOutputStream oos = new ObjectOutputStream(fout);
    System.out.println("Process complete");

Deserializ the object

public class Reader {
public static void main(String[] args) throws ClassNotFoundException, 
IOException {
    Employee employee = new Employee();
    FileInputStream fin = new 
    ObjectInputStream ois = new ObjectInputStream(fin);
    employee = (Employee) ois.readObject();

NOTE: Now change the serialVersionUID of the Employee class and save:

private static final long serialVersionUID = **4L**;

And execute the Reader class. Not to execute the Writer class and you will get the exception.

Exception in thread "main"; local class incompatible: 
stream classdesc serialVersionUID = 1, local class serialVersionUID = 4

I generally use serialVersionUID in one context: When I know it will be leaving the context of the Java VM.

I would know this when I to use ObjectInputStream and ObjectOutputStream for my application or if I know a library/framework I use will use it. The serialVersionID ensures different Java VMs of varying versions or vendors will inter-operate correctly or if it is stored and retrieved outside the VM for example HttpSession the session data can remain even during a restart and upgrade of the application server.

For all other cases, I use


since most of the time the default serialVersionUID is sufficient. This includes Exception, HttpServlet.

If you get this warning on a class you don't ever think about serializing, and that you didn't declare yourself implements Serializable, it is often because you inherited from a superclass, which implements Serializable. Often then it would be better to delegate to such a object instead of using inheritance.

So, instead of

public class MyExample extends ArrayList<String> {

    public MyExample() {


public class MyExample {
    private List<String> myList;

    public MyExample() {
         this.myList = new ArrayList<String>();

and in the relevant methods call instead of (or (This does not fit in all cases, but still quite often.)

I often see people extending JFrame or such, when they really only need to delegate to this. (This also helps for auto-completing in a IDE, since JFrame has hundreds of methods, which you don't need when you want to call your custom ones on your class.)

One case where the warning (or the serialVersionUID) is unavoidable is when you extend from AbstractAction, normally in a anonymous class, only adding the actionPerformed-method. I think there shouldn't be a warning in this case (since you normally can't reliable serialize and deserialize such anonymous classes anyway accross different versions of your class), but I'm not sure how the compiler could recognize this.

If you will never need to serialize your objects to byte array and send/store them, then you don't need to worry about it. If you do, then you must consider your serialVersionUID since the deserializer of the object will match it to the version of object its classloader has. Read more about it in the Java Language Specification.

If you're serializing just because you have to serialize for the implementation's sake (who cares if you serialize for an HTTPSession, for instance...if it's stored or not, you probably don't care about de-serializing a form object), then you can ignore this.

If you're actually using serialization, it only matters if you plan on storing and retrieving objects using serialization directly. The serialVersionUID represents your class version, and you should increment it if the current version of your class is not backwards compatible with its previous version.

Most of the time, you will probably not use serialization directly. If this is the case, generate a default serializable uid by clicking the quick fix option and don't worry about it.

Original question has asked for 'why is it important' and 'example' where this Serial Version ID would be useful. Well I have found one.

Say you create a Car class, instantiate it, and write it out to an object stream. The flattened car object sits in the file system for some time. Meanwhile, if the Car class is modified by adding a new field. Later on, when you try to read (i.e. deserialize) the flattened Car object, you get the – because all serializable classes are automatically given a unique identifier. This exception is thrown when the identifier of the class is not equal to the identifier of the flattened object. If you really think about it, the exception is thrown because of the addition of the new field. You can avoid this exception being thrown by controlling the versioning yourself by declaring an explicit serialVersionUID. There is also a small performance benefit in explicitly declaring your serialVersionUID (because does not have to be calculated). So, it is best practice to add your own serialVersionUID to your Serializable classes as soon as you create them as shown below:

public class Car {
static final long serialVersionUID = 1L; //assign a long value

SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws in case of serialVersionUID mismatch

Read more:

This question is very well documented in Effective Java by Joshua Bloch. A very good book and a must read. I will outline some of the reasons below :

The serialization runtime comes up with a number called Serial version for each serializable class. This number is called serialVersionUID. Now there is some Math behind this number and it comes out based on the fields/methods that are defined in the class. For the same class the same version is generated every time. This number is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.

If the class is serializable you can also declare your own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long. Most IDE's like Eclipse help you generate that long string.

To understand the significance of field serialVersionUID, one should understand how Serialization/Deserialization works.

When a Serializable class object is serialized Java Runtime associates a serial version no.(called as serialVersionUID) with this serialized object. At the time when you deserialize this serialized object Java Runtime matches the serialVersionUID of serialized object with the serialVersionUID of the class. If both are equal then only it proceeds with the further process of deserialization else throws InvalidClassException.

So we conclude that to make Serialization/Deserialization process successful the serialVersionUID of serialized object must be equivalent to the serialVersionUID of the class. In case if programmer specifies the serialVersionUID value explicitly in the program then the same value will be associated with the serialized object and the class, irrespective of the serialization and deserialzation platform(for ex. serialization might be done on platform like windows by using sun or MS JVM and Deserialization might be on different platform Linux using Zing JVM).

But in case if serialVersionUID is not specified by programmer then while doing Serialization\DeSerialization of any object, Java runtime uses its own algorithm to calculate it. This serialVersionUID calculation algorithm varies from one JRE to another. It is also possible that the environment where the object is serialized is using one JRE (ex: SUN JVM) and the environment where deserialzation happens is using Linux Jvm(zing). In such cases serialVersionUID associated with serialized object will be different than the serialVersionUID of class calculated at deserialzation environment. In turn deserialization will not be successful. So to avoid such situations/issues programmer must always specify serialVersionUID of Serializable class.