Keywords in Java – Java Reserved Words

In any programming language, there are some fundamental concepts that you need to know before you can write even the most elementary programs, such as the case with Java programming language as well. This article introduces you to one of the Java fundamentals where you will learn the Java keywords. This is one of the basic units which helps to form a class in Java. Let us start our discussion with what is keywords in Java and then we will discuss some main keywords in Java that we frequently use in our Java programs.

Keywords in Java

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is Keyword in Java?

The smallest individual unit in a Java program is called a Token in Java.Java has 5 tokens and the keyword is one of the tokens in Java. A keyword is a reserved word that conveys special meaning to the Java compiler. These are reserved for special purposes and we cannot use them as identifier names otherwise the compiler will give an error.

In Java. there are 51 keywords, but 2 of them are not used which are-goto and const. Only 49 keywords are used in Java. All of them have different purposes and meanings. Below is the Java Keyword List:

List of Java Keywords

Let’s discuss each of them briefly:

1. abstract keyword

The abstract keyword in Java is used when we declare a class as an abstract class. Making a class as an abstract class restricts itself from creating its object. The abstract class can contain both abstract or non-abstract methods. We can extend this class but can not instantiate it. The keyword is placed before the class name as:

abstract class ClassName {
  //code inside the abstract class
}

2. boolean keyword in java

The boolean keyword in Java is used to declare the variables of a boolean data type. If we declare any variable with a boolean keyword, then it holds boolean values. There can be only two boolean values which are – true and false.

boolean myVar;
myVar = false;

3. assert keyword in java

The assert keyword in Java is used to achieve an assertion in Java. Assertion helps in checking the assumptions made in the Java programs. The assert keyword is used with boolean expressions in two different ways:

The first way of using assert keyword is:

assert booleanExpression;

The second way of using assert keyword is:

assert booleanExpression1: booleanExpression2;

4. break keyword

The break keyword in Java is used to break from a looping statement of Java. We can use the break keyword as a statement. We write in a single line with a semicolon. When we use it with either for, while or do-while loop, the control flow reaches to the end of the respective loop. We also use it in the switch statement.

For example:

for (int num = 0; num < 10; num++)
if (num % 2 == 0) break;

5. byte keyword

The byte keyword in Java is used to define a variable with a byte data type. The byte data type can hold 8-bit values.

byte myVar = 100;

6. case keyword

The case keyword in Java is used in switch statements to write different options. We write each option with the case statement and the condition is checked around each case of the switch statement.

switch (expression) {
case option1:
  //statement
case option2:
  //statement
case option3:
  //statement
case option4:
  //statement
case option5:
  //statement
}

7. catch keyword

The catch keyword in Java is used together with the try statements. It is used to catch the exceptions generated by the try block. The catch block cannot be used alone; it has to be used only after the catch block.

try {
  //statements
}
catch {
  //statements
}

8. class keyword

The class keyword in Java is used to declare a class in Java. A class is a collection of methods and data members.

class MyClass {
  //fields
  //member functions
}

9. char keyword

The char keyword in Java is used to declare a variable of a char data type. The char data type can be used to hold a value of 16-bit Unicode characters.

char myChar = ‘T’;

10. continue keyword

The continue keyword is used with the looping statement to send the current control flow back to the starting of the loop without executing the further statements after the continue statement.

while (i < 10) {
  if (i % 3 == 0) continue;
}

11. default keyword

The default keyword in Java is used with the switch statements when we want to specify the default block of code. When no condition matches any case statement, then the default case is executed.

switch (expression) {
case option1:
  //statement
case option2:
  //statement
case option3:
  //statement
default:
  //statement
}

12. do keyword

The do keyword in Java is used in control flow statements with the while statement. They are collectively known as- do-while loop. Using the do statement allows the statement(s) to iterate multiple times until the condition matches.

do {
  //statements
} while ( test - expression )

13. double keyword

The double keyword is used to declare a variable with a double data type. The double data type holds 64-bit floating-point values.

double myDouble = 344.78;

14. else keyword

The else keyword in Java is used as a decision-making statement and it is used after the if statement. If the condition of the if statement evaluates to false then the else statement is executed.

if (condition) {
  Statements
  if condition is true
}
else {
  Statement
  if condition is false
}

15. enum keyword

The enum keyword in Java is used to specify the fixed value of constants. With the enum keyword, we can declare the enumerated type. Enums in Java represents a class that contains a fixed set of constant values that can’t be changed. We cannot declare an enum inside a method but we can declare it inside or outside class.

public enum Colors {
  RED,
  YELLOW,
  BLUE,
  GREEN
}

16. extends keyword

The extends keyword is another important keyword in Java that is used to inherit the parent class. If a class wants to inherit the properties from another class, it can inherit it using the extends keyword. The Child class is written before the extends keyword and the parent class is written after the extends keyword. We use this keyword to achieve one of the OOPs concept i.e. Inheritance in Java.

class ParentClass {
  //code inside the parent class
}
class ChildClass extends ParentClass {
  //code inside the child class’
}

17. for keyword

The for keyword in Java is used as a looping statement in Java. In for loop, all the looping statements are written in the same line.

for (initialization expression; test - expressions; update - expression) {
  //statement inside the for loop
}

18. final keyword

The final keyword in Java is used to restrict the variable, class, or methods in Java. If we declare a variable as final, then we can’t change its value again. If we use the final keyword with a class, then no other class can inherit the final class. When you declare a method as final then the method can not be overridden in the child class.

How to Declare final variables:

final int myVar = 10;

Declaring the final method:

final myMethod {
  //code inside final method
}

Declaring final class:

final class MyClass {
  //code inside final class
}

19. finally keyword

The finally keyword in Java is used in Exception Handling. It is used in a try-catch structure. The statements inside the finally block always executes no matter if the exception is handled or not. The finally statement always comes after the try-catch block.

try {
  //statements
}
catch {
  //statements
}
finally {
  //statements
}

20. float keyword

The float keyword in Java is used to declare a variable of a float data type. The float data type can hold a 32-bit floating number. We need to use the letter F or f to denote a float variable.

float myFloat = 15.7F;

21. if keyword

The if keyword in Java is used as a decision-making statement. We put the test condition inside the if statement and if the condition evaluates to true then the statements inside the if block is executed, otherwise they are skipped.

if (test - condition) {
  //statement if the condition is true
}

22. int keyword

The int keyword in Java is used to declare an integer type variable. The int data type is used to hold a 32-bit integer signed value.

int myNumber = 345;

23. implements keyword

The implements keyword in Java is used by a class to implement an interface. Implementing an interface allows a class to use the methods defined in an interface.

class MyClass implements MyInterface {
  //code inside class
}

24. instanceof keyword

The instanceOf keyword in Java is used to check whether an object belongs to a class , interface, or a subclass. It indicates whether an object is an instance of a particular class or not.

if (objectName instanceof ClassName)

25. import keyword

The import keyword is used to access the classes and interfaces inside the current source code. We can import packages and classes at the starting of the source code.

Example:

import package com.techvidvan.javatutorials.MyClass;
//imports the MyClass. 

import package com.techvidvan.javatutorials. * ;
//imports all the classes and provides access to them.

26. interface keyword

The interface keyword in Java is used when we want to create an interface in Java. An interface in Java can only contain abstract methods. The abstract methods are the methods that have no method body or implementation.

interface MyInterface {
  //abstract methods
}

27. long keyword

The long keyword in Java is used to declare a variable with a long data type. It holds a 64-bit long integer value. We use the letter l or L to denote a long value.
Example:

long myValue = 234345L;

28. new keyword

The new keyword in Java is used when we instantiate a class or create objects of a class. Creating objects with a new keyword is the most common way of creating objects.

Syntax of using the new keyword

MyClass object = new MyClass();

29. native keyword

The native keyword in Java is used to specify that the method is implemented using the Java Native Interface(JNI). We can use native as a modifier for only a method. We can’t apply it with any other entity.

Example:

class NativeDemo {
  //statements
}
public native String getLines();
class Main {
  NativeDemo obj = new NativeDemo();
  obj.getLines();
}

30. null keyword

The null keyword in Java is used to indicate the null value. The null value represents a reference variable. If we declare a reference variable as null then it refers to nothing. If we declare a variable as null then the object refers to nothing.

String myString;
myString = null;
//Now myString is an empty string that holds no value.

MyClass obj = new MyClass();
obj = null;
//Now, the object does not hold the reference of MyClass.

31. package keyword

The package keyword in Java is used to create a package. A package is a collection of same type classes and interfaces for better readability and proper distribution of multiple classes. To include a class in a package we write it on the very first line of the Java program.

For Example:

package com.techvidvan.javatutorials.operators;
//This line creates a class inside the operators subpackage

public class ArithmeticOperators {
  //Code inside the class
}

32. public keyword

The public keyword in Java denotes the access specifier in Java. This keyword can be used with class, constructor, variable, interface or a method. If we use the public keyword with any entity that it can be accessed from anywhere. It has the widest scope as compared to all the access specifiers of Java.

public class MyClass {
  public int myVar;
  public void printName();
}

33. private keyword

The private keyword in Java is another access specifier that can be used with a class, variable or a method. Any entity declared as private can only be accessed within the class itself in which it has been declared. It can’t be accessed from outside that class. It has the narrowest scope and is the most restricted access specifier in Java.

private class MyClass {
  private int myVar;
  private void printName();
}

34. protected keyword

The protected keyword is also an access specifier in Java. The entities declared with a protected keyword can be accessed within the same package and also from the different packages but only through the subclasses of that class. It can only be used with a variable or a method; not with a class or an interface.

protected int myVar;
protected void printName();

35. return keyword

The return keyword in Java is used inside the methods to return from the method. When the return keyword is encountered, the control flow reaches to the code where the method was being called. The return keyword can also return a value from a function or a method.

public int getNumber(int num) {
  num = 5;
  return num;
}

36. static keyword

The static keyword in Java is used with a variable, method or a block. It is used to share the same variable or a method within a class.

public static void display()
static int number = 10;

37. short keyword

The short keyword in Java is used to declare a variable of a short data type. The short data type can hold 16-bit (2 bytes) integer value and can store a range of -32,768 to 32,767 numbers.

short myNum = 38;

38. super keyword

The super keyword in Java is used to refer to the object of the parent or superclass. It is used to call the immediate parent class methods.

class Parent {
  String color = “Red”;
}

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:
Red

39. switch keyword

The switch keyword in Java is used for the switch as a conditional statement. The switch keyword is very effective against the if statement as with the help of switch the compiler directly jumps to the particular case rather than executing all the conditions which are in the if statement.

Code to understand the switch statement:

public class Main {
  public static void main(String args[]) {
    int dayOfNumber = 2;

    switch (dayOfNumber) {
    case 0:
      System.out.println(“Sunday”);
      break;
    case 1:
      System.out.println(“Monday”);
      Break;
    case 2:
      System.out.println(“Tuesday”);
      Break;
    case 3:
      System.out.println(“Wednesday”);
      break;
    case 4:
      System.out.println(“Thursday”);
      Break;
    case 5:
      System.out.println(“Friday”);
      break;
    case 6:
      System.out.println(“Saturday”);
      break;
    default:
      System.out.println(“Not the vaild number of the Day”);
    }
  }
}

Output:
Tuesday

40. synchronized keyword

The synchronized keyword in Java is used to achieve synchronization in Java in a multi-threaded environment. The methods that are critical and need to be accessed by only a single resource at the same time, then these methods are declared as synchronized with the help of a synchronized keyword.

synchronized void methodName {
  //code inside the method
}

41. strictfp keyword

The strictfp keyword in Java Programming Language is used to provide the platform-independent facility i.e. the piece of code will return the same result in different platforms. There are some priorities that may differ from platform to platform. That is the reason why Java introduces the strictfp keywords to ensure that every platform may run the code in the same precision.

The strictfp keyword is used with classes, interfaces, and methods. The Example is given below:

strictfp use in the Class:

strictfp class Keywords {
  // the methods of the class.
}

Use in the interface:

strictfp interface Keywords {
  // methods of the interface
}

Use in the methods:

class Keywords {
  strictfp void StrictfpKeyword {
    // the logic of the method
  }
}

42. this keyword

The this keyword in Java is used to refer to the current object of the class inside the method or a constructor. The this keyword is used to remove the ambiguity between the instance variables and parameters.

class ClassName {
  int number;

  //constructor
  ClassName(int number) {
    this.number = number;
  }
}

43. throw keyword

The throw keyword in Java Programming Language is used to explicitly throw an exception. For example if the user enters a number greater than 10 then the program will throw an exception. In this case to throw the custom exception the Java introduces the throw keyword. The throw keyword allows the developer to throw the custom exception.

public classThrowKeyword {
  public static void ageRestriction(int age) {
    if (age < 18) throw new ArithmeticException("Age restriction to vote");
    else System.out.println("Allow to Vote");
  }
  public static void main(String args[]) {
    System.out.println("Enter your age: ");
    ageRestriction(13);
  }
}

Output:
Enter your age
Exception in thread main java.lang.ArithmeticException: Age restriction to vote

44. throws keyword

The throws keyword in Java is used in Exceptions. We use the throws keyword for only the checked exceptions in Java. It indicates the programmer that to be on the safe side you should use it to avoid exceptions.

public void getNames() throws IOException {
  //code inside the method
}

45. try keyword

The try keyword in Java is useful for exception handling. Whenever we want a block to be tested for exceptions, then we put in the try block. But the try block must end with the catch or finally block.

try {
  //statements
}
catch {
  //statements
}

46. transient keyword

The transient keyword in Java Programming Language is useful to accomplish serialization in the Java Environment. When we declare the data member with a transient keyword then that data member will not be serialized.

transient int age;

47. void keyword

The void keyword in Java is useful with methods to specify that the method returns nothing. There is no return value of the method.

public void display() {
  //code inside method
}

48. volatile keyword

The volatile keyword in Java is useful with a variable to indicate that the value of a variable may be modified asynchronously by different threads. We also use it with classes to make them thread-safe.

class Demo {
  static volatile int myvar = 5;
}

49. while keyword

The while keyword in the Java Programming Language is useful to iterate a piece of code as many times as you want. If there is no information about the terminating condition, then it is better to use a while loop. The while loop also offers the infinite looping structure.

while (condition) {
  // the piece of code
}

Conclusion

Keywords in Java are special words that we can use only for the situation when they are meant to be used. We can’t use them as identifiers. In this article, we have discussed different keywords in Java. Basically there are 51 keywords in java but two of them goto and const are for future purpose. So only 49 keywords are useful currently in Java. We hope you might have understood the use of each keyword in Java along with their syntax.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.