Java Questions 21 - 30  «Prev  Next»

Serialization, Volatile, and Enums in Java SE 25

These ten questions distinguish default serialization rules, field modifiers, and modern enum declarations.

  1. What does transient mean on a field?

    Answer: It excludes an instance field from the default serialized state used by Java object serialization. It does not erase the field at runtime, prevent normal access, or stop custom serialization code from writing the value explicitly.

    During ordinary Serializable deserialization, an omitted transient field starts with its default value unless custom restoration code assigns it. Static fields are class state and are not part of default instance serialization anyway. Transient is not a universal rule for JSON libraries, database mappings, or other frameworks, which define their own policies.

  2. What is serialization used for?

    Answer: It encodes data so it can be stored or transferred and reconstructed later. Java's built-in object serialization uses ObjectOutputStream and ObjectInputStream for eligible object graphs. Serializable is a marker interface; Externalizable is not merely a marker and requires explicit readExternal and writeExternal behavior.

    import java.io.*;
    
    public class TransientState {
        private static final class Data implements Serializable {
            @Serial private static final long serialVersionUID = 1L;
            String name = "Ada";
            transient String cache = "computed";
        }
        public static void main(String[] args) throws Exception {
            var bytes = new ByteArrayOutputStream();
            try (var output = new ObjectOutputStream(bytes)) {
                output.writeObject(new Data());
            }
            try (var input = new ObjectInputStream(
                    new ByteArrayInputStream(bytes.toByteArray()))) {
                input.setObjectInputFilter(ObjectInputFilter.Config.createFilter(
                        "maxdepth=4;maxrefs=20;maxbytes=4096;TransientState$Data;java.lang.String;!*"));
                Data restored = (Data) input.readObject();
                System.out.println(restored.name + " " + restored.cache);
            }
        }
    }

    This self-contained round trip prints Ada null. A filter limits permitted classes and graph resources. Avoid deserializing untrusted Java object streams without a carefully designed policy; serialization can invoke behavior during reconstruction. For interchange formats, an explicit data schema is often easier to evolve and validate.

  3. Can volatile be applied to static fields as well as instance fields?

    Answer: Yes. Volatile can modify either kind of field, but not ordinary local variables or parameters. It cannot be combined with final on the same field. A write to a volatile field happens-before a subsequent read of that field, supplying visibility and ordering.

    Volatile does not make compound operations such as count++ atomic. A volatile reference also does not make the referenced object's fields or array elements volatile. Use a lock or suitable atomic operation when an invariant requires several actions to occur together, rather than relying on a simplified “master memory copy” explanation.



  4. What does it mean for a member to be static?

    Answer: It belongs to the declaring class rather than to an individual instance. A static field has one variable per declaring class identity, not one per object. Class identity includes its defining class loader, so “one copy in the entire JVM” can be an oversimplification.

    No instance is needed for ordinary static access. However, class initialization follows specified triggers and is often delayed until active use; static does not mean all application classes are initialized at startup. Static mutable data also needs a concurrency policy when shared across threads.

  5. Where can an enum be declared in Java SE 25?

    Answer: An enum can be top-level, a member of a class or interface, or local within an allowed block such as a method body. Member and local enums are implicitly static. A local enum therefore does not capture surrounding local variables like an ordinary local inner class.

    An enum declaration cannot introduce its own type parameters or explicitly extend a different class. It can implement interfaces, including parameterized interfaces, and an enum type can be used as a generic type argument. The legacy bans on local enums and interface-member enums are incorrect for Java SE 25.


  6. How do you declare enum constants RED, BLUE, and GREEN?

    Answer: Use enum Color { RED, BLUE, GREEN }. A public top-level version normally belongs in Color.java. The constants are named instances of Color, not strings or integer aliases.

    import java.util.Arrays;
    
    public class LocalColors {
        public static void main(String[] args) {
            enum Color { RED, BLUE, GREEN }
            Color selected = Color.BLUE;
            System.out.println(selected);
            System.out.println(Arrays.toString(Color.values()));
        }
    }

    This legal local enum example prints BLUE and [RED, BLUE, GREEN]. No preview flags are required. If the enum declares additional fields or methods after its constants, separate that member section with a semicolon.

  7. What is the type of an enum constant?

    Answer: Its declared type is the enum type. Color.RED is a Color. A constant with a class body has an anonymous subclass as its runtime class, so getClass can differ between constants while getDeclaringClass identifies their common enum type.

    Use enum values directly in typed parameters, collections, and switches. Comparing two values of the same enum with == is appropriate. Avoid persisting ordinal values as stable business identifiers, because reordering constants changes those ordinal numbers.

  8. What is an enum in Java?

    Answer: It is a special class declaration defining a fixed set of named instances. It may also contain fields, constructors, methods, and interface implementations. Its superclass is the corresponding specialization of Enum.

    Enums are not merely lists of strings or integers. They support type-safe operations and can attach behavior to constants. Fields should generally be immutable unless shared mutable singleton state is intentional. EnumSet and EnumMap are useful collection implementations specialized for enum values.


  9. What does an enum's values method return?

    Answer: The implicitly declared static values method returns an array containing the enum constants in declaration order. For Color, its return type is Color[]. Changing the returned array does not change the enum's declared constants.

    Do not confuse values with the instance methods name or ordinal. Name returns the declared constant name; ordinal is its zero-based declaration position. ValueOf performs exact name lookup and throws IllegalArgumentException when no constant has that name.

  10. Can application code directly construct a new enum instance?

    Answer: No. An enum's instances are created for its declared constants during enum initialization. Code cannot write new Color(), and enum constructors cannot be public or protected. Reflection also does not provide a supported way to construct additional enum instances.

    Constants may supply constructor arguments, and an enum constructor can delegate to another constructor of the same enum using this. That internal constructor chaining is different from allowing ordinary callers to create additional values. An enum variable can still be null unless the application's contract excludes it.

References: Serializable, Serialization filters, Enum classes, and Memory-model rules.


SEMrush Software