public class Employee implements java.io.Serializable
{
public String name;
public int transient id;
}
Suppose we are serializing ...
Employee e = new Employee();
e.name="REUBEN";
e.id=94731;
Now if I deserialize this then
System.out.println("Name: " + e.name); will give the o/p REUBEN
System.out.println("ID: " + e.id); will give the o/p 0
It is clear that as id
is transient
it was not sent to the output stream.
My question is, this zero is the default value of int
?
We are not saving the state so it is giving the output as 0
, but it is also a value. Shouldn't it be null
?
Yes, member variables of a class get their default values when they come into being (when they are created in a a JVM) hence the 0, which is the default value of the primitive int
type. If this is causing problems with "verifying" whether the ID was sent across or not, just use Integer
which would get the default value of null
(not that it should be a source of any confusion, just saying).
public class Employee implements java.io.Serializable
{
public String name;
public transient Integer id;
}
System.out.println("Name: " + e.name); will give the o/p REUBEN
System.out.println("ID: " + e.id); will give the o/p null
It can't be null, because int
is a primitive type. Instead, it receives the default value for the type, which is 0. It's always the "natural 0" of any type - null
for a reference type, 0 for numeric types, U+0000 for char
, and false
for boolean
. See section 4.12.5 of the Java Language Specification for more details.
Note that this is also the default value you get if you just declare an instance/static variable and read it before writing to it.
If you want to allow id
to be null, you need to make it an Integer
rather than an int
.
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