Lesson Completion
Back to course

Identifiers and Keywords: Naming Rules and Reserved Words

Beginner
10 minutesβ˜…4.8Java

1. The Hook (The "Byte-Sized" Intro)

  • In a Nutshell: Identifiers = names (variables, methods, classes).
  • Rules: Start with letter/underscore/$ (not digit), case-sensitive, no keywords. Keywords = 50+ reserved words (if, class, public, etc.), can't be used as identifiers. Contextual keywords = special meaning in context (module, var, yield).
  • Best practices: Use meaningful names (camelCase for variables, PascalCase for classes), avoid single letters except loops.
  • Golden rule: Code is read more than writtenβ€”make names self-explanatory!

Think of naming people. Identifiers = person's name (unique, meaningful). Rules = naming conventions (can't start with number "1John"). Keywords = reserved titles (can't name someone "President" as regular name). Best practices = use full names (not "J" for John)!


2. Conceptual Clarity (The "Simple" Tier)

πŸ’‘ The Analogy

  • Identifier: Street address (unique location)
  • Keyword: Traffic sign (reserved meaning)
  • Naming Convention: Dress code (follow the rules)

3. Technical Mastery (The "Deep Dive")

java
// =========================================== // 1. IDENTIFIERS (Valid Names) // =========================================== // βœ… VALID identifiers int age; // Starts with letter String user_name; // Contains underscore double $salary; // Starts with $ (not recommended) int _count; // Starts with underscore String firstName123; // Contains digits (not at start) // ❌ INVALID identifiers int 123name; // ❌ Starts with digit String first-name; // ❌ Contains hyphen double my salary; // ❌ Contains space int class; // ❌ Reserved keyword // Case-sensitive (different identifiers) int value = 10; int Value = 20; int VALUE = 30; // All three are DIFFERENT variables! // =========================================== // 2. NAMING CONVENTIONS // =========================================== // βœ… Variables and methods: camelCase int studentAge; String userName; void calculateTotal() { } double getBalance() { } // βœ… Classes and interfaces: PascalCase class Student { } interface Runnable { } class BankAccount { } // βœ… Constants: UPPER_SNAKE_CASE final int MAX_SIZE = 100; final String DEFAULT_NAME = "Unknown"; static final double PI = 3.14159; // βœ… Packages: lowercase.dot.notation package com.example.myapp; package java.util; // ❌ BAD naming (but technically valid) int x; // Not descriptive String s1; // What is s1? void m() { } // What does m() do? class data { } // Should be PascalCase // βœ… GOOD naming int studentCount; String emailAddress; void processPayment() { } class Customer { } // =========================================== // 3. RESERVED KEYWORDS (Cannot use as identifiers) // =========================================== // 50 Reserved Keywords in Java: // abstract continue for new switch // assert default if package synchronized // boolean do goto private this // break double implements protected throw // byte else import public throws // case enum instanceof return transient // catch extends int short try // char final interface static void // class finally long strictfp volatile // const float native super while // ❌ CANNOT use these as identifiers int if = 10; // ❌ Compile error String class = "Java"; // ❌ Compile error void return() { } // ❌ Compile error // =========================================== // 4. CONTEXTUAL KEYWORDS (Java 9+) // =========================================== // These have special meaning in specific contexts // but can be used as identifiers elsewhere // βœ… As identifier (allowed) String var = "test"; // var as variable name (allowed) int module = 5; // module as variable name String yield = "result"; // yield as variable name // Special meaning in context: var list = new ArrayList<>(); // var = local variable type inference module java.base { } // module = module declaration yield value; // yield = switch expression (Java 14+) // =========================================== // 5. LITERALS (Special values, not keywords) // =========================================== // These are literals, not keywords: true // boolean literal false // boolean literal null // null literal // Can use as identifiers (but DON'T!) int true = 1; // ❌ Compiles but VERY confusing! String null = ""; // ❌ Compiles but terrible practice! // =========================================== // 6. BEST PRACTICES // =========================================== // βœ… GOOD: Meaningful, descriptive names int studentAge = 20; String customerEmail = "user@example.com"; double accountBalance = 1500.50; void calculateMonthlyPayment(double principal, double rate) { // Clear what this does } class ShoppingCart { // Clear what this represents } // ❌ BAD: Cryptic, unclear names int sa = 20; // What is sa? String ce; // What is ce? double ab; // What is ab? void cmp(double p, double r) { // What does cmp do? What are p and r? } class SC { // What is SC? } // Loop variables: single letters OK in short loops for (int i = 0; i < 10; i++) { // βœ… OK for loop counter System.out.println(i); } // But for collections, use descriptive names for (Student student : students) { // βœ… Clear System.out.println(student.getName()); } // NOT this: for (Student s : students) { // ❌ Less clear System.out.println(s.getName()); }

5. The Comparison & Decision Layer

ElementConventionExample
VariablecamelCasestudentAge
MethodcamelCasecalculateTotal()
ClassPascalCaseBankAccount
InterfacePascalCaseRunnable
ConstantUPPER_SNAKE_CASEMAX_SIZE
Packagelowercasecom.example.app

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "Can you use 'var' as an identifier in Java?" Answer: Yes, but context matters!

java
// βœ… var as identifier (allowed) String var = "test"; int var = 10; // βœ… var as type inference (Java 10+) var list = new ArrayList<String>(); // var infers type var count = 10; // var infers int // var is a "contextual keyword" (not reserved keyword) // Special meaning: local variable type inference // But can still be used as identifier elsewhere

Follow-up: "Why is 'goto' a keyword if Java doesn't use it?" Answer: Reserved for future use. Java reserves it to prevent confusion (C/C++ have goto). Same with const (use final instead).

Pro-Tips:

  1. Avoid underscores in names (except constants):
java
// ❌ Avoid int user_age; String first_name; // βœ… Prefer int userAge; String firstName;
  1. Boolean naming (use is/has/can):
java
// βœ… Clear intent boolean isActive; boolean hasPermission; boolean canDelete; // ❌ Unclear boolean active; boolean permission;
  1. Method naming (verbs for actions):
java
// βœ… Action verbs void calculateTotal() String getName() void setAge(int age) boolean isValid() // ❌ Noun names void total() String name()

Topics Covered

Java FundamentalsJava Syntax

Tags

#java#basics#syntax#variables#data-types#beginner-friendly

Last Updated

2025-02-01