Java Basics Chapter
Identifiers Interview Questions and Answers
Learn how Java identifiers work, from naming rules and case sensitivity to naming conventions, identifier shadowing, Unicode support, and common naming mistakes.
Identifiers interview questions
Identifiers Interview Question 15 Questions
Click on any question to expand the answer.
Interview Answer
Identifiers are names given to program elements so they can be referenced in Java code. They are used to name classes, interfaces, methods, variables, constants, packages, modules, constructors, labels, and type parameters. An identifier does not store a value by itself; it only identifies a declared element.
Key Points
- Identifiers are developer-defined names.
- They make program elements accessible by name.
- Identifiers are case-sensitive.
- The same naming rules apply to all identifiers.
- Naming conventions differ based on the element being named.
- Clear identifiers improve readability and maintainability.
Example
package training;
public class Employee {
private int employeeId;
public Employee(int employeeId) {
// this.employeeId refers to the field.
this.employeeId = employeeId;
}
public void displayEmployeeId() {
System.out.println(employeeId);
}
public static void main(String[] args) {
Employee employee = new Employee(101);
employee.displayEmployeeId();
}
}Output
101Interview Tips
- Give examples such as Employee, employeeId, and displayEmployeeId.
- Do not describe an identifier as a value or data type.
- Mention that identifiers are used to reference declared program elements.
Summary
Identifiers are names assigned to Java program elements. They allow classes, methods, variables, packages, and other declarations to be referenced clearly.
Interview Answer
A Java identifier must begin with a Java letter and may continue with Java letters or Java digits. It cannot contain spaces, operators, or punctuation such as hyphens, and it cannot be a reserved keyword or literal. Java identifiers are case-sensitive and can have unlimited length according to the language specification.
Key Points
- The first character cannot be a digit.
- Later characters may include letters and digits.
- Underscores and dollar signs are permitted.
- Spaces and symbols such as -, @, and # are invalid.
- Reserved keywords cannot be identifiers.
- true, false, and null cannot be identifiers.
- Identifier names are case-sensitive.
Example
public class IdentifierRules {
public static void main(String[] args) {
int employeeAge = 30;
int _itemCount = 5;
int total2 = 20;
// int 2total = 20; Invalid: starts with a digit.
// int employee-age = 30; Invalid: contains a hyphen.
// int class = 1; Invalid: class is a keyword.
System.out.println(employeeAge);
System.out.println(_itemCount);
System.out.println(total2);
}
}Output
30
5
20Interview Tips
- Separate compiler rules from recommended naming conventions.
- Remember that an identifier cannot begin with a digit.
- Mention that Java identifiers are case-sensitive.
- Do not say that identifiers can contain only English letters.
Summary
A valid identifier begins with a Java letter and continues with Java letters or digits. It must not contain invalid symbols or conflict with reserved language tokens.
Interview Answer
The first character must be accepted as a Java identifier-start character. This includes many letters, currency symbols, connecting punctuation characters, the dollar sign, and the underscore. Following characters may additionally include digits and other characters accepted as Java identifier parts.
Key Points
- ASCII letters may begin an identifier.
- Unicode letters may also begin an identifier.
- The underscore may appear in a multi-character identifier.
- The dollar sign is legal but discouraged in application code.
- Digits may appear only after the first character.
- Spaces and most punctuation marks are not allowed.
- Java uses Character identifier rules to classify Unicode characters.
Example
public class IdentifierCharacters {
public static void main(String[] args) {
int count = 10;
int _total = 20;
int $price = 30;
int number2 = 40;
// int 2number = 50; Invalid: a digit cannot be first.
System.out.println(count + _total + $price + number2);
}
}Output
100Interview Tips
- State that digits are allowed only after the first character.
- Mention Unicode support when discussing Java letters.
- Avoid using dollar signs because tools and generated code commonly use them.
- Do not assume that every visible Unicode symbol is valid.
Summary
Java identifiers begin with a valid identifier-start character. Later positions support a wider set of characters, including digits.
Interview Answer
Yes, Java identifiers can contain digits, underscores, dollar signs, and valid Unicode characters. A digit cannot be the first character, and a single underscore cannot be used as a normal identifier because it is reserved. Although dollar signs and Unicode names are legal, descriptive English names are usually easier for development teams to maintain.
Key Points
- Digits are allowed after the first character.
- An underscore may appear within a longer identifier.
- A single underscore is reserved.
- Dollar signs are legal but generally discouraged.
- Java supports identifiers based on Unicode.
- Unicode identifiers remain case-sensitive.
- Legal names are not always recommended names.
Example
public class SpecialIdentifiers {
public static void main(String[] args) {
int version2 = 21;
int total_count = 50;
int $generatedValue = 75;
int संखà¥à¤¯à¤¾ = 100;
// int _ = 10; Invalid: a single underscore is reserved.
System.out.println(version2);
System.out.println(total_count);
System.out.println($generatedValue);
System.out.println(संखà¥à¤¯à¤¾);
}
}Output
21
50
75
100Interview Tips
- Distinguish valid identifiers from professional naming practices.
- Remember that a digit cannot appear first.
- Mention the special rule for a single underscore.
- Prefer names that every team member can read easily.
Summary
Java permits digits, underscores, dollar signs, and supported Unicode characters in identifiers. Their placement and use must follow Java’s lexical rules.
Interview Answer
Keywords and reserved words already have predefined roles in Java’s grammar. Allowing them as identifiers would make source code ambiguous because the compiler could not reliably determine whether a word represented language syntax or a developer-defined name. Therefore, reserved keywords are recognized as separate tokens and cannot be ordinary identifiers.
Key Points
- Keywords define Java language constructs.
- The compiler assigns them predefined meanings.
- Reserved keywords cannot be renamed or redefined.
- Examples include class, int, public, return, and new.
- const and goto are reserved even though Java does not use them.
- Contextual keywords have special meanings only in particular contexts.
- true, false, and null are literals rather than identifiers.
Example
public class ReservedWordExample {
public static void main(String[] args) {
int classCount = 5;
int returnValue = 10;
// int class = 5; Invalid: class defines a Java declaration.
// int return = 10; Invalid: return controls method execution.
System.out.println(classCount + returnValue);
}
}Output
15Interview Tips
- Explain that the restriction prevents grammatical ambiguity.
- Use class or return as clear keyword examples.
- Mention that const and goto remain reserved.
- Do not incorrectly classify true, false, and null as identifiers.
Summary
Reserved words cannot be identifiers because Java’s compiler already uses them as language tokens. This rule keeps declarations and program syntax unambiguous.
Interview Answer
Yes, Java identifiers are case-sensitive. Names such as count, Count, and COUNT are treated as three different identifiers. Incorrect capitalization can therefore cause compilation errors or reference the wrong program element.
Key Points
- Uppercase and lowercase letters are different.
- employeeName and EmployeeName are separate identifiers.
- Class names normally begin with an uppercase letter.
- Method and variable names normally begin with a lowercase letter.
- Constants normally use uppercase letters.
- Consistent capitalization improves code readability.
Example
public class CaseSensitiveExample {
public static void main(String[] args) {
int score = 10;
int Score = 20;
int SCORE = 30;
// Java treats these as three different identifiers.
System.out.println(score);
System.out.println(Score);
System.out.println(SCORE);
}
}Output
10
20
30Interview Tips
- State clearly that Java is case-sensitive.
- Use a simple example such as value and Value.
- Follow standard naming conventions to avoid confusion.
- Check capitalization when resolving cannot find symbol errors.
Summary
Java treats identifiers with different capitalization as different names. Consistent casing prevents mistakes and makes code easier to understand.
Interview Answer
An identifier is a developer-defined name used to identify a program element. A variable is a named storage location that holds a value, while a keyword has a predefined meaning in Java syntax. A literal is a fixed value written directly in source code.
Key Points
- Identifiers provide names to program elements.
- Variables store values that may change.
- Every variable has an identifier.
- Keywords define Java language constructs.
- Reserved keywords cannot be identifiers.
- Literals directly represent values such as 25, true, and "Java".
Example
public class IdentifierDifference {
public static void main(String[] args) {
// int is a keyword.
// age is an identifier and variable name.
// 25 is an integer literal.
int age = 25;
System.out.println(age);
}
}Output
25Interview Tips
- Use one variable declaration to explain all four concepts.
- Do not describe a literal as a variable.
- Remember that an identifier is the name, not the stored value.
- Use class, int, or return as keyword examples.
Summary
An identifier names a program element, and a variable stores a value under an identifier. Keywords belong to Java syntax, while literals are direct values written in code.
Interview Answer
Classes and interfaces should use UpperCamelCase, while methods and variables should use lowerCamelCase. Constants should use uppercase words separated by underscores, and package names should use lowercase letters. Type parameters normally use short uppercase names such as T, E, K, and V.
Key Points
- Classes use names such as EmployeeService.
- Interfaces use names such as PaymentProcessor.
- Methods use names such as calculateTotal.
- Variables use names such as employeeCount.
- Constants use names such as MAX_RETRY_COUNT.
- Packages use names such as com.example.payment.
- Type parameters commonly use T, E, K, and V.
Example
package com.example.payment;
public class PaymentService<T> {
private static final int MAX_RETRY_COUNT = 3;
private T paymentData;
public PaymentService(T paymentData) {
this.paymentData = paymentData;
}
public void displayPaymentData() {
// Method and variable names use lowerCamelCase.
System.out.println(paymentData);
System.out.println(MAX_RETRY_COUNT);
}
public static void main(String[] args) {
PaymentService<String> paymentService =
new PaymentService<>("Payment completed");
paymentService.displayPaymentData();
}
}Output
Payment completed
3Interview Tips
- Distinguish compiler rules from naming conventions.
- Choose names that describe purpose rather than data type.
- Avoid unnecessary abbreviations and single-letter variable names.
- Use standard type-parameter names in generic code.
Summary
Java naming conventions use different capitalization styles for different program elements. Following them makes code predictable, professional, and easier to maintain.
Interview Answer
true, false, and null cannot be identifiers because they are literal tokens. var is a contextual keyword, so it can be used as an identifier in some positions, such as a variable name, but it cannot be used as a class, interface, or type-parameter name. A single underscore is a reserved keyword and cannot be used as a normal named identifier, although modern Java permits it in specific unnamed declarations.
Key Points
- true and false are boolean literals.
- null is the null literal.
- var is not a reserved keyword in every context.
- int var = 10 is valid.
- A class named var is invalid.
- A single underscore cannot be a normal identifier.
- Longer names such as _count are valid.
Example
public class SpecialIdentifierExample {
public static void main(String[] args) {
int var = 10;
int _count = 20;
// int true = 1; Invalid: true is a boolean literal.
// int null = 2; Invalid: null is the null literal.
// int _ = 3; Invalid as a normal named identifier.
System.out.println(var);
System.out.println(_count);
}
}Output
10
20Interview Tips
- Do not incorrectly describe true, false, and null as identifiers.
- Explain that var is context-sensitive.
- Mention that var cannot be used as a type name.
- Distinguish the single underscore from identifiers such as _value.
Summary
true, false, null, and a single underscore cannot be normal identifiers. var can be an identifier only where Java’s contextual-keyword rules permit it.
Interview Answer
The Java Language Specification defines an identifier as an unlimited-length sequence, so it does not specify a source-level maximum length. However, compiled class files impose practical limits: field and method names are stored using a structure limited to 65,535 encoded bytes. Developers should still use concise and meaningful names.
Key Points
- Java source identifiers have no specified language-level maximum.
- Compiler and tool implementations may have practical limitations.
- Class-file names are restricted by their encoded representation.
- Unicode characters may require multiple encoded bytes.
- Extremely long identifiers reduce readability.
- Names should be descriptive but reasonably short.
Interview Tips
- Answer that the language specification defines identifiers as unlimited-length.
- Mention class-file limits only as an advanced clarification.
- Do not confuse identifier length with variable storage size.
- Prioritize readability over using unnecessarily long names.
Summary
Java does not define a source-level maximum identifier length. Practical compiler, class-file, and readability limits still make excessively long names unsuitable.
Interview Answer
Identifier shadowing occurs when a declaration with the same name makes another declaration temporarily inaccessible through its simple name. A local variable or method parameter can shadow an instance field. The hidden field can still be accessed using this.fieldName, while a hidden static field can be accessed using the class name.
Key Points
- A local variable can shadow an instance field.
- A method parameter can shadow a field.
- The nearest declaration is selected by a simple name.
- this accesses the current object’s hidden field.
- ClassName.fieldName accesses a hidden static field.
- Java does not allow redeclaring a local variable inside its overlapping scope.
Example
public class Employee {
private int employeeId;
public Employee(int employeeId) {
// The parameter shadows the instance field.
this.employeeId = employeeId;
}
public void displayEmployeeId() {
int employeeId = 500;
// Uses the local variable.
System.out.println(employeeId);
// Uses the shadowed instance field.
System.out.println(this.employeeId);
}
public static void main(String[] args) {
Employee employee = new Employee(101);
employee.displayEmployeeId();
}
}Output
500
101Interview Tips
- Explain shadowing using a constructor parameter and instance field.
- Use this to access the current object’s field.
- Do not confuse shadowing with method overriding or field hiding.
- Avoid unnecessary shadowing when it reduces readability.
Summary
Shadowing occurs when a local declaration uses the same name as a field or another accessible declaration. The this keyword helps distinguish an instance field from a local variable or parameter.
Interview Answer
A valid identifier follows Java’s compiler rules, such as using permitted characters and avoiding reserved tokens. A recommended identifier also follows professional naming conventions by being descriptive, readable, and appropriate for the program element. Therefore, an identifier can compile successfully but still be a poor naming choice.
Key Points
- Valid identifiers satisfy Java syntax rules.
- Recommended identifiers clearly describe their purpose.
- Dollar signs are legal but discouraged in application code.
- Names should avoid unclear abbreviations.
- Variables and methods normally use lowerCamelCase.
- Classes and interfaces normally use UpperCamelCase.
- Constants normally use uppercase words separated by underscores.
Example
public class NamingExample {
public static void main(String[] args) {
// Valid but unclear identifiers.
int x = 25;
int $v = 5;
// Valid and recommended identifiers.
int employeeAge = 25;
int retryCount = 5;
System.out.println(x + $v);
System.out.println(employeeAge + retryCount);
}
}Output
30
30Interview Tips
- Distinguish language rules from coding conventions.
- Prefer names that explain business meaning.
- Avoid single-letter names except for small temporary values.
- Do not use dollar signs in normal application code.
Summary
A valid identifier is accepted by the compiler. A recommended identifier also follows naming conventions and communicates its purpose clearly.
Interview Answer
Java allows identifiers to contain Unicode characters accepted by its identifier-start and identifier-part rules. This permits variable, method, and class names in many writing systems. However, Unicode identifiers may create readability, keyboard, tooling, normalization, and visually confusing character problems in collaborative projects.
Key Points
- Java identifiers are not limited to English letters.
- Unicode letters can appear in identifiers.
- Identifier characters are checked using Character rules.
- Similar-looking Unicode characters may represent different code points.
- Equivalent-looking text may use different Unicode sequences.
- Team members may have difficulty typing or searching Unicode names.
- Unicode identifiers can increase the risk of visually deceptive code.
Example
public class UnicodeIdentifierExample {
public static void main(String[] args) {
int संखà¥à¤¯à¤¾ = 100;
int किंमत = 50;
// Unicode identifiers are valid Java identifiers.
int à¤à¤•ूण = संखà¥à¤¯à¤¾ + किंमत;
System.out.println(à¤à¤•ूण);
}
}Output
150Interview Tips
- Mention that Java supports international naming through Unicode.
- Explain that legal Unicode names may still reduce team readability.
- Prefer consistent naming rules across the project.
- Watch for visually similar characters from different alphabets.
Summary
Java supports Unicode identifiers through its character-classification rules. They enable international names but may cause readability, compatibility, and security-related confusion.
Interview Answer
Invalid identifiers cause compilation errors when they begin with an illegal character, contain unsupported symbols, or conflict with reserved tokens. Duplicate declarations also fail when two fields have the same name in one class or when local variables with the same name have overlapping scopes. Methods may share a name only when their parameter lists form valid overloads.
Key Points
- An identifier cannot begin with a digit.
- Keywords cannot be ordinary identifiers.
- Spaces and symbols such as hyphens are invalid.
- Duplicate fields in the same class are not allowed.
- Duplicate parameters in one method are not allowed.
- Local variables cannot be redeclared in overlapping scopes.
- Method names can repeat when valid overloading rules are followed.
Example
public class IdentifierErrorExample {
private int employeeId;
// private int employeeId; Invalid: duplicate field.
public void display(int count) {
int total = 10;
// int count = 5; Invalid: duplicates the parameter.
// int total = 20; Invalid: duplicate local variable.
// int 2value = 30; Invalid: begins with a digit.
// int employee-name = 40; Invalid: contains a hyphen.
System.out.println(count + total + employeeId);
}
public static void main(String[] args) {
IdentifierErrorExample example = new IdentifierErrorExample();
example.display(5);
}
}Output
15Interview Tips
- Explain duplicate-name rules according to scope.
- Remember that overloaded methods may have the same name.
- Check the compiler’s first reported error before fixing later errors.
- Use IDE inspections to detect naming conflicts early.
Summary
Invalid characters and reserved tokens make identifiers illegal. Duplicate identifiers cause errors when declarations conflict within the same namespace or overlapping scope.
Interview Answer
Common mistakes include using unclear abbreviations, inconsistent capitalization, misleading names, reserved words, excessive identifier length, and identifiers that differ only by case. Developers also misuse underscores, dollar signs, and Unicode characters. These problems can be avoided by following standard Java naming conventions and choosing concise, descriptive names.
Key Points
- Avoid names such as data, value, temp, or x when their purpose is unclear.
- Do not use names that differ only by capitalization.
- Avoid dollar signs in manually written code.
- Do not use a single underscore as a named identifier.
- Use lowerCamelCase for variables and methods.
- Use UpperCamelCase for classes and interfaces.
- Use uppercase words with underscores for constants.
- Keep naming consistent across the project.
Example
public class ProductService {
private static final int MAX_RETRY_COUNT = 3;
public double calculateDiscountedPrice(double productPrice) {
// The name explains what the value represents.
double discountRate = 0.10;
return productPrice - productPrice * discountRate;
}
public static void main(String[] args) {
ProductService productService = new ProductService();
double finalPrice = productService.calculateDiscountedPrice(1000.0);
System.out.println(finalPrice);
System.out.println(MAX_RETRY_COUNT);
}
}Output
900.0
3Interview Tips
- Choose names based on purpose rather than data type.
- Use verbs for methods and nouns for variables or classes.
- Avoid unexplained abbreviations and misleading names.
- Apply one naming convention consistently across the codebase.
- Rename identifiers when their original meaning changes.
Summary
Good identifiers are legal, descriptive, consistent, and easy to understand. Following Java naming conventions reduces confusion and improves long-term maintainability.