Programs

Keywords in Java: List of All Top Java Keywords

Keywords in Java refer to any of the 52 reserved terms with a predefined meaning in the programming language. Hence, they cannot be used as names for methods, variables, objects, classes, subclasses, or identifiers. In other words, these Java keywords add unique meaning to the Java compiler and are reserved for special purposes. Therefore, using them as identifier names will cause the compiler to give an error. In Java, there are a total of 52 reserved keywords. Out of these, 49 are in use, two are not in use, and one is in preview.

Top Keywords in Java Every Programmer Should Know

We have rounded up some of the most relevant keywords in Java, their use, and examples in the list below.

1. abstract

The abstract keyword in Java is used to declare an abstract class. The abstract class can contain abstract and non-abstract methods but cannot be used to create objects. An abstract method does not have a body and can only be used in an abstract class. The subclass it is inherited from provides the body. Moreover, while abstract classes can be extended, they cannot be instantiated. Plus, the abstract keyword cannot be used with constructors and variables. 

Given below is a code snippet to show an abstract class with an abstract method :

abstract class Vehicle  

{  

    abstract void car(); 

}  

class Maruti extends Vehicle  

    @Override  

    void car() {  

        System.out.println(“Car is moving”);  

    }  

}  

public class AbstractExample1 {  

    public static void main(String[] args) {  

    Maruti obj=new Maruti();  

    obj.car();  

    }         

}  

Output: Car is moving

2. boolean

A primitive data type, the boolean keyword in Java can store only two values – true and false. The default value of the boolean keyword is false, and it is typically used with conditional statements. However, the boolean keyword can be applied to methods and variables and declaring any variable with the boolean keyword means that it holds boolean values.

Given below is a simple boolean example in Java:

public class BooleanExample1 {  

    public static void main(String[] args) {  

        int num1=67;  

        int num2=43;  

    boolean b1=true;  

    boolean b2=false;  

if(num1<num2)  

{  

    System.out.println(b1);  

}  

else  

{  

    System.out.println(b2);  

    }         

}  

Output: false

3. class

The class keyword in Java is one of the most commonly reserved terms. It is used to declare a class in Java containing the block of code with fields, methods, constructors, etc. A class may contain one or more classes, a concept known as nested class. Every object is an instance of a class, and the class name should be such that it is unique within a package. One can only assign abstract, public, strictfp, and the final modifier to a class. But other modifiers such as private, protected, and static can be assigned to the inner class.

Given below is a simple example of the class keyword:

public class ClassExample {  

    public static void main(String[] args) {     

        System.out.println(“Greetings!”);  

    }  

}  

Output: Greetings!

4. default

The default keyword in Java is an access modifier. Thus, if one does not assign any access modifier to methods, variables, classes, and constructors by default, it is considered a default access modifier. Alternatively, the default keyword can be used in switch statements to label a block of code to be executed if there is no case matching the specified value. From Java 8, the default keyword also finds use in allowing an interface to provide an implementation of a method. The default access modifier is only accessible within the package.

Given below is a code snippet as an example of the default keyword in Java:

class A {  

 String msg=”Access the default variable outside the class within the package”;      

}  

public class DefaultExample2 {  

public static void main(String[] args) {  

    A a=new A();  

   System.out.println(a.msg);  

}  

}  

Output: Access the default variable outside the class within the package

5. enum

The enum keyword in Java is a data type containing a definite set of constants. In other words, enum can be thought of as a class having a fixed set of constants. An enum can be defined inside or outside the class. Plus, since a Java enum inherits the Enum class internally, it cannot inherit any other class. However, it can implement many interfaces. A Java enum can have fields, methods, constructors, and main methods. 

class EnumExample{  

//defining the enum inside the class  

public enum Week { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }  

//main method  

public static void main(String[] args) {  

//traversing the enum  

for (Week w : Week.values())  

System.out.println(w);  

}} 

Output:

SUNDAY

MONDAY

TUESDAY

WEDNESDAY

THURSDAY

FRIDAY

SATURDAY

6. import

The import keyword allows the programmer to access available Java packages. It is used for importing a package, sub-package, an interface, a class, or enum in the Java program. The syntax for using the Java keyword is import packageName.*;

The following code snippet demonstrates the use of the import keyword:

import java.util.*; //imports all the classes and interfaces of the util package  

public class ImportExample  

{  

    /* Driver Code */  

    public static void main(String ar[])  

    {  

        System.out.println(“Using import statement in Java”);  

       /* Method from java.util.Date class. */  

        System.out.println(new Date());  

    }  

}  

Output:

Using import statement in Java

Fri Oct 29 15:42:43 UTC 2021

7. protected

The protected keyword in Java is an access modifier that can be used for attributes, classes, constructors, and methods and is accessible inside the package. It is also accessible outside the package, but only through inheritance. 

The following example shows how a protected variable is accessible outside the class and within the package:

class X {  

 protected String msg=”Access the protected variable outside the class within the package”;  

}  

public class ProtectedExample2 {  

public static void main(String[] args) {  

    X x=new X();  

   System.out.println(x.msg);  

}  

}  

Output:

Access the protected variable outside the class within the package

8. static

The static keyword in Java is primarily used for memory management and can be applied to methods, blocks, variables, and nested classes. Thus, the static can be a method (class method), variable (class variable), nested class, or block. Static members of a class get stored in the class memory, and one can directly access them through the class name. Thus, there is no requirement of instantiating a class. The most significant advantage of static variables is that they make the program memory-efficient because they get memory in the class area only once during class loading.

Given below is a code snippet to show the use of the static keyword in Java :

class Test

{

// static method

static void abc()

{

System.out.println(“from abc”);

}

public static void main(String[] args)

{

// calling abc without creating

// any object of class Test

abc();

}

}

Output: 

from abc

9. super

The super keyword in Java is a reference variable used to refer to parent class objects. Its primary use is in invoking the immediate parent class methods. Whenever one creates the instance of a subclass, an instance of the parent class is implicitly created, which is referred to by the super reference variable. In a nutshell, the super keyword in Java can call the immediate parent class method, immediate parent class constructor, and refer to the immediate parent class instance variable. 

Given below is a code snippet to show the use of the super keyword in Java :

class Parent {

  String color = “Blue”;

}

class Child extends Parent {

  void getColor() {

    System.out.println(super.color);

  }

}

public class Main() {

  public static void main(String args[]) {

    Child obj = new Child();

    obj.getColor();

  }

}

Output: 

Blue

10. throws

The throws keyword in Java declares an exception -colour it specifies the exceptions that the current method may throw. Thus, the programmer should provide the exception handling code to maintain the normal flow of the program.

The following example demonstrates the use of the throws keyword:

import java.io.IOException;  

class Testthrows{  

  void m()throws IOException{  

    throw new IOException(“device error”);//checked exception  

  }  

  void n()throws IOException{  

    m();  

  }  

  void p(){  

   try{  

    n();  

   }catch(Exception e){System.out.println(“Exception Handled”);}  

  }  

  public static void main(String args[]){  

   Testthrows obj=new Testthrows();  

   obj.p();  

   System.out.println(“Normal Flow”);  

  }  

}  

Output:

Exception Handled

Normal Flow

The above list of keywords in Java is not exhaustive and only describes some of the most commonly used ones. There are several other Java keywords, each serving a specific purpose in the context of the programming language.

On that note, if you want to upscale your Java skills, upGrad’s Job-linked PG Certification in Software Engineering is the right course for you. The 5-month online program is specially curated for those who wish to kickstart a promising career in software development. 

Here are some highlights to give you a sneak peek into what the course has in offer:

  • MERN Stack and Cloud-Native specialisations
  • 500+ content hours with 350+ hours of hands-on training
  • 50+ live sessions and five industry projects
  • Peer networks and discussion forums
  • Career guidance and industry networking

Sign up today to learn from the best in the higher EdTech industry.

1. What is not a Java keyword?

In Java, null, true, and false are not keywords. They are reserved words for literal values and cannot be used as identifiers.

2. Can Java interfaces have variables?

Similar to a class, a Java interface can have variables and methods. However, the methods declared in an interface are abstract by default, meaning they only have the method signature without a body.

3. What is the use of the final keyword in Java?

The final keyword in Java is a non-access specifier used to restrict a variable, class, and method. Thus, if you initialise a variable using the final keyword, you cannot modify its value. Likewise, if you declare a method as final, no subclass can override it. Moreover, a class declared as final cannot be inherited by other classes either.

Want to share this article?

Prepare for a Career of the Future

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks