Interview Q&A · Java · 4 questions in this topic
transient Fields and Type Conversion — Java Interview Q&A
Fields excluded from serialization and the rules for converting values across types. Part of Objects, References & Memory · 294 questions in the Java bank.
What are transient variables?
Answer
A transient field is skipped by default Java serialization, so its value is not written to the stream. It is used for data that must not persist, such as passwords, or need not persist, such as caches and derived fields. After deserialization the field is restored to its type default, typically zero or null, and must be rebuilt if needed.
Example
public class Session implements java.io.Serializable { private String user; private transient String password; // never serialized private transient int cachedHash; // derived; recomputed later }
What is type conversion?
Answer
Type conversion assigns a value of one type to a variable of another type. Java divides it into widening conversion, which moves to a larger compatible type without loss, and narrowing conversion, which moves to a smaller type and needs an explicit cast. Understanding which direction applies tells you whether the compiler will accept the assignment as written.
Example
int a = 10; long b = a; // widening: automatic byte c = (byte) a; // narrowing: explicit cast
What is automatic (widening) conversion?
Answer
Automatic conversion happens when the source and destination types are compatible and the destination is larger, so no data can be lost. An int can be assigned directly to a long, float, or double without a cast. This widening path is applied by the compiler and never needs explicit syntax.
Example
int count = 100; long big = count; // automatic widening double approx = count; // automatic widening to double
What is narrowing conversion?
Answer
Narrowing conversion moves from a larger type to a smaller type, so it needs an explicit cast and may lose information through truncation or overflow. The cast syntax tells the compiler you accept that risk. Note that ClassCastException applies only to casts of object references, never to casts between primitive numbers.
Example
long big = 300L; byte small = (byte) big; // explicit cast; value wraps to 44 Object o = "hi"; String s = (String) o; // reference cast; wrong type would throw ClassCastException
💡 Primitive casts truncate silently; only reference casts can throw ClassCastException.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission