Java keywords are a set of reserved words that have specific meanings in the Java programming language. These words are essential to the Java syntax and cannot be used as names for variables, methods, classes, or any other constructs.
Keywords are crucial for the structure and organization of Java code. They express certain concepts and operations in the language and allow the Java compiler to interpret and execute the code. For instance, you can use the “for” keyword to create a loop and the “class” keyword to define a new class.
It is important to understand and use Java keywords correctly in your code because they help to ensure that your code is properly structured and follows the rules of the Java language. Incorrect use of keywords can lead to syntax errors and other issues that can make your code difficult to read and debug.
List of Java Keywords
Here is a table of Java keywords, organized in alphabetical order and grouped by category:
Keyword | Category | Description |
---|---|---|
abstract | OOP | Indicates that a class or method is incomplete and must be implemented in a subclass. |
assert | Debugging | Enables runtime checks to verify the truth of a boolean expression. |
boolean | Primitive Type | Represents a boolean value (true or false). |
break | Flow Control | Terminates the execution of a loop or switch statement. |
byte | Primitive Type | Represents an 8-bit integer value. |
case | Flow Control | Specifies a label for a block of code within a switch statement. |
catch | Exception Handling | Specifies a block of code that is executed if an exception is thrown in the try block. |
char | Primitive Type | Represents a single 16-bit Unicode character. |
class | OOP | Defines a new class. |
const | Deprecated | Was used to define a constant field (no longer used in Java). |
continue | Flow Control | Skips the remaining code in a loop and goes to the next iteration. |
default | Flow Control | Specifies a block of code that is executed if no case matches the value in a switch statement. |
do | Flow Control | Begins a loop that executes a block of code until a specified condition is met. |
double | Primitive Type | Represents a double-precision floating-point value. |
else | Flow Control | Specifies a block of code that is executed if a condition is false. |
enum | OOP | Defines an enumerated type, which is a set of named constants. |
extends | OOP | Indicates that a class is a subclass of another class. |
final | OOP | Indicates that a field, method, or class cannot be overridden or modified. |
finally | Exception Handling | Specifies a block of code that is always executed, whether or not an exception is thrown in the try block. |
float | Primitive Type | Represents a single-precision floating-point value. |
for | Flow Control | Begins a loop that executes a block of code until a specified condition is met. |
goto | Deprecated | Was used to transfer control to a labeled statement (no longer used in Java). |
if | Flow Control | Specifies a block of code that is executed if a condition is true. |
implements | OOP | Indicates that a class implements a particular interface. |
import | Compilation | Specifies a list of classes or packages to be imported. |
instanceof | OOP | Determines whether an object is an instance of a particular class or interface. |
int | Primitive Type | Represents a 32-bit integer value. |
interface | OOP | Defines an interface, which is a set of abstract methods that a class must implement. |
long | Primitive Type | Represents a 64-bit integer value. |
native | Method | Indicates that a method is implemented in native code (e.g. C or C++) rather than in Java. |
new | OOP | Creates a new instance of a class. |
package | Compilation | Specifies the package in which a class is located. |
private | OOP | Indicates that a field, method, or class is accessible only within its own class. |
protected | OOP | Indicates that a field, method, or class is accessible only within its own class and its subclasses. |
public | OOP | Indicates that a field, method, or class is accessible to all classes. |
return | Method | Terminates the execution of a method and returns a value to the calling method. |
short | Primitive Type | Represents a 16-bit integer value. |
static | OOP | Indicates that a field, method, or class belongs to the class rather than to a specific instance of the class. |
strictfp | Method | Indicates that a method must be executed in strict floating-point mode. |
super | OOP | Refers to the parent class of a subclass. |
switch | Flow Control | Begins a switch statement, which compares a value against a list of possible cases. |
synchronized | Method | Indicates that a method can be accessed by only one thread at a time. |
this | OOP | Refers to the current object. |
throw | Exception Handling | Throws an exception to be caught by an enclosing try block. |
throws | Method | Indicates that a method may throw an exception. |
transient | Field | Indicates that a field is not part of the persistent state of an object and is not serialized. |
try | Exception Handling | Begins a block of code that may throw an exception. |
void | Method | Indicates that a method does not return a value. |
volatile | Field | Indicates that a field may be modified by multiple threads concurrently and that the field should not be cached. |
while | Flow Control | Begins a loop that executes a block of code until a specified condition is met. |
Note that “const” and “goto” are reserved keywords in Java, but they are not used anymore:
- const: This keyword was used in earlier versions of Java to define a constant field, but it has been deprecated and is no longer used in the language.
- goto: This keyword was also used in earlier versions of Java to transfer control to a labeled statement, but it has also been deprecated and is no longer used in the language.
Java Keyword Usage + Examples
This section of the article delves into the usage of all Java keywords and provides examples of how they can be utilized in code.
abstract
In Java, the abstract
keyword denotes a class or method as abstract
. abstract
classes cannot be instantiated and must be subclassed before they can be used. Similarly, abstract
methods have declarations but no implementation and must be implemented by a subclass.
public abstract class Shape { // Shape is an abstract class public abstract double getArea(); // Abstract method } public class Circle extends Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double getArea() { return Math.PI * radius * radius; // Implementation of the abstract method } }
assert
The assert
keyword allows you to create a boolean expression that the Java runtime evaluates. If the expression is true
, the program continues running as usual. However, if the expression is false
, the program throws an AssertionError
.
You can use the assert
keyword to check the validity of method arguments and confirm the internal state of objects. This keyword is commonly employed to test the validity of arguments passed to a method or to check the internal state of an object.
Example:
public void setAge(int age) { assert age > 0 : "Age must be positive"; this.age = age; }
boolean
The keyword boolean
declares a boolean
variable, which can store either true
or false
. Boolean
variables are frequently used in conditional statements to manipulate program flow.
boolean isValid = true; if (isValid) { System.out.println("The value is valid"); } else { System.out.println("The value is invalid"); }
break
The Java keyword break
allows a programmer to exit a loop or switch
statement before it has completed. When a break
statement is encountered, the loop or switch
is immediately terminated and the program continues with the next statement after the loop or switch
.
for (int i = 0; i < 10; i++) { if (i == 5) { break; } System.out.println(i); // Outputs 0, 1, 2, 3, 4 }
byte
Use the byte
keyword to declare a variable of the byte
type, a primitive data type that represents an 8-bit signed integer. The byte
type is useful for conserving memory when manipulating large arrays of data.
byte b = 100; byte c = (byte) (b + 200); // 300 is too large for a byte, so it overflows to 44 System.out.println(c); // Outputs 44
case
The case
keyword is used in a switch
statement to specify a branch of code to execute based on the value of a char
, byte
, short
, int
, or String
expression. The case
keyword is followed by a value and a colon, and the branch of code is terminated with a break
statement. If no case
value matches the expression, a default branch can be specified with the default
keyword.
int day = 3; switch (day) { 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("Invalid day"); break; } // Outputs "Wednesday"
catch
The catch
keyword is used in a try-catch
block to handle exceptions that may be thrown in the try
block. The catch
keyword is followed by a class or interface type, and the exception is passed as an argument to the catch block. The catch block contains the code to handle the exception, such as logging the error or displaying an error message to the user.
try { int[] arr = new int[5]; arr[10] = 100; // This line throws an ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: " + e.getMessage()); } // Outputs "Error: 10"
char
The char
keyword declares a variable of the char
type, a primitive data type that holds a single 16-bit Unicode character. Programmers often use char variables to store characters or symbols
char c = 'a'; System.out.println(c); // Outputs "a"
class
In Java, the class
keyword creates a new class. A class is a template for creating objects, and it defines the properties and behaviors of those objects. The class
keyword is followed by the name of the class and a set of curly braces containing the class members (fields, methods, etc.).
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } }
continue
The continue
keyword is used to skip the remainder of the current iteration of a loop and move on to the next iteration. When a continue
statement is encountered, the loop’s update expression is executed and the loop’s condition is reevaluated.
for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; } System.out.println(i); // Outputs 1, 3, 5, 7, 9 }
default
The default
keyword is used in a switch
statement to provide a block of code that will be executed if none of the case
labels match the value of the switch
expression. The default
block is optional and can appear at most once in a switch
statement.
int i = 3; switch (i) { case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; default: System.out.println("Other"); } // Outputs "Other"
do
To create a do-while
loop, we use the do
keyword. This loop type executes a block of code at least once, and then repeats the loop as long as a specified condition remains true.
Importantly, the condition is checked after each iteration of the loop. In other words, the do-while
loop guarantees that the loop will run at least once.
int i = 0; do { System.out.println(i); // Outputs 0, 1, 2, 3, 4 i++; } while (i < 5);
double
The keyword double
declares a variable of type double
, which is a primitive data type that represents a double-precision 64-bit floating-point number. Developers frequently use the double
type to store decimal values and perform floating-point arithmetic.
double d = 3.14; double e = d * 2; // e is now 6.28 System.out.println(e); // Outputs 6.28
else
The else
keyword pairs with an if
statement to execute a block of code when the if
statement’s condition is false
. The else
block is optional and can only appear once in an if
statement.
int i = 3; if (i == 1) { System.out.println("One"); } else { System.out.println("Other"); // Outputs "Other" }
enum
The keyword enum
allows developers to create an enumeration, a specific type of class that holds a fixed set of values. These values can be related constants, such as the days of the week or the suits in a card deck. Enumerations are useful for organizing and using a set of related constants.
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
extends
The extends
keyword is used in a class declaration to specify that the class is a subclass of another class. The subclass (also known as the child class) inherits the members of the superclass (also known as the parent class), including fields and methods.
public class Employee extends Person { // Employee is a subclass of Person }
final
The Java keyword final
has various uses, including in the following situations:
- When applied to a variable, it means that the variable’s value cannot be changed once it is assigned.
final int X = 10; // X is a constant that cannot be changed
- When applied to a method, it means that the method cannot be overridden by a subclass.
public final void printMessage() { // printMessage() cannot be overridden System.out.println("Hello, world!"); }
- When applied to a class, it means that the class cannot be subclassed.
public final class MyClass { // MyClass cannot be subclassed // Members and methods }
finally
The finally
keyword is used in a try-catch-finally
block to specify a block of code that will always be executed, whether or not an exception is thrown. The finally
block is typically used to release resources or perform other cleanup tasks.
The finally
keyword ensures that a block of code will always execute, regardless of whether an exception occurred in the try-catch block. This block is often used to release resources or perform other cleanup tasks.
try { // Code that might throw an exception } catch (Exception e) { // Code to handle the exception } finally { // Code that will always be executed }
float
The float
keyword declares a variable as a float
, a primitive data type that stores a single-precision 32-bit floating point number. This type is often used to represent decimal values that have a certain level of precision. Additionally, the float
type is ideal for representing decimal values.
float f = 3.14f; float g = 0.1f; float h = f + g; // h is 3.24
for
To create a loop that iterates a predetermined number of times, you can use the for
keyword. This loop has three components:
- an initialization statement,
- a condition that gets checked before each iteration,
- an increment or decrement statement.
Firstly, the initialization statement sets the starting point for the loop. Next, the condition is evaluated. If it is true, the loop continues to run. Otherwise, it stops. Lastly, the increment or decrement statement updates the loop variable, allowing the loop to move to the next iteration or end.
for (int i = 0; i < 10; i++) { System.out.println(i); // Outputs 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
if
Use the if
keyword to specify a condition that, when met, allows a block of code to execute. Follow this if
statement with an optional else
clause to execute a different block of code if the condition is not met.
For example: “If the weather is sunny, go to the beach. Otherwise, stay indoors.” This use of the if
and else
keywords allows you to control the flow of your program and make it more dynamic.
int x = 10; if (x > 5) { System.out.println("x is greater than 5"); } else { System.out.println("x is not greater than 5"); }
implements
The implements
keyword is used in a class declaration to specify that the class implements one or more interfaces. An interface is a set of related methods that a class must implement in order to conform to the interface.
public class Employee implements Comparable<Employee> { // Employee implements the Comparable interface }
import
The import
keyword is used to include a package or class from another package in a Java program. It allows the use of classes from the imported package or class without specifying the fully qualified name.
import java.util.List; // Allows the use of the List class without specifying its package
instanceof
The instanceof
keyword in Java allows you to test if an object belongs to a specific class or implements a particular interface. This operator returns true
if the object is indeed an instance of the class or interface in question, or false
if it is not.
if (obj instanceof String) { String str = (String) obj; // Code that operates on the String object }
int
To declare a variable of type int
, you must use the int
keyword. This primitive data type represents a 32-bit signed integer and is commonly used for storing whole numbers that do not need a wide range or a decimal component.
int x = 10; int y = 20; int z = x + y; // z is 30
interface
The interface
keyword is used to define an interface, which is a set of related methods that a class must implement in order to conform to the interface. An interface specifies the behavior that a class must implement, but does not provide any implementation details.
public interface Comparable<T> { int compareTo(T o); }
long
Use the long
keyword to declare a variable of the long
type, a primitive data type that stores a 64-bit signed integer. The long data type is often chosen to store whole numbers that need a larger range than what the int
type can offer.
long x = 100000000000L; // The L indicates that the value is of type long long y = 200000000000L; long z = x + y; // z is 300000000000
native
You can use the native
keyword to declare a method written in a language other than Java and accessed through the Java Native Interface (JNI). You may use native methods to access system resources or perform tasks that are difficult or impossible to achieve using pure Java code. These methods are implemented in native code.
public native void callNativeMethod();
new
The new
keyword is used to create a new instance of a class. It is followed by the name of the class and a set of parentheses that may contain arguments to pass to the class’s constructor.
String str = new String("Hello, world!");
package
The package
keyword is used to specify the package to which a class belongs. A package is a namespace that organizes a set of related classes and interfaces. The package
statement should be the first statement in a Java source file and should be followed by the name of the package.
package com.example; public class MyClass { // Class belongs to the com.example package }
private
The Java keyword private
restricts access to class members (fields or methods) within the class itself. These private members are not accessible outside the class, not even by subclasses. In other words, private members can only be accessed within the class in which they are defined.
public class MyClass { private int x; // x can only be accessed within MyClass public void setX(int x) { this.x = x; } }
protected
The protected
keyword is used to specify that a member of a class is accessible within the class and its subclasses. A protected member cannot be accessed from outside the class or its subclasses.
public class MyClass { protected int x; // x can be accessed within MyClass and its subclasses public void setX(int x) { this.x = x; } }
public
Use the keyword public
to make a class member accessible from any other class. This means that even if a public member is in a different package, it can still be accessed from any class. In other words, you can use public members from any class, regardless of their location in the program
public class MyClass { public int x; // x can be accessed from any class public void setX(int x) { this.x = x; } }
return
The return
keyword is used to exit a method and return a value to the caller. The return
statement is followed by the value to be returned. If the method is declared to return a value (e.g. int
, double
, etc.), the value returned must be of the same type. If the method is declared to return void
, no value is returned.
public int getSum(int x, int y) { return x + y; // Returns the sum of x and y to the caller } public void printMessage() { System.out.println("Hello, world!"); return; // Returns nothing to the caller }
short
Declaring a variable of the short
type, which is a primitive data type representing a 16-bit signed integer, uses the short
keyword. In contrast to the int
type, which has a larger range, the short
type is often chosen to store whole numbers that require a smaller range than the int
type but a larger range than the byte
type.
short x = 10000; short y = 20000; short z = (short) (x + y); // z is 30000
static
The static
keyword is used to specify that a member of a class belongs to the class itself, rather than to a specific instance of the class. A static member can be accessed without creating an instance of the class, using the name of the class and the dot operator.
public class MyClass { public static int x; // x belongs to the class, not to a specific instance public static void setX(int x) { MyClass.x = x; } }
strictfp
The strictfp
keyword is used to specify that a class, interface, or method is to be implemented in strict floating-point mode. In strict floating-point mode, all intermediate results of floating-point operations are computed with strict precision, ensuring that the results are consistent across all platforms.
public strictfp class MyClass { // MyClass is implemented in strict floating-point mode }
super
To refer to the immediate superclass of a class, you can use the super
keyword. This is commonly used to access members of the superclass that have been overridden in the subclass or to call the superclass’s constructor. Additionally, using the super
keyword allows you to take advantage of the functionality and features of the superclass in the subclass.
public class Employee extends Person { public Employee() { super(); // Calls the constructor of the Person class } @Override public void printName() { super.printName(); // Calls the printName() method of the Person class System.out.println(" (Employee)"); } }
switch
The switch
keyword is used to create a multi-way branch statement, which allows the program to execute different code blocks depending on the value of an expression. The expression is compared to a series of case
labels, and the code block associated with the first matching label is executed.
int x = 2; switch (x) { case 1: System.out.println("x is 1"); break; case 2: System.out.println("x is 2"); break; default: System.out.println("x is not 1 or 2"); break; }
this
The keyword this
refers to the current object and is frequently utilized to access members of the object that have been overshadowed by local variables or parameters. In other words, it allows the programmer to access elements of the current object that have been masked by variables or parameters with the same name.
public class MyClass { private int x; public MyClass(int x) { this.x = x; // Assigns the value of the parameter to the field } }
throw
To throw an exception explicitly, you can use the throw
keyword in Java. This keyword must be followed by an instance of the Throwable
class or one of its subclasses, such as Exception
or RuntimeException
.
Keep in mind that exceptions are objects that signal an unusual or unexpected event has occurred during the execution of a program. Therefore, it is important to use the throw keyword correctly and only in appropriate situations.
Alternatively, you can also use the throws
keyword in a method declaration to indicate that the method may throw a specified exception. This is different from the throw
keyword, which actually throws the exception.
if (x < 0) { throw new IllegalArgumentException("x must be non-negative"); }
throws
The throws
keyword is used in a method declaration to specify that the method may throw one or more exceptions. The throws
clause lists the types of exceptions that the method may throw, and the caller of the method is responsible for catching and handling the exceptions.
public void parseFile(String fileName) throws IOException { // Code that may throw an IOException }
transient
The Java keyword transient
indicates that a field should not be serialized during the process of converting an object to a stream of bytes, known as serialization. When an object is deserialized, fields marked as transient
will not be included in the resulting object and will not retain their original value. This keyword allows developers to exclude specific fields from the serialization process, potentially improving efficiency or security.
public class MyClass implements Serializable { private int x; private transient int y; // y will not be serialized // Other members and methods }
try
The try
keyword is used to enclose a block of code that may throw an exception. The try
block is followed by one or more catch
blocks that handle the exception, and an optional finally
block that is always executed when the try
block exits.
try { // Code that may throw an exception } catch (IOException e) { // Code to handle the IOException } finally { // Code that is always executed }
void
The keyword void
indicates that a method will not return any value. When declaring a method to return void, you should not include a return
statement in the body of the method.
public void printMessage() { System.out.println("Hello, world!"); }
volatile
To ensure that multiple threads can modify a field concurrently, you can use the volatile
keyword. When a field is marked as volatile
, it is not stored in local memory, but rather read from and written to main memory. This guarantees that all threads can see the updated value of the field.
In other words, the volatile
keyword allows for visibility of the field across threads.
public class MyClass { private volatile boolean flag; // flag can be modified by multiple threads // Other members and methods }
while
The while
keyword allows you to create a loop that will continually execute a block of code as long as a particular condition remains true
. Once the condition becomes false
, the loop will terminate.
To use the while
keyword effectively, you must ensure that the condition will eventually become false
, otherwise the loop will run indefinitely. Additionally, it is important to consider the logic of the condition, as it will determine the behavior of the loop.
int x = 0; while (x < 10) { System.out.println(x); x++; }
Errors and Challenges when Using Java Keywords
Using a keyword as a variable name
One of the most basic mistakes that developers can make when using Java keywords is attempting to use a keyword as a variable name. As mentioned previously, Java has a set of reserved words that have specific meanings and cannot be used as names for variables, methods, classes, or other constructs. If a developer tries to use a keyword as a variable name, they will receive a compile-time error.
To avoid this mistake, it is important for developers to be familiar with the list of Java keywords and to use only non-keyword names for variables, methods, and other constructs. It is also a good idea to use a Java Integrated Development Environment (IDE) that provides syntax highlighting, as this can make it easier to spot keywords and avoid using them as variable names.
Misusing a keyword in a conditional statement
Another pitfall to watch out for when using Java keywords is misusing a keyword in a conditional statement. For example, if a developer uses the “else” keyword without an accompanying “if” statement, it will result in a syntax error. Similarly, if a developer uses the “case” keyword without an accompanying “switch” statement, it will also result in a syntax error.
To prevent these errors, you should carefully plan your program’s logic and double-check that you use all keywords correctly. An Integrated Development Environment (IDE) with error checking can also help by alerting you to any syntax errors with keyword usage.
Using a keyword as a method or class name
Just like using a keyword as a variable name, using a keyword as a method or class name will also result in a compile-time error. It is important to choose non-keyword names for all methods and classes to avoid this mistake.
Confusing the meanings of similar keywords
Some Java keywords have similar meanings or functions, which can lead to confusion for developers.
For example, the “final” and “finally” keywords are often confused, as they have different uses and contexts. The “final” keyword is used to declare a variable or method as “final”, meaning that it cannot be changed or overridden, whereas the “finally” keyword is used in a try-catch block to specify a block of code that should always be executed, regardless of whether an exception is thrown.
Not properly nesting keywords
Some Java keywords, such as “if” and “for”, require a specific structure or nesting order. If a developer does not properly nest these keywords, it can result in a syntax error. For example, if an “if” statement is not properly closed with a corresponding “endif” statement, it will result in an error.
Tips and best practices
To avoid these and other mistakes when using Java keywords, there are a few tips and best practices that developers can follow:
- Familiarize yourself with the list of Java keywords and avoid using them as variable names or other constructs.
- Use an IDE that provides syntax highlighting and error checking to make it easier to spot mistakes.
- Carefully plan out the logic of a program and double-check that all keywords are being used correctly.
- Regularly review and test code to catch any errors involving the misuse of keywords.
- If in doubt about the correct usage of a keyword, refer to the official Java documentation.
In conclusion, Java keywords are a fundamental aspect of the Java programming language. As reserved words, they have specific meanings and cannot be used as names for variables, methods, classes, or other constructs. It is important for developers to understand the meaning and usage of each keyword in order to write correct and effective code.
By familiarizing themselves with the full list of Java keywords and understanding how to use them appropriately, developers can ensure that their code is clear, concise, and reliable. As with any skill, practice is key to mastering the use of Java keywords. We encourage readers to incorporate these keywords into their coding practices and to refer back to this article as a useful resource.