Loading
Java Keywords and Identifiers

Interview Questions of keywords-and-identifiers

Scenario1:  Variable Naming Error

Scenario:


You are writing a Java program and decide to name your integer variable for. When you try to compile, you get an error.


Question: 

Why does this error occur, and how would you fix it ?


Answer: 

The error occurs because for is a reserved keyword in Java, used for loops. Keywords cannot be used as variable names. To fix it, choose a different identifier, such as forCount or loopCounter.


Scenario 2:  Class Declaration Confusion

Scenario:


A teammate tries to declare a new class as public class int { ... } but the code would not compile.


Question: 

What is wrong with this class declaration ?


Answer: 

int is a keyword in Java, used to declare integer variables. Keywords cannot be used as class names. The class should be renamed to something like IntegerClass or MyInt.


Scenario 3:  Identifier Rules

Scenario:


You want to create a variable named 123total to store a sum, but the IDE highlights it as invalid.


Question:

Why cannot you use 123total as a variable name, and what would be a valid alternative ?


Answer:

Identifiers cannot start with a digit. A valid alternative would be total123 or sum123.


Scenario 4:  Case Sensitivity

Scenario:


You have two variables in your code: Result and result. You assign different values to each.


Question:

Will Java treat these variables as the same or different ? Why ?


Answer:

Java is case-sensitive, so Result and result are treated as two distinct identifiers.


Scenario 5:  Using Contextual Keywords

Scenario:


You want to use the word record as a class name in Java 16.


Question:

Will this work ? Why or why not ?


Answer:

No, starting from Java 16, record is a contextual keyword used to define record classes. It cannot be used as a class name.