Java Keywords and Identifiers
Scenario1: Variable Naming Error
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.
You are writing a Java program and decide to name your integer variable for. When you try to compile, you get an error.
Interview 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
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.
A teammate tries to declare a new class as public class int { ... } but the code would not compile.
Interview 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
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.
You want to create a variable named 123total to store a sum, but the IDE highlights it as invalid.
Interview 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
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.
You have two variables in your code: Result and result. You assign different values to each.
Interview 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
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.
You want to use the word record as a class name in Java 16.
Interview 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.