Java Basics Chapter
Keywords Interview Questions and Answers
Learn how Java keywords work, from reserved and contextual keywords to access modifiers, final, static, abstract, exception-handling keywords, and common keyword mistakes.
Keywords interview questions
Keywords Interview Question 15 Questions
Click on any question to expand the answer.
Interview Answer
Keywords are predefined words that have special meanings in Java syntax. Reserved keywords cannot be used as names for variables, methods, classes, interfaces, or other identifiers because the compiler already uses them to recognize language constructs. Contextual keywords act as keywords only in specific grammatical contexts.
Key Points
- Keywords are part of Java’s language syntax.
- Examples include class, public, static, if, return, and new.
- Reserved keywords can never be used as identifiers.
- Contextual keywords have special meanings only in specific contexts.
- Keyword matching is case-sensitive.
- Public is not a keyword, while public is.
Interview Tips
- Explain the difference between reserved and contextual keywords.
- Do not classify true, false, or null as keywords.
- Mention that changing the letter case creates a different token.
Summary
Java keywords have predefined roles in the language grammar. Reserved keywords cannot be identifiers because the compiler must interpret them as language tokens.
Interview Answer
In Java SE 26, the Java Language Specification defines 51 reserved keywords and 17 contextual keywords, giving 68 keyword sequences in total. Reserved keywords are always treated as keywords, while contextual keywords are recognized as keywords only in particular parts of Java syntax.
Key Points
- Java SE 26 has 51 reserved keywords.
- It also has 17 contextual keywords.
- Reserved keywords cannot be used as identifiers.
- Contextual keywords may behave as identifiers outside restricted contexts.
- const and goto are reserved but currently unused.
- strictfp is obsolete and should not be used in new code.
- true, false, and null are literals, not keywords.
Interview Tips
- State the Java version when giving the keyword count.
- Avoid the outdated answer that Java always has 50 keywords.
- Mention both reserved and contextual keyword categories.
- Remember that underscore is a reserved keyword in modern Java.
Summary
Modern Java classifies keywords as reserved or contextual. Java SE 26 defines 51 reserved keywords and 17 contextual keywords.
Interview Answer
A keyword is a word with a special role in Java grammar, while a reserved keyword can never be used as an identifier. A literal is a direct value such as 10, true, 'A', "Java", or null. An identifier is a developer-defined name for a class, method, variable, package, or other program element.
Key Points
- Keywords define Java language constructs.
- Reserved keywords cannot be used as identifiers.
- Contextual keywords are special only in specific contexts.
- Literals represent fixed values directly in source code.
- Identifiers provide names to program elements.
- true and false are boolean literals.
- null is the null literal.
Interview Tips
- Use class as a keyword example.
- Use customerName as an identifier example.
- Use 100 or "Java" as literal examples.
- Do not describe true, false, and null as reserved keywords.
Summary
Keywords control Java syntax, literals represent values, and identifiers name program elements. Reserved keywords are a strict category that cannot be used as identifiers.
Interview Answer
A final variable can be assigned only once. A final method cannot be overridden or hidden by a subclass, while a final class cannot be extended. For reference variables, final prevents reassignment of the reference but does not automatically make the referenced object immutable.
Key Points
- A final variable receives only one assignment.
- A final reference cannot point to another object.
- The referenced object may still be mutable.
- A final method cannot be overridden.
- A final static method cannot be hidden.
- A final class cannot have subclasses.
- A class cannot be both abstract and final.
Interview Tips
- Explain final separately for variables, methods, and classes.
- Do not say that final always creates an immutable object.
- Mention that blank final fields can be initialized later exactly once.
- Distinguish final from finally and finalize().
Summary
The final keyword restricts modification or inheritance depending on where it is used. It prevents variable reassignment, method overriding, and class extension.
Interview Answer
static makes a member belong to the class rather than to individual objects. final prevents reassignment when used with variables and restricts overriding or inheritance when used with methods or classes. A static final field has one class-level value that can be assigned only once, so it is commonly used for shared constants.
Key Points
- A static field has one shared copy per class.
- A non-static field belongs to each object.
- A final field can be assigned only once.
- A static final field combines class-level sharing with one-time assignment.
- static final does not guarantee compile-time constant status.
- A mutable object referenced by static final can still change internally.
- Static members should normally be accessed through the class name.
Interview Tips
- Explain static as ownership and final as restriction.
- Do not assume every static final field is immutable.
- Mention that compile-time constants require additional conditions.
- Use static final for values shared by all objects.
Summary
static creates a class-level member, while final prevents reassignment or inheritance-related changes. static final is commonly used for one shared, fixed reference or value.
Interview Answer
public members are accessible from any class. protected members are accessible within the same package and in subclasses outside the package through inheritance. private members are accessible only inside the class where they are declared.
Key Points
- public provides the widest accessibility.
- protected allows package-level and subclass access.
- private provides the most restricted access.
- Top-level classes can be public or package-private, but not protected or private.
- Access modifiers support encapsulation and controlled visibility.
- Members without an access modifier have package-private access.
Interview Tips
- Explain access using class, package, subclass, and external-package scope.
- Remember that protected access outside the package has inheritance-related restrictions.
- Do not call package-private a Java keyword.
Summary
public allows access everywhere, protected supports package and subclass access, and private restricts access to the declaring class. Choosing the correct modifier improves encapsulation and API design.
Interview Answer
The abstract keyword defines incomplete classes and methods intended for inheritance. An abstract class cannot be instantiated, and an abstract method has no implementation in that class. A concrete subclass must implement all inherited abstract methods unless the subclass is also abstract.
Key Points
- An abstract class cannot be instantiated directly.
- It may contain abstract and concrete methods.
- An abstract method contains only a declaration.
- Abstract methods cannot be private, static, or final.
- An abstract class may have fields, constructors, and static methods.
- A class containing an abstract method must be declared abstract.
Syntax
abstract class Shape {
abstract double calculateArea();
}Interview Tips
- Do not say that an abstract class can contain only abstract methods.
- Mention that constructors are allowed but cannot be abstract.
- Explain that abstract supports partial implementation and code reuse.
- Distinguish abstract classes from interfaces.
Summary
The abstract keyword represents incomplete behavior that subclasses must complete. It supports abstraction while allowing shared fields and implemented methods.
Interview Answer
this refers to the current object, while super refers to the immediate parent-class part of the current object. this is used to access current-class members or constructors, whereas super is used to access inherited members or parent constructors.
Key Points
- this refers to the current class instance.
- super refers to the immediate parent class.
- this() calls another constructor in the same class.
- super() calls a constructor of the parent class.
- this resolves conflicts between fields and parameters.
- super accesses parent members hidden or overridden by the subclass.
Syntax
this.fieldName = fieldName;
this();
super.fieldName;
super();Interview Tips
- this() and super() must be the first statement in a constructor.
- They cannot both be called explicitly in the same constructor.
- Neither keyword can be used in a static context.
- super cannot directly access private parent-class members.
Summary
this works with the current object and current-class constructors. super accesses immediate parent-class members and constructors.
Interview Answer
extends creates inheritance between classes or between interfaces. implements is used when a class agrees to provide the behavior defined by one or more interfaces. A class can extend only one class but can implement multiple interfaces.
Key Points
- A class uses extends to inherit from one parent class.
- An interface uses extends to inherit from one or more interfaces.
- A class uses implements to implement interfaces.
- Java does not support multiple inheritance of classes.
- Implemented interface methods must be provided unless the class is abstract.
- A class may extend one class and implement multiple interfaces together.
Syntax
class Child extends Parent implements FirstInterface, SecondInterface {
}
interface ChildInterface extends FirstInterface, SecondInterface {
}Interview Tips
- Mention single inheritance for classes.
- Mention multiple inheritance through interfaces.
- Do not use implements between two interfaces.
- Place extends before implements in a class declaration.
Summary
extends represents class or interface inheritance, while implements connects a class with interface contracts. Java supports one parent class and multiple implemented interfaces.
Interview Answer
synchronized controls concurrent access to a method or block so only one thread at a time can execute it for the same monitor. volatile ensures that reads and writes use the latest value visible across threads. transient prevents a field from being included in Java’s default object serialization.
Key Points
- synchronized provides mutual exclusion and memory visibility.
- It can be applied to instance methods, static methods, and blocks.
- volatile improves visibility of shared-variable updates.
- volatile does not make compound operations such as count++ atomic.
- transient affects default serialization, not normal object usage.
- A transient field receives its default value after deserialization unless restored manually.
Syntax
private volatile boolean running;
private transient String password;
public synchronized void update() {
}
synchronized (lock) {
}Interview Tips
- Do not describe volatile as a replacement for synchronized.
- Use synchronized when multiple operations must execute atomically.
- Use volatile for simple shared-state visibility when compound locking is unnecessary.
- Do not rely on transient as a security or encryption mechanism.
Summary
synchronized manages exclusive thread access, volatile provides visibility of shared values, and transient excludes fields from default serialization. Each keyword solves a different problem.
Interview Answer
throw is used inside a method or block to explicitly raise an exception object. throws is used in a method declaration to specify exceptions that the method may pass to its caller. throw works with one exception object at a time, while throws can declare multiple exception types.
Key Points
- throw is a statement.
- throws is part of a method declaration.
- throw requires a Throwable object.
- throws declares possible exception types.
- Checked exceptions must be handled or declared.
- Unchecked exceptions do not require a throws declaration.
Syntax
throw new ExceptionType("Message");
returnType methodName() throws ExceptionType1, ExceptionType2 {
}Example
public class ExceptionExample {
public static void validateAge(int age) throws IllegalArgumentException {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (IllegalArgumentException exception) {
System.out.println(exception.getMessage());
}
}
}Output
Age must be at least 18Interview Tips
- Explain throw as raising an exception and throws as declaring it.
- Mention that throws does not actually create or raise an exception.
- Do not confuse exception declaration with exception handling.
- Remember that throw can also rethrow a caught exception.
Summary
throw explicitly raises an exception object during execution. throws declares exceptions that a method may pass to its caller.
Interview Answer
try contains code that may produce an exception, and catch handles a matching exception. finally contains cleanup code that normally executes whether an exception occurs or not. assert checks an assumption during development and throws AssertionError when the condition is false and assertions are enabled.
Key Points
- try must be followed by catch, finally, or both.
- Multiple catch blocks can handle different exception types.
- More specific exceptions must be caught before broader exceptions.
- finally is commonly used for cleanup operations.
- try-with-resources is preferred for closing AutoCloseable resources.
- Assertions are disabled by default.
- Assertions can be enabled using the -ea JVM option.
Syntax
try {
riskyOperation();
} catch (ExceptionType exception) {
handleException();
} finally {
cleanup();
}
assert condition : "Error message";Example
public class ExceptionKeywordExample {
public static void main(String[] args) {
int age = 20;
assert age >= 0 : "Age cannot be negative";
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException exception) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Execution completed");
}
}
}Output
Cannot divide by zero
Execution completedInterview Tips
- Do not use assertions for validating user input or business rules.
- Use assertions for internal assumptions that should always be true.
- Mention that finally may not execute if the JVM terminates abruptly.
- Prefer try-with-resources for files, streams, and database resources.
Summary
try, catch, and finally provide structured exception handling and cleanup. assert helps detect programming assumptions during testing and debugging.
Interview Answer
native declares a method whose implementation is provided outside Java, commonly through platform-specific code. strictfp was introduced to enforce consistent floating-point calculations, but modern Java already evaluates floating-point expressions strictly, so it is generally unnecessary. default provides an implementation for an interface method and also represents the fallback branch in a switch statement.
Key Points
- A native method has no Java method body.
- Native methods are commonly connected through JNI.
- Native code can reduce portability and introduce security risks.
- strictfp applies to floating-point behavior.
- strictfp is retained mainly for source compatibility.
- A default interface method contains an implementation.
- default is also used in switch statements and expressions.
- Package-private access is not declared using the default keyword.
Syntax
public native void executeNativeCode();
public strictfp double calculate() {
return 10.5 / 3.0;
}
interface Printer {
default void print() {
System.out.println("Printing");
}
}
switch (value) {
default:
System.out.println("Unknown value");
}Interview Tips
- Mention JNI when explaining native methods.
- Do not give a Java body to a native method.
- Explain that strictfp has little practical effect in modern Java.
- Do not call package-private access a default keyword modifier.
Summary
native connects Java methods to external implementations, strictfp relates to floating-point consistency, and default provides interface behavior or a switch fallback branch.
Interview Answer
instanceof checks whether an object is compatible with a specified reference type. new creates objects and arrays, return exits a method and may send a value back to the caller, and void declares that a method does not return a value.
Key Points
- instanceof performs a runtime type check.
- instanceof returns false when the reference is null.
- Pattern matching can combine type checking and variable creation.
- new allocates and initializes objects or arrays.
- return immediately ends method execution.
- A non-void method must return a compatible value.
- A void method may use return without a value.
- Constructors do not declare any return type, including void.
Syntax
object instanceof Type
Type reference = new Type();
return value;
void methodName() {
return;
}Example
public class KeywordUsageExample {
public static int createLength(Object value) {
if (value instanceof String text) {
return text.length();
}
return 0;
}
public static void main(String[] args) {
String message = new String("Java");
int length = createLength(message);
System.out.println(length);
}
}Output
4Interview Tips
- Do not confuse instanceof with object comparison.
- Mention that new can create both objects and arrays.
- Remember that constructors have no return type.
- Explain that return exits the method immediately.
Summary
instanceof checks runtime type compatibility, new creates objects and arrays, return ends method execution, and void indicates that a method returns no value.
Interview Answer
Common mistakes include using reserved keywords as identifiers, choosing overly broad access modifiers, combining incompatible modifiers, and misunderstanding static, final, abstract, or protected behavior. Developers also confuse literals with keywords and use outdated or unnecessary language features. These problems can be avoided by following Java syntax rules and applying the most restrictive suitable modifier.
Key Points
- Reserved keywords cannot be used as identifiers.
- true, false, and null are literals, not identifiers.
- A class cannot be both abstract and final.
- An abstract method cannot be private, static, or final.
- Top-level classes cannot be private or protected.
- protected access outside the package has inheritance restrictions.
- final references do not make objects immutable.
- static methods cannot directly access instance members.
- default does not declare package-private access.
- Underscore cannot be used as a standalone identifier.
Example
abstract class Report {
protected abstract void generate();
}
final class SalesReport extends Report {
@Override
protected void generate() {
System.out.println("Sales report generated");
}
}
public class ModifierExample {
public static void main(String[] args) {
SalesReport report = new SalesReport();
report.generate();
}
}Output
Sales report generatedInterview Tips
- Use private by default and increase visibility only when required.
- Check whether modifiers are valid for the declaration type.
- Avoid using language terms as variable or method names.
- Understand each modifier’s effect instead of memorizing combinations.
- Use compiler warnings and code-quality tools to catch modifier mistakes.
Summary
Most keyword-related mistakes come from invalid modifier combinations, incorrect access assumptions, and confusion about reserved language tokens. Clear naming and restrictive access design produce safer and more maintainable Java code.