Java Keywords
Keywords Overview
Java has 53 keywords (including reserved words), which can be categorized as follows:
- Access Control Keywords: Control access to classes, methods, and variables
- Class, Method, and Variable Modifiers: Define characteristics of classes, methods, and variables
- Program Control Statements: Control program execution flow
- Error Handling: Handle exceptions and errors
- Package Related: Manage packages and imports
- Primitive Data Types: Define primitive data types
- Variable References: Handle variable references and instances
- Reserved Words: Keywords reserved for future use
Java has a set of keywords that are reserved words and cannot be used as variable, method, class, or any other identifier names:
| Keyword | Description |
|---|---|
| abstract | Non-access modifier. Used for classes and methods: An abstract class cannot be used to create objects (to access it, it must be inherited from another class). An abstract method can only be used in an abstract class and does not have a body. The body is provided by the subclass (inherited from) |
| assert | For debugging |
| boolean | A data type that can only store true or false values |
| break | Breaks out of a loop or switch block |
| byte | A data type that can store integers from -128 to 127 |
| case | Marks a block of code in switch statements |
| catch | Catches exceptions generated by try statements |
| char | A data type used to store a single character |
| class | Defines a class |
| continue | Continues to the next iteration of a loop |
| const | Defines a constant. Not used - use final instead |
| default | Specifies the default block of code in a switch statement |
| do | Used together with while to create a do-while loop |
| double | A data type that can store decimals from 1.7e−308 to 1.7e+308 |
| else | Used in conditional statements |
| enum | Declares an enumerated (unchangeable) type |
| exports | Exports a package with a module. Added in Java 9 |
| extends | Extends a class (indicates that a class inherits from another class) |
| final | Non-access modifier used for classes, attributes and methods, making them unchangeable (cannot be inherited or overridden) |
| finally | Used with exceptions, a block of code that will be executed regardless of whether an exception is thrown |
| float | A data type that can store decimals from 3.4e−038 to 3.4e+038 |
| for | Creates a for loop |
| goto | Not in use, has no function |
| if | Creates a conditional statement |
| implements | Implements an interface |
| import | Used to import a package, class or interface |
| instanceof | Checks whether an object is an instance of a specific class or interface |
| int | A data type that can store integers from -2147483648 to 2147483647 |
| interface | Used to declare a special type of class that only contains abstract methods |
| long | A data type that can store integers from -9223372036854775808 to 9223372036854775808 |
| module | Declares a module. Added in Java 9 |
| native | Specifies that a method is not implemented in the same Java source file (but in another language) |
| new | Creates new objects |
| package | Declares a package |
| private | An access modifier used for attributes, methods and constructors, making them only accessible within the declared class |
| protected | An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses |
| public | An access modifier used for classes, attributes, methods and constructors, making them accessible by any other class |
| requires | Specifies required libraries inside a module. Added in Java 9 |
| return | Finishes the execution of a method, and can be used to return a value from a method |
| short | A data type that can store integers from -32768 to 32767 |
| static | A non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class |
| strictfp | Obsolete. Restricts the precision and rounding of floating point calculations |
| super | Refers to superclass (parent) objects |
| switch | Selects one of many code blocks to be executed |
| synchronized | A non-access modifier, which specifies that methods can only be accessed by one thread at a time |
| this | Refers to the current object in a method or constructor |
| throw | Creates a custom error |
| throws | Indicates what exceptions may be thrown by a method |
| transient | Used to ignore an attribute when serializing an object |
| try | Creates a try...catch statement |
| var | Declares a variable. Added in Java 10 |
| void | Specifies that a method should not have a return value |
| volatile | Indicates that an attribute is not cached thread-locally, and is always read from the "main memory" |
| while | Creates a while loop |
Java keywords are predefined reserved words in the Java language with special meanings. These keywords cannot be used as variable names, method names, class names, or any other identifiers. The Java language specification defines these keywords, and they form the foundation of Java syntax.
NOTE
Note: true, false, and null are not keywords, but they are literals and reserved words, and cannot be used as identifiers.
Access Control Keywords
public
Defines public access, can be accessed by any other class.
public class MyClass {
public int publicVariable = 10;
public void publicMethod() {
System.out.println("This is a public method");
}
}private
Defines private access, can only be accessed within the same class.
public class MyClass {
private int privateVariable = 20;
private void privateMethod() {
System.out.println("This is a private method");
}
}protected
Defines protected access, can be accessed by classes in the same package or subclasses.
public class Parent {
protected int protectedVariable = 30;
protected void protectedMethod() {
System.out.println("This is a protected method");
}
}
class Child extends Parent {
public void accessProtected() {
System.out.println(protectedVariable); // Accessible
protectedMethod(); // Can be called
}
}Class, Method and Variable Modifiers
static
Defines static members that belong to the class rather than instances.
public class StaticExample {
static int staticVariable = 100;
static void staticMethod() {
System.out.println("Static method, static variable value: " + staticVariable);
}
public static void main(String[] args) {
// Access directly through class name
StaticExample.staticMethod();
System.out.println(StaticExample.staticVariable);
}
}final
Defines final, unchangeable elements.
public class FinalExample {
// final variable (constant)
final int CONSTANT = 42;
// final method (cannot be overridden)
final void finalMethod() {
System.out.println("This method cannot be overridden");
}
}
// final class (cannot be inherited)
final class FinalClass {
// Class content
}abstract
Defines abstract classes or abstract methods.
abstract class AbstractClass {
// Abstract method (no implementation)
abstract void abstractMethod();
// Concrete method
void concreteMethod() {
System.out.println("Concrete method implementation");
}
}
class ConcreteClass extends AbstractClass {
@Override
void abstractMethod() {
System.out.println("Implementing abstract method");
}
}synchronized
Used for multi-thread synchronization.
public class SynchronizedExample {
private int count = 0;
// Synchronized method
synchronized void increment() {
count++;
}
void anotherMethod() {
// Synchronized block
synchronized(this) {
count--;
}
}
}volatile
Ensures variable visibility, prevents compiler optimization.
public class VolatileExample {
private volatile boolean flag = false;
public void setFlag() {
flag = true; // Immediately visible to all threads
}
public boolean getFlag() {
return flag;
}
}Program Control Statements
Conditional Statements
if, else
Conditional judgment statements.
int score = 85;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 80) {
System.out.println("Good");
} else if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}switch, case, default
Multi-branch selection statement.
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
break;
}Loop Statements
for
For loop statement.
// Traditional for loop
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println("Number: " + num);
}while
While loop statement.
int i = 0;
while (i < 5) {
System.out.println("while loop: " + i);
i++;
}do
Do-while loop statement.
int j = 0;
do {
System.out.println("do-while loop: " + j);
j++;
} while (j < 3);Jump Statements
break
Breaks out of a loop or switch statement.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop
}
System.out.println(i);
}continue
Skips the current loop iteration.
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip current iteration
}
System.out.println(i);
}return
Returns from a method.
public int calculateSum(int a, int b) {
if (a < 0 || b < 0) {
return -1; // Early return
}
return a + b; // Normal return
}Error Handling Keywords
try, catch, finally
Exception handling mechanism.
public class ExceptionExample {
public void divideNumbers(int a, int b) {
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Division by zero error: " + e.getMessage());
} finally {
System.out.println("This executes regardless of exception");
}
}
}throw
Throws an exception.
public void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
System.out.println("Age validation passed: " + age);
}throws
Declares exceptions that a method may throw.
public void readFile(String filename) throws IOException {
FileReader file = new FileReader(filename);
// File reading operations
}Package Related Keywords
package
Declares a package.
package com.example.myproject;
public class MyClass {
// Class content
}import
Imports classes from other packages.
import java.util.ArrayList;
import java.util.List;
import java.io.*; // Import entire package
public class ImportExample {
public void useImportedClasses() {
List<String> list = new ArrayList<>();
// Use imported classes
}
}Primitive Data Type Keywords
Java defines 8 primitive data types:
Integer Types
byte byteValue = 127; // 8-bit, range: -128 to 127
short shortValue = 32767; // 16-bit, range: -32,768 to 32,767
int intValue = 2147483647; // 32-bit, range: -2^31 to 2^31-1
long longValue = 9223372036854775807L; // 64-bit, range: -2^63 to 2^63-1Floating-Point Types
float floatValue = 3.14f; // 32-bit single precision floating point
double doubleValue = 3.14159265359; // 64-bit double precision floating pointCharacter and Boolean Types
char charValue = 'A'; // 16-bit Unicode character
boolean booleanValue = true; // Boolean value: true or falseVariable Reference Keywords
this
Refers to the current object.
public class ThisExample {
private int value;
public void setValue(int value) {
this.value = value; // Distinguish parameter from member variable
}
public ThisExample getThis() {
return this; // Return current object
}
}super
Refers to the parent class.
class Parent {
protected String name = "Parent";
public void display() {
System.out.println("Parent method");
}
}
class Child extends Parent {
private String name = "Child";
public void display() {
super.display(); // Call parent method
System.out.println("Current class name: " + this.name);
System.out.println("Parent class name: " + super.name);
}
}null
Represents a null reference.
String str = null; // Null reference
if (str == null) {
System.out.println("String is null");
}Object and Type Related Keywords
new
Creates new objects.
// Create objects
ArrayList<String> list = new ArrayList<>();
String str = new String("Hello");
// Create arrays
int[] numbers = new int[10];instanceof
Checks object type.
Object obj = "Hello World";
if (obj instanceof String) {
String str = (String) obj;
System.out.println("This is a string: " + str);
}class
Gets the Class object of a class.
Class<?> stringClass = String.class;
System.out.println("Class name: " + stringClass.getName());
// Can also get through object
String str = "Hello";
Class<?> objClass = str.getClass();Other Important Keywords
void
Indicates that a method returns no value.
public void printMessage() {
System.out.println("This method returns no value");
}interface
Defines an interface.
interface Drawable {
void draw(); // Interface method (default is public abstract)
default void defaultMethod() {
System.out.println("Default method");
}
}
class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}implements
Implements an interface.
class Rectangle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}extends
Inherits from a class.
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}Reserved Words
The following are Java reserved keywords that are not currently in use, but reserved for future versions:
- const: Constant declaration (not used, use final instead)
- goto: Jump statement (not used, Java does not support goto)
Strict Floating Point Keyword
strictfp
Ensures portability of floating point calculations.
strictfp class StrictMath {
public double calculate(double a, double b) {
return a * b; // Calculated strictly according to IEEE 754 standard
}
}Assertion Keyword
assert
Used for assertion checking during debugging.
public void validateInput(int value) {
assert value > 0 : "Value must be greater than 0";
System.out.println("Input value: " + value);
}Enumeration Keyword
enum
Defines an enumeration type.
enum Color {
RED, GREEN, BLUE;
public void printColor() {
System.out.println("Color: " + this.name());
}
}
public class EnumExample {
public static void main(String[] args) {
Color color = Color.RED;
color.printColor();
}
}Keyword Usage Notes
Case Sensitive: Java keywords are all lowercase.
Publicis not a keyword, butpublicis.Cannot Be Used As Identifiers: Keywords cannot be used as variable names, method names, class names, etc.
// Wrong examples
int class = 10; // Error: class is a keyword
void if() {} // Error: if is a keyword
// Correct examples
int className = 10; // Correct
void ifCondition() {} // CorrectContext Sensitive: Some words are only keywords in specific contexts, such as
var(Java 10+).Version Differences: Different Java versions may introduce new keywords, such as:
- Java 1.2:
strictfp - Java 1.4:
assert - Java 5:
enum - Java 10:
var(contextual keyword)
- Java 1.2:
Best Practices
Memorize Common Keywords: Focus on mastering commonly used keywords for access control, program control, and exception handling.
Understand Keyword Meanings: Not only know the syntax, but also understand the purpose and use cases of each keyword.
Avoid Naming Conflicts: Avoid using keywords or names similar to keywords when choosing variable names.
Use Modifiers Appropriately: Choose appropriate access modifiers and other modifiers based on actual needs.
Exception Handling: Properly use try-catch-finally and throws keywords to handle exceptions.
By mastering these Java keywords, you will be able to better understand and write Java code, building well-structured and fully functional Java applications.