Java Keywords
Reserved words that have special meaning in Java
🔑 What are Java Keywords?
Java keywords are reserved words with special meanings that cannot be used as variable names. They control program flow, define data types, and specify access levels in your Java code.
// Keywords in action
public class MyClass {
private int number;
public static void main(String[] args) {
if (true) {
System.out.println("Hello Java!");
}
}
}
Types of Java Keywords
Access Modifiers
Control visibility of classes and methods
Data Types
Define what kind of data to store
Control Flow
Control program execution flow
Class Keywords
Define classes and inheritance
🔹 Access Modifier Keywords
Control who can access your classes, methods, and variables:
public class Example {
public int publicVar = 1; // Accessible everywhere
private int privateVar = 2; // Only within this class
protected int protectedVar = 3; // Within package and subclasses
int defaultVar = 4; // Within package only
public void showAccess() {
System.out.println("Public: " + publicVar);
System.out.println("Private: " + privateVar);
}
}
Output:
Public: 1
Private: 2
🔹 Data Type Keywords
Specify what type of data your variables can hold:
public class DataTypes {
public static void main(String[] args) {
int age = 25; // Whole numbers
double price = 19.99; // Decimal numbers
boolean isActive = true; // True or false
char grade = 'A'; // Single character
String name = "John"; // Text
System.out.println("Age: " + age);
System.out.println("Price: $" + price);
System.out.println("Active: " + isActive);
}
}
Output:
Age: 25
Price: $19.99
Active: true
🔹 Control Flow Keywords
Control how your program executes:
public class ControlFlow {
public static void main(String[] args) {
// if-else statement
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
// for loop
for (int i = 1; i <= 3; i++) {
System.out.println("Count: " + i);
}
}
}
Output:
Grade: B
Count: 1
Count: 2
Count: 3
🔹 Common Keywords Reference
Essential keywords every Java beginner should know:
Most Used Keywords:
- public: Makes code accessible everywhere
- static: Belongs to class, not instance
- void: Method returns nothing
- class: Defines a new class
- new: Creates new objects
- return: Exits method with value
- this: Refers to current object
- super: Refers to parent class
public class KeywordDemo {
private String message;
public KeywordDemo(String msg) {
this.message = msg; // 'this' refers to current object
}
public void display() {
System.out.println(this.message);
return; // Optional for void methods
}
public static void main(String[] args) {
KeywordDemo demo = new KeywordDemo("Hello Keywords!");
demo.display();
}
}