Interview Q&A · Java · 4 questions in this topic

transient Fields and Type Conversion — Java Interview Q&A

All Java topics

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

Example.javajava
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

Example.javajava
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

Example.javajava
int count = 100;
long big = count; // automatic widening
 double approx = count; // automatic widening to double

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits