Java Basics Chapter
Constants Interview Questions and Answers
Learn how Java constants work, from the final keyword and static final fields to blank final variables, compile-time constants, constant folding, and naming conventions.
Constants interview questions
Constants Interview Question 15 Questions
Click on any question to expand the answer.
Interview Answer
A constant is a named value that cannot be reassigned after initialization. In Java, constants are commonly declared using the final keyword, and shared class-level constants are usually declared static final. Strictly speaking, the Java Language Specification defines a constant variable as a final primitive or String variable initialized with a constant expression.
Key Points
- The final keyword prevents reassignment.
- static makes one value shared by all objects of the class.
- Constants are commonly written using uppercase names.
- Multiple words are separated using underscores.
- A constant should be initialized before it is used.
- Primitive and String compile-time constants may be embedded into compiled code.
Syntax
accessModifier static final dataType CONSTANT_NAME = value;Example
public class ApplicationConfig {
public static final int MAX_USERS = 100;
public static final String APPLICATION_NAME = "Java Portal";
public static void main(String[] args) {
System.out.println(APPLICATION_NAME);
System.out.println(MAX_USERS);
}
}Output
Java Portal
100Interview Tips
- Mention both final and static final when explaining constants.
- Explain that static final is the standard choice for class-wide constants.
- Remember that not every final variable is a compile-time constant.
Summary
A Java constant is commonly created using final so its value cannot be reassigned. Class-level constants are normally declared static final and named using uppercase letters.
Interview Answer
The final keyword allows a variable to be assigned only once. For a primitive variable, the stored value cannot change after assignment; for a reference variable, the reference cannot point to another object, although the referenced object may still be mutable. Both static and instance fields can be declared final.
Key Points
- A final variable can be assigned only once.
- A final variable may be initialized during declaration.
- A blank final instance field may be initialized in a constructor.
- final prevents reference reassignment, not object modification.
- static final is commonly used for shared constants.
- final can also be applied to methods and classes for different purposes.
Syntax
final int minimumAge = 18;
static final double TAX_RATE = 0.18;Example
import java.util.ArrayList;
import java.util.List;
public class FinalKeywordExample {
private static final int MAX_ATTEMPTS = 3;
public static void main(String[] args) {
final int minimumAge = 18;
final List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
System.out.println(minimumAge);
System.out.println(MAX_ATTEMPTS);
System.out.println(languages);
}
}Output
18
3
[Java, Python]Interview Tips
- Do not say that a final reference makes an object immutable.
- Explain that final controls assignment to the variable.
- Distinguish final variables from final methods and final classes.
Summary
The final keyword prevents a variable from being assigned another value after initialization. With object references, it fixes the reference but does not automatically protect the object’s internal state.
Interview Answer
A literal is a fixed value written directly in source code, such as 100, true, or "Java". A variable is a named storage location whose value may change, while a constant is a final variable that cannot be reassigned after initialization. In the declaration final int MAX_USERS = 100, MAX_USERS is the constant and 100 is the literal.
Key Points
- A literal is an unnamed value written directly in code.
- A variable stores a value under a name.
- A variable can normally be reassigned.
- A constant is declared using final.
- Constants improve readability by replacing unexplained literal values.
- A literal may initialize either a variable or a constant.
Syntax
int variableName = literal;
final int CONSTANT_NAME = literal;Example
public class ValueDifference {
public static void main(String[] args) {
int currentUsers = 50;
final int MAX_USERS = 100;
currentUsers = 75;
System.out.println(currentUsers);
System.out.println(MAX_USERS);
}
}Output
75
100Interview Tips
- Use one declaration to explain all three concepts.
- Do not describe a literal as a variable.
- Mention that the literal has no identifier of its own.
- Explain that final prevents reassignment of the constant.
Summary
A literal is a direct value, a variable is a named value that may change, and a constant is a final variable that cannot be reassigned. Constants often receive their initial values from literals.
Interview Answer
final is a keyword used to restrict reassignment, inheritance, or method overriding. finally is an exception-handling block that normally executes when a try statement exits and is generally used for cleanup logic. finalize() is an Object method associated with the obsolete finalization mechanism; finalization is deprecated for removal and should not be used for resource management.
Key Points
- A final variable can be assigned only once.
- A final method cannot be overridden.
- A final class cannot be extended.
- A finally block is associated with try and catch.
- finally usually executes whether an exception occurs or not.
- finalize() is deprecated for removal because of security, reliability, and performance problems.
Example
public class FinalFinallyExample {
public static void main(String[] args) {
final int MAX_ATTEMPTS = 3;
try {
System.out.println("Maximum attempts: " + MAX_ATTEMPTS);
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException exception) {
System.out.println("Division failed");
} finally {
System.out.println("Execution completed");
}
}
}Output
Maximum attempts: 3
Division failed
Execution completedInterview Tips
- State that these three terms are unrelated despite their similar names.
- Describe final as a keyword and finally as a block.
- Describe finalize() as a deprecated method, not a reliable cleanup mechanism.
- Prefer try-with-resources for closing files, streams, and similar resources.
Summary
final applies restrictions to variables, methods, and classes, while finally supports exception-handling cleanup. finalize() belongs to the deprecated finalization mechanism and should be avoided in modern Java.
Interview Answer
An instance constant is a final non-static field, so every object has its own assigned value. A static constant is declared static final and has one shared value associated with the class. A local constant is a final variable declared inside a method, constructor, or block and is available only within that scope. Java permits both instance and static fields to be declared final, and local variables may also use the final modifier.
Key Points
- An instance constant belongs to an individual object.
- Different objects may initialize instance constants with different values.
- A static constant belongs to the class.
- Only one static constant field is shared by all instances.
- A local constant exists only within its declaring scope.
- Local constants cannot use the static modifier.
Syntax
final int instanceConstant;
static final int STATIC_CONSTANT = 100;
final int localConstant = 10;Example
public class Product {
private final int productId;
private static final double TAX_RATE = 0.18;
public Product(int productId) {
this.productId = productId;
}
public void displayDetails() {
final String CATEGORY = "Electronics";
System.out.println("Product ID: " + productId);
System.out.println("Tax rate: " + TAX_RATE);
System.out.println("Category: " + CATEGORY);
}
public static void main(String[] args) {
Product firstProduct = new Product(101);
Product secondProduct = new Product(102);
firstProduct.displayDetails();
secondProduct.displayDetails();
}
}Output
Product ID: 101
Tax rate: 0.18
Category: Electronics
Product ID: 102
Tax rate: 0.18
Category: ElectronicsInterview Tips
- Explain the difference using ownership and scope.
- Mention that instance final fields are commonly initialized by constructors.
- Use static final for values shared across every object.
- Do not call every final object field a compile-time constant.
Summary
Instance constants belong to individual objects, static constants are shared at class level, and local constants exist within methods or blocks. Their main differences are ownership, lifetime, initialization, and scope.
Interview Answer
Java constants are commonly declared static final because final prevents reassignment, while static creates one class-level value shared by all objects. This avoids creating a separate copy for every instance and allows the constant to be accessed using the class name.
Key Points
- final allows the variable to be assigned only once.
- static associates the constant with the class rather than an object.
- Only one shared field exists for the class.
- Objects do not need separate copies of the same constant.
- Static constants can be accessed without creating an object.
- Compile-time constants may be inlined by the compiler.
Syntax
public static final dataType CONSTANT_NAME = value;Example
public class ApplicationLimits {
public static final int MAX_LOGIN_ATTEMPTS = 3;
public static void main(String[] args) {
System.out.println(ApplicationLimits.MAX_LOGIN_ATTEMPTS);
}
}Output
3Interview Tips
- Explain the purpose of both static and final separately.
- Mention that static final is appropriate for values shared by every object.
- Do not assume every static final field is a compile-time constant.
- Access static constants through the class name.
Summary
The static modifier creates one class-level field, while final prevents reassignment. Their combination is ideal for values that should remain fixed and shared throughout the application.
Interview Answer
Java constants are normally named using uppercase letters, with underscores separating multiple words. The name should clearly describe the meaning of the value rather than its data type or implementation. This convention makes constants easy to distinguish from regular variables.
Key Points
- Use uppercase letters for constant names.
- Separate multiple words with underscores.
- Choose descriptive and meaningful names.
- Avoid unexplained abbreviations.
- Do not begin names with digits.
- Follow normal Java identifier rules.
- Keep related constants inside an appropriate class or enum.
Syntax
public static final int MAX_RETRY_COUNT = 3;
public static final String DEFAULT_LANGUAGE = "English";Example
public class ServerConfig {
public static final int DEFAULT_PORT = 8080;
public static final int CONNECTION_TIMEOUT_SECONDS = 30;
public static void main(String[] args) {
System.out.println(DEFAULT_PORT);
System.out.println(CONNECTION_TIMEOUT_SECONDS);
}
}Output
8080
30Interview Tips
- Prefer MAX_CONNECTIONS over MAX or NUMBER.
- Avoid camelCase names for public static final constants.
- Use names that describe business meaning, not only the stored value.
- Remember that naming conventions improve readability but are not compiler rules.
Summary
Java constants should use descriptive uppercase names with words separated by underscores. Consistent naming helps developers identify fixed values quickly.
Interview Answer
A final variable cannot be assigned a new value after it has been initialized. For a primitive variable, the primitive value remains fixed. For a reference variable, the reference cannot point to another object, but the existing object may still be modified if it is mutable.
Key Points
- A final variable can be assigned only once.
- Reassigning a final primitive causes a compilation error.
- Reassigning a final reference also causes a compilation error.
- final does not automatically make an object immutable.
- Mutable object contents can still be changed.
- The variable must be definitely assigned before it is used.
Example
import java.util.ArrayList;
import java.util.List;
public class FinalVariableExample {
public static void main(String[] args) {
final int MAX_USERS = 100;
final List<String> users = new ArrayList<>();
users.add("Amit");
users.add("Neha");
System.out.println(MAX_USERS);
System.out.println(users);
}
}Output
100
[Amit, Neha]Interview Tips
- Distinguish variable reassignment from object mutation.
- Do not say that final makes every referenced object immutable.
- Mention that immutable objects such as String cannot change internally.
- Explain that final applies to the variable, not automatically to the object.
Summary
A final variable cannot be reassigned after initialization. However, an object referenced by a final variable may still change when the object itself is mutable.
Interview Answer
A blank final variable is a final variable declared without an initial value. A blank final instance field must be initialized exactly once in an instance initializer or in every constructor. This allows each object to receive a different fixed value during creation.
Key Points
- A blank final variable has no value at its declaration.
- It must be assigned exactly once.
- An instance blank final field can be initialized in a constructor.
- Every constructor must ensure that the field is initialized.
- It may also be assigned in an instance initializer block.
- Using it before definite assignment causes a compilation error.
- It is useful for immutable object properties.
Syntax
private final dataType variableName;
public ClassName(dataType value) {
this.variableName = value;
}Example
public class Employee {
private final int employeeId;
private final String employeeName;
public Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
public void display() {
System.out.println(employeeId);
System.out.println(employeeName);
}
public static void main(String[] args) {
Employee employee = new Employee(101, "Rahul");
employee.display();
}
}Output
101
RahulInterview Tips
- Mention that blank final fields support constructor-based initialization.
- State that every constructor must initialize the field.
- Explain that the value may differ between objects.
- Do not confuse a blank final field with a default-initialized normal field.
Summary
A blank final variable is declared without an initial value but must be assigned exactly once before use. Instance blank final fields are usually initialized through constructors.
Interview Answer
A static blank final variable is a class-level final field declared without an initializer. It must be assigned exactly once in a static initializer block because constructors initialize objects, not class-level fields. Its value is shared by every object of the class.
Key Points
- It is declared using static final without an initial value.
- It belongs to the class rather than individual objects.
- It must be initialized in a static initializer block.
- It cannot be initialized in a constructor.
- It must be assigned exactly once.
- It is useful when the value requires runtime calculation or configuration.
- The static initializer executes when the class is initialized.
Syntax
private static final dataType CONSTANT_NAME;
static {
CONSTANT_NAME = value;
}Example
public class RuntimeConfiguration {
private static final int PROCESSOR_COUNT;
static {
PROCESSOR_COUNT = Runtime.getRuntime().availableProcessors();
}
public static void main(String[] args) {
System.out.println(PROCESSOR_COUNT > 0);
}
}Output
trueInterview Tips
- State that static blank final fields are initialized during class initialization.
- Do not initialize them inside constructors.
- Use them when the value is unavailable at compile time.
- Distinguish runtime constants from compile-time constants.
Summary
A static blank final variable is a shared class field declared without an initial value. It must be assigned exactly once in a static initializer block before the class uses it.
Interview Answer
A final primitive variable stores a value that cannot be changed after initialization. A final reference variable stores an object reference that cannot be reassigned to another object. However, the object referenced by a final variable may still be modified if it is mutable.
Key Points
- A final primitive value cannot be reassigned.
- A final reference cannot point to another object.
- final applies to the variable, not directly to the object.
- Mutable objects can still change internally.
- Immutable objects cannot change after creation.
- Reassigning either type causes a compilation error.
Syntax
final int MAX_ATTEMPTS = 3;
final StringBuilder message = new StringBuilder("Java");Example
public class FinalVariableDemo {
public static void main(String[] args) {
final int MAX_ATTEMPTS = 3;
final StringBuilder message = new StringBuilder("Java");
message.append(" Constants");
System.out.println(MAX_ATTEMPTS);
System.out.println(message);
}
}Output
3
Java ConstantsInterview Tips
- Explain value fixation for primitives and reference fixation for objects.
- Do not say that a final reference makes the object immutable.
- Distinguish object mutation from reference reassignment.
- Use an immutable class when the object itself must not change.
Summary
A final primitive keeps its stored value fixed, while a final reference keeps its object reference fixed. The referenced object can still change when it is mutable.
Interview Answer
Yes, the internal state of an object referenced by a final variable can be modified if the object is mutable. The final keyword prevents the variable from referencing a different object, but it does not prevent method calls or changes to the existing object. Immutability must be provided by the object’s class design.
Key Points
- final prevents reference reassignment.
- It does not automatically prevent object mutation.
- Collection elements can be added, removed, or updated.
- Mutable fields inside the object may still change.
- Immutable objects cannot be modified after creation.
- Unmodifiable views may still differ from truly immutable objects.
Example
import java.util.ArrayList;
import java.util.List;
public class FinalReferenceExample {
public static void main(String[] args) {
final List<String> technologies = new ArrayList<>();
technologies.add("Java");
technologies.add("Spring Boot");
technologies.set(0, "Core Java");
System.out.println(technologies);
}
}Output
[Core Java, Spring Boot]Interview Tips
- Use a mutable collection to demonstrate the difference clearly.
- State that assigning a new ArrayList to technologies would not compile.
- Do not confuse final with immutable or unmodifiable.
- Mention defensive copying when designing immutable classes.
Summary
The state of a mutable object referenced by a final variable can be changed. Only the reference itself is protected from reassignment.
Interview Answer
A compile-time constant is a final primitive or String variable initialized with a constant expression that the compiler can evaluate during compilation. A runtime constant is assigned using a value calculated while the program is running, such as a method result, constructor argument, or configuration value. Compile-time constants may be inlined into client bytecode, while runtime constants are accessed from their fields during execution.
Key Points
- Compile-time constants must use primitive types or String.
- They must be declared final.
- Their initializer must be a constant expression.
- Runtime constants may be initialized in constructors or initializer blocks.
- Method calls do not produce compile-time constant expressions.
- Compile-time constants may be copied into dependent class files.
Syntax
public static final int MAX_USERS = 100;
public static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();Example
public class ConstantTypes {
private static final int MAX_RETRIES = 3;
private static final int PROCESSOR_COUNT;
static {
PROCESSOR_COUNT = Runtime.getRuntime().availableProcessors();
}
public static void main(String[] args) {
System.out.println(MAX_RETRIES);
System.out.println(PROCESSOR_COUNT > 0);
}
}Output
3
trueInterview Tips
- Do not classify every static final field as a compile-time constant.
- Check the data type and initializer expression.
- Mention inlining when explaining compile-time constants.
- Explain that changing an inlined public constant may require recompiling dependent classes.
Summary
Compile-time constants are fully evaluated by the compiler and may be inlined. Runtime constants remain fixed after assignment but receive their values during program execution.
Interview Answer
Constant folding allows the Java compiler to evaluate constant expressions during compilation instead of calculating them repeatedly at runtime. Constant propagation allows references to compile-time constant variables to be replaced with their known values in eligible expressions. The JVM’s Just-In-Time compiler may perform additional runtime optimizations beyond those performed by javac.
Key Points
- Constant expressions are evaluated during compilation.
- Arithmetic operations on constant values may be folded.
- String concatenation involving constants may be computed in advance.
- Compile-time constant variables may be inlined.
- Method calls are generally not compile-time constant expressions.
- JIT compilation can perform additional runtime optimizations.
Example
public class ConstantOptimization {
private static final int BASE = 10;
private static final int MULTIPLIER = 5;
private static final int RESULT = BASE * MULTIPLIER + 20;
private static final String MESSAGE = "Java" + " Constants";
public static void main(String[] args) {
System.out.println(RESULT);
System.out.println(MESSAGE);
}
}Output
70
Java ConstantsInterview Tips
- Explain folding as calculation and propagation as value substitution.
- Mention that javac can store the computed result directly in bytecode.
- Do not assume that every final value is eligible for constant folding.
- Distinguish compile-time optimization from JIT runtime optimization.
Summary
Constant folding computes constant expressions during compilation, while constant propagation substitutes known constant values where permitted. These optimizations reduce unnecessary runtime calculations.
Interview Answer
Common mistakes include treating every final variable as a compile-time constant, using mutable objects as constants, declaring shared values without static, and exposing mutable public fields. Developers also sometimes hard-code unexplained values or change public compile-time constants without recompiling dependent applications. These issues can be avoided through proper encapsulation, immutability, naming, and type selection.
Key Points
- Not every final variable is a compile-time constant.
- A final reference does not make its object immutable.
- Shared constants should normally be static final.
- Public mutable collections should not be exposed directly.
- Constant names should use uppercase letters and underscores.
- Frequently changing configuration should not be compiled as a constant.
- Dependent classes may contain inlined copies of public constants.
Example
import java.util.List;
public final class ApplicationConstants {
public static final int MAX_LOGIN_ATTEMPTS = 3;
public static final String DEFAULT_LANGUAGE = "English";
private static final List<String> SUPPORTED_LANGUAGES =
List.of("English", "Marathi", "Hindi");
private ApplicationConstants() {
throw new AssertionError("Constants class cannot be instantiated");
}
public static List<String> getSupportedLanguages() {
return SUPPORTED_LANGUAGES;
}
public static void main(String[] args) {
System.out.println(MAX_LOGIN_ATTEMPTS);
System.out.println(DEFAULT_LANGUAGE);
System.out.println(getSupportedLanguages());
}
}Output
3
English
[English, Marathi, Hindi]Interview Tips
- Prefer immutable values for public constants.
- Keep mutable implementation details private.
- Store environment-specific values in configuration files instead of constants.
- Recompile dependent classes after changing an inlined public constant.
- Avoid creating a constants class containing unrelated application values.
Summary
Correct constant design requires more than adding static final. Use meaningful names, immutable values, proper encapsulation, and configuration mechanisms appropriate to how often the value changes.