View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

A Complete Guide to Keywords in Java

By Pavan Vadapalli

Updated on Mar 17, 2025 | 19 min read | 6.5k views

Share:

Java has been used in computer programming for about 25 years and is still widely utilized by programmers today. Over 9 million people use Java. Programming in Java requires an understanding of the language's structure. "How many keywords are in Java?" is a question that developers frequently ask. Java includes 68 reserved keywords as of the most recent version, each of which has a distinct purpose in the language. It is essential to know the keywords in Java to write code that is streamlined and efficient. Programming language reserved words are called keywords in Java. They serve as internal procedures or stand in for predefined activities. As a result, these terms cannot be used as variable names or objects.

In this blog, we will review each of the predefined Java keyword examples, along with their types, usage, and significance in programming.

Understanding Keywords in Java

Java keywords serve as your program's road signs, guiding you to your destination like signposts in a new city. Like the foundation of a building, Java keywords are essential to the organization of your code. Let’s learn these Java reserved words in detail:

What Are Keywords in Java?

Special words with a predetermined meaning for the Java compiler are called Java keywords. Because they are reserved words, they cannot be used in programming languages as:

  • Class names
  • Function names
  • Identifiers
  • Variable names, etc.

However, a compile-time error will occur if we attempt to use them as an identifier, variable name, or other term. In simple words, these are reserved terms that, according to the compiler, have a particular meaning and are not available for use in other contexts.

Java programming keywords are essential for identifying and controlling:

  • Control Flow: Control flow structures that guide code block execution are generated using keywords (if, else, for, while, and switch).
  • Object-Oriented Features: Java keywords such as class, extends, and interface enable the creation and inheritance of classes. Java OOPs concept tutorials can help one master object-oriented features.
  • Access Control: Java keywords, such as public, private, and protected, define the accessibility of classes, methods, and variables to provide encapsulation and security.
  • Data Types: Keywords such as int, double, boolean, and char specify the data type of variables, which determines the type of data that variables can store.
  • Error Handling: To support robust and error-tolerant code, keywords for handling exceptions, such as try, catch, finally, and throw, are used.

Effective use of these keywords enables programmers to create reliable, maintainable, and efficient code.

Total Count of Keywords in Java

With the latest version of Java, 51 reserved keywords in Java have extremely specific meanings and can't be used as application code identifiers. Additionally, 16 contextual keywords are considered keywords if they are discovered in a particular context. That means the total Java keyword count is 67. These keywords should only be used by programmers for their intended purpose.

Recent Additions:

Java has recently added some new Java language keywords for its development. These additions help improve code safety, readability, and maintainability in modern Java development:

  • sealed: The sealed keyword, added to Java 15, restricts which classes can extend or implement a certain class or interface. This keyword provides more control over the hierarchy of inheritance since only certain specified classes can act as subclasses.
  • permits: This is used with the sealed keyword. It defines which subclasses are allowed in a sealed class and essentially declares the allowed classes that will extend it.
  • record: Introduced in Java 14 as a preview feature and standardized in Java 16, the record keyword provides a concise syntax for declaring classes mainly used to store immutable data. Records automatically generate boilerplate code, such as constructors, equals(), hashCode(), and toString() methods.

Unused Reserved Keywords:

Java reserves certain keywords for potential future use, even though they are not actively used in the language. These reserved words cannot be used as identifiers, ensuring compatibility with possible future updates. While they have meanings in other programming languages, Java intentionally avoids using them to promote better coding practices and maintain clarity:

  • goto: Reserved but not used in Java, goto is a control flow statement available in some other programming languages. The use of this statement is typically not recommended since it can create confusing and uncontrollable code structures.

const: Also reserved but not used, const was meant to declare constants. In Java, the final keyword is used for this purpose, allowing variables to be assigned a value that cannot be changed after their declaration.

Categories of Java Keywords 

Java Keywords can be grouped into different categories based on their purpose in the language. These keywords help define data types, control program flow, handle exceptions, manage classes and objects, and more. The following is a comprehensive Java keyword guide with descriptions.

Access Modifiers

Access modifiers define who can access different parts of your code in Java. They help protect data and methods from accidental use or modification. By using access control, you determine how different parts of your program interact, making it more secure and organized.

In simpler terms, these can be viewed as visibility settings. The following table provides an overview of Java access modifiers:

Keywords

Description

public

Indicates that members of any class can access a method, variable, class, or interface.

protected

Specifies that a method or variable is accessible within its class, subclass, or classes from another package.

private

Restricts access so that only the class in which the method or variable is declared can access it.

Class, Method, and Variable Modifiers

In Java, special keywords modify the behavior of classes, methods, and variables. These modifiers help organize code and define certain behaviors, such as making methods belong to a class, preventing variables from being changed, or requiring subclasses to implement abstract methods.

Below is a detailed look at Java keywords in this category:

Keywords

Description

abstract

Declares a class or method as abstract. A class that contains a method without a definition is called an abstract class, whereas the method itself is called an abstract method. When a class or method is declared as abstract, it indicates that the subclass will implement it later.

static

Declares a method or variable as a class-level member instead of restricting it to a specific object.

final

This prevents modification. A final class cannot be subclassed, a final variable can only contain a constant value and a final method cannot be overridden.

strictfp

Ensures consistent floating-point calculations by limiting accuracy and rounding variations for portability.

synchronized

Defines critical sections in multithreaded Java programs to prevent concurrent access issues.

volatile

Indicates that a variable’s value may change asynchronously, often used in multithreading.

transient

Used in serialization to specify that a data member should not be serialized.

native

Specifies that a method is implemented in native code using the Java Native Interface (JNI).

Control Flow Statements

Control flow statements guide a program's decision-making and repetition processes. They enable code to execute specific sections based on conditions or repeat actions multiple times, ensuring the program responds appropriately to different scenarios.

The following table provides an overview of Java keywords used in control flow statements:

Keywords

Description

if

 

In order to test a boolean expression, it is used to specify an if statement.

For instance: 

if(4==2){
  System.out.println(true); 
}

else

It is also used to test a boolean expression in combination with the if statement.

For instance: 

if(4==2){
 System.out.println(true); 
} 
else{
 System.out.println(false);
}

switch

It runs code based on the test value. Once the test value matches each case inside the switch statement, it executes the corresponding test case.

case

This term is used inside the switch statement to indicate different matching cases. However, inside the switch statement, it also indicates a block of text.

As an illustration, consider this:

     int i=2;
     switch(i){
       case 1:
         System.out.println(yes)    
         break;
       case 2:
         System.out.println(no)    
         break;
     }

default

The switch statement, which is run when no case matches the provided value, can optionally employ it.

As an illustration, consider this:

     int i=1;
     switch(i){
       case 1:
         System.out.println(yes)    
         break;
       default:
         System.out.println(no);
     }

for

It is employed in programs to loop through a collection of statements. It is employed to initiate a loop.

As an illustration, consider the following: 

 for(int i=0;i<10;i++){ 
                //Statements inside for loop.
              }

while

Depending on whether a given condition is true or false, it is utilized to carry out a block of statements.

As an illustration:

int j=0;
while(j<100){
    System.out.println(j);
    j++;
}

do

In Java, it creates a do-while loop when combined with the while loop.

As an illustration, consider this: 

     int i=1;
     do{
         System.out.println(yes);    
         i++; 
     }while(i<100);

break

It is a control statement that is used to exit a loop and interrupt its execution.

As an illustration, consider this:

     int i=0;
     while(i<10){
       if(i==5)
           break;
       i++;
     }

continue

It is used to return control to the loop while ignoring all subsequent statements in a program.

As an illustration: 

int j=0;
while(j<10){
  if(j==5){ 
     j++;
     continue;
  }
   System.out.println(j);
   j++; 
}

return

It is used to return a value to the caller method and to indicate that a method has finished running.

An example:

double square(double num){
    return num * num;
}

assert

This keyword enables programmers to confirm the assumptions stated in a program rapidly.

Error Handling

Java provides mechanisms to handle problems that may arise during execution. Programs can catch errors, manage them efficiently, and properly handle resources through specific constructs. This helps prevent crashes and ensures smooth execution. The following table provides an overview of Java keywords related to error or exception handling:

Keywords

Description

try

Specifies a block of code that will be examined for handling exceptions.

catch

This keyword works in tandem with an optional finally block and the try block. It is used to catch an exception and define what to do when the try block throws an exception.

finally

Refers to a block that is always executed when used with the try-catch structure.

throw

Used to throw exceptions, mostly custom exceptions explicitly. However, an instance of an exception must follow it.

throws

Declares exceptions in Java and specifies which exceptions a method may throw.

Object-Oriented Programming

The foundation of Java is object-oriented programming (OOP). This approach to software design centers around data and the operations applied to it. It promotes modularity, reusability, and a clean structure, making complex software systems more manageable. Below is an overview of Java keyword meanings:

Keywords

Description

class

Used to define a class. A class in Java represents a specific type of object.

class A{
   //statements or methods
}

interface

Creates a class-like structure that contains only static interfaces, final fields, and abstract methods. Other classes can later implement these interfaces.

extends

Indicates that a class is inheriting from another class or interface. Used in class definitions.

For example, class A extends B.

implements

Specifies the interfaces that a class implements.

For example, class A implements InterfaceB.

new

Used to create new instances of a class.

this

Refers to the current instance of the class in which it is used.

super

Refers to the superclass (base class) of the current class. It can be used with constructors and methods.

instanceof

Check whether an object is an instance of a specific class or implements an interface.

Package Management

These keywords help organize classes and interfaces into packages, similar to folders in a file system. Package management prevents naming conflicts, improves code maintainability, and enables developers to manage access control and namespaces effectively. This results in cleaner, more efficient code.

The table below lists commonly used Java programming keywords for package management:

Keywords

Description

package

A Java package is declared using this keyword. A collection of classes and interfaces is called a package.

An example of a package:

package com.bookstore.app;

public class Book {
    // Class Implementation
}

import

This keyword is used to include classes or entire Java packages so they can be referenced later in the application without explicitly mentioning the package name.

Example: 

import java.util.Scanner;

Primitive Data Types

Java provides eight basic or primitive data types. These include int for whole numbers and double for decimals. A char represents a single character, and a boolean stores true or false values. These are the building blocks for manipulating data in the language.

The following table provides a category-wise explanation of Java keywords related to primitive data types:

Keywords

Description

byte

8-bit values can be stored in this keyword's data type.

Example:

byte aByte = 100;

short

Used as a data type that can store a 16-bit integer.

Example:

short aShort = 10000;

int

Stores a 32-bit signed integer and is used as a data type in Java.

Example: 

int a = 5;

long

Stores a 64-bit integer as a Java data type.

Example:

long aLong = 100000L;

float

Stores a 32-bit floating-point number.

Example:

float aFloat = 10.5f;

double

Stores a 64-bit floating-point value.

Example:

double aDouble = 20.99;

char

Stores any character defined in the Java character set.

Example:

char aChar = 'A';

boolean

Used to define a boolean variable, which accepts only true or false values. Its default value is false.

Example:

boolean aBoolean = true;

Use upGrad's thorough tutorials on Java keywords and other topics to improve your Java skills. Explore our comprehensive Java tutorials to become an expert Java programmer.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

Contextual Keywords in Java

These are also known as restricted Java identifiers and restricted keywords. They give the code specific meaning. Contextual keywords follow Java keyword restrictions and are interpreted based on their syntactic grammatical position.

Examples of Contextual Keywords in Java

The context in which the following 16 words appear determines whether they are considered keywords or other tokens. The following table shows the Java keyword roles as contextual keywords:

Keywords

Description

exports

modules are imported and exported using exports.

module

This keyword is used to declare a module.

non-sealed

It is used to specify sealed classes and interfaces that are not sealed.

open

It is used for module declaration.

opens

These are used for module import and export.

permits

It enables for defining of interfaces and sealed classes.

provides

It also allows the modules to be imported and exported.

record

It is used to define new records.

requires

This is the specification for module import and export.

sealed

It is used to specify interfaces and classes that are sealed.

to

It is also utilized for module import and export.

transitive

In a RequiresModifier, it is identified as a terminal.

uses

Modules are imported and exported using it.

var

It is employed to determine the types of local variables.

with

Modules are imported and exported using it.

yield

In a switch statement, it is employed to produce a value.

Importance of Contextual Keywords in Java 

Contextual keywords improve code readability by making syntax more intuitive and self-explanatory. Since they function as keywords only in specific scenarios, they prevent conflicts with existing identifiers, ensuring smoother transitions when new language features are introduced. This approach reduces ambiguity while maintaining backward compatibility.

Benefits of using contextual keywords for specific tasks or constructs:

  • Maintains Backward Compatibility: Since these keywords are not globally reserved, older codebases remain unaffected.
  • Improves Code Clarity: They make the intent of a construct more explicit, leading to more readable and maintainable code.
  • Avoids Naming Conflicts: Developers can still use these words as variable names outside their specific keyword context.
  • Supports New Features: Enables Java to introduce modern functionalities without disrupting existing syntax or requiring major rewrites.

Unused Reserved Words in Java

Certain words are reserved for specific purposes in Java, although they are not currently active in the language. These reserved words, along with their possible and future uses, provide insight into Java's design and potential future directions.

What Are Unused Reserved Words?

Unused reserved words are terms that Java has set aside within its syntax but does not currently use. Reserving these words allows Java to incorporate them in future updates without causing compatibility issues with existing code.

By reserving these words, Java ensures they remain unavailable for other purposes. This foresight helps maintain consistency and prevents inconsistencies as the language evolves.

List of Unused Reserved Words

At the moment, the following is the unused  Java keyword list or Java unused reserved words:

  • goto: Originally reserved for unconditional jumps in code, goto was not implemented in Java because it could lead to complex and unreadable code structures.
  • const: Although many programming languages use const for constant values, Java uses the final keyword instead, making const unnecessary.
  • strictfp: Initially used to enforce strict floating-point calculations for platform portability, strictfp became unnecessary when later Java versions adopted always-strict floating-point semantics.

Potential Future Use of Reserved Words

As programming paradigms evolve, certain scenarios may arise where these reserved words become relevant again. For example, new control structures or enhancements in constant variable declarations could lead to the reconsideration of goto or const. However, any such activation would be carefully evaluated, as Java remains committed to code clarity and simplicity.

Java keyword purposes ensure flexibility for future language development while maintaining the integrity of existing programs.

Explore upGrad’s blogs on Java Free Online Course with Certification in 2025 to improve your programming skills and become an expert developer.

The Default Keyword in Java

The default keyword is primarily used in switch statements. It enables a variable to be compared against a list of values to check for equivalence. Each value is referred to as a case, and each case involves checking the variable being evaluated.

A special case that executes without requiring a matching value is represented by default. If a break or exit statement appears before the default statement in any of the previous cases, it will prevent the default case from being executed. The default case is optional.

Usage in Switch Statements

If no case matches the switch expression, the default keyword specifies which block of code should be executed. The following example demonstrates the functionality of the default Java keyword functions in switch statements:

public class DefaultSwitchExample {
    public static void main(String[] args) {
        int day = 5;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;

            case 3:
                System.out.println("Wednesday");

                break;

                // other cases
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}

If the value of the day in this example does not match any of the listed cases, the default case is executed. This means that if you enter any input other than 1 to 7, the output will be "Invalid day."

Introduction of Default Methods 

Before Java 8, interfaces could only have abstract methods, and their implementations had to be provided in a separate class. If a new method was added to an interface, its implementation code had to be included in every class that implemented the interface.

Java 8 resolved this issue by introducing default methods, which allow interfaces to have methods with implementations without requiring modifications to the implementing classes.

The syntax of a default method is as follows:

public interface Example {
   // Default method with an implementation
   default void print() {
      System.out.println("This is a default method!");
   }
}

Now let’s see an example of a default method in Java:

interface MyExampleInterface
{
    public void cube(int num); // abstract method
    
    default void print() // default method
    {
      System.out.println("This is a default method!");
    }
}
  
class MyClass implements MyExampleInterface
{
    // implementation of cube abstract method
    public void cube(int num)
    {
        System.out.println(num*num*num);
    }
  
    public static void main(String args[])
    {
        MyClass obj = new MyClass();
        obj.cube(5);
        
        obj.print(); // default method executed
    }
}

The output of the above-mentioned code is as follows:

125

This is a default method!

How to Implement All the Keywords in Java Effectively

Proper keyword use in Java is essential for writing clear, efficient, and maintainable code. By mastering these keywords appropriately, developers can ensure that their code functions correctly. Strictly following best practices increases readability and reduces the chances of errors during execution. Predictable behavior in code minimizes miscommunication within a team and allows future developers to understand the system easily. Additionally, it helps maintain the codebase more efficiently.

Best Practices for Java Keywords

The following list of tips and tricks can enhance your Java keyword usage.

  • Avoid naming variables with Java keywords: Using a keyword as an identifier or variable will cause a syntax error.
  • Use meaningful names: Ensure that class, method, and variable names are descriptive, and avoid ambiguous acronyms.
  • Be mindful when using frameworks: Pay attention to keywords when dynamically creating classes or methods, especially when working with frameworks that generate code automatically.
  • Effectively use keywords to organize your code: For thread safety and efficiency in multithreaded applications, use appropriate keywords like final, synchronized, and volatile.
  • Use access modifiers: Utilize access modifiers (public, private, protected) to encapsulate data and define visibility for classes, methods, and variables, ensuring modularity and security.
  • Handle exceptions properly: Use try, catch, and finally, blocks to manage exceptions effectively. This ensures resource management and prevents potential errors.

Common Pitfalls to Avoid

While programming in Java, it is important to be aware of common pitfalls that can impact performance and maintainability. Here are some mistakes to avoid:

  • Static Variables Overuse: Static keywords and variables are useful. Excessive use can lead to memory leaks and unintended side effects, especially in multithreaded environments.
  • Misapplying the final keyword: Incorrect use of final may limit modification possibilities, such as preventing method overriding or variable reassignment, thus reducing flexibility.
  • Neglecting Exception Handling: Failing to handle exceptions properly can cause programs to crash unexpectedly, leading to poor user experience and system instability.
  • Ignoring Thread Safety: Not considering thread safety can lead to concurrency issues, resulting in unpredictable behavior in multithreaded applications.

Tools for Effective Keyword Utilization

Making use of the right tools may improve your proficiency in using Java keyword definitions correctly.

  • IDEs, or integrated development environments: Use robust IDEs like IntelliJ IDEA, Eclipse, or NetBeans, which provide capabilities like code completion, syntax highlighting, and real-time error detection to avoid keyword abuse.
  • Static Code Analysis Tools: Use tools like Checkstyle and SonarQube to automatically detect coding inconsistencies and enforce coding standards to ensure the correct use of keywords.
  • Version Control Systems: Then comes version control, like Git, where you can check the changes for keyword usage and maintain integrity at the code level.

Conclusion

Mastering Java keyword descriptions. is essential for developing robust and efficient applications. These reserved words form the foundation of Java syntax, shaping the structure and behavior of your code. Proper application of these keywords enables you to write clear, maintainable, and error-free programs. Continuous learning through the best Java courses and consistent practice will refine your coding skills, helping you unlock your full potential in Java development.

Ready to dive deeper into Java keywords? Explore upGrad’s in-depth and free core Java certification course to enhance your coding skills!

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

References:
https://www.linkedin.com/pulse/rising-demand-java-developers-today-aspire-techsoft-0schf/
https://www.linkedin.com/pulse/java-keywords-reserved-words-nareshit-naresh-i-technologies-43jhc/

Frequently Asked Questions

1. What is Java's main keyword?

2. What distinguishes Java keywords from identifiers?

3. In Java, are "true," "false," and "null" keywords?

4. What does the 'final' keyword mean in Java?

5. Why are 'const' and 'goto' reserved in Java and not used?

6. How is 'abstract' different from 'interface' in Java?

7. What impact does the Java 'static' keyword have on a function or variable?

8. What function does the Java 'synchronized' keyword serve?

9. Could you explain about the 'transient' keyword?

10. What does the 'volatile' keyword in Java mean?

11. How is the 'assert' keyword used in Java?

Pavan Vadapalli

899 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program