Java Keywords

Filed Under: Java
Java Keywords

Java keywords are the reserved words that are used by the Java compiler. These keywords have special meaning to the Java compiler. The reserved keywords help us in writing code and help the compiler in understanding the code and create the bytecode.

We can’t create identifiers (class, variable, method) having the same name as the reserved keyword.

Java Keywords

Java has 64 reserved keywords. We can divide them into the following categories.

  1. Primitive types and void: 9 keywords
  2. Modifiers: 10 keywords
  3. Declarations: 7 keywords
  4. Control Flow: 15 keywords
  5. Miscellaneous: 13 keywords

Let’s have a brief look into all these keywords.

1. Primitive types and void

These keywords are used to create variables of primitive data types. The void is used when the method doesn’t return anything.

  1. boolean: creates a boolean variable. The only possible values are true and false and the default value is false.
  2. byte: creates a byte variable. A byte takes 8-bits and ranges from -128 to 127.
  3. char: used to create a character variable. It takes 2-bytes and it’s unsigned. The value ranges from 0 to 65,536.
  4. short: create a short variable of 2-bytes. The value ranges from -32,768 to 32,767.
  5. int: create an integer variable, takes 4-bytes and the range is from -2,147,483,648 to 2,147,483,647
  6. long: creates a long variable, takes 8-bytes and the range is from -9,223,372,036,854,775,808 to
    9,223,372,036,854,775,807.
  7. float: creates a signed floating point variable using 4-bytes.
  8. double: creates a signed double using 8-bytes.
  9. void: used with methods to specify that it doesn’t return anything.

Here is a simple example showing the use of these keywords. Notice the use of void keyword in the java main function to indicate that it doesn’t return anything.


package com.journaldev.examples;

public class JavaKeywords {

	public static void main(String[] args) {
		boolean flag = true;
		byte b = 10;
		char c = 'a';
		short s = 2;
		int i = 1000;
		long l = 12345678L;
		float f = 1.23F;
		double d = 1.2e3D;

	}

}

2. Modifiers Keywords

These keywords are used to specify the scope of the variable, methods, and class.

  1. public: used with class, methods, and fields to define their scope. The private identifiers can be accessed from anywhere.
  2. protected: used with inner class, methods, and fields. The protected members are accessible only from within the class, the sub-classes and the other classes in the same package.
  3. private: the private keyword is used with class variables, methods, and inner classes. The private members are accessible only within the class code.
  4. abstract: used to implement abstraction in Java. It’s used with a class declaration to create an abstract class. It can also be used with methods inside an abstract class to declare abstract methods. The abstract methods must be implemented by the subclass. We can’t create an instance of an abstract class.
  5. static: can be used with fields, methods, and inner class. The static members belong to the class and shared by all the instances of the class.
  6. final: used with class, fields, and methods. The final class can’t be extended. The final fields value can’t be changed, once assigned. The final method can’t be overridden in the subclass.
  7. transient: used with class fields to declare that they won’t be part of serialization. When an object is serialized, only non-transient fields are part of the serialization process. When the object is deserialized, the transient fields are assigned with their default values.
  8. volatile: used with class fields to declare that their value might change by other threads. It was intended to use in case of multithreading, but it has several issues and it’s better to stick with synchronization.
  9. synchronized: used with a method or to create a code block. It’s used to create a code block that can be executed by only one thread at a time. It’s very useful in maintaining data consistency in a multithreaded environment.
  10. native: used with java method declaration to specify that the method is not implemented in the same Java class, but rather in another language. For example, System class currentTimeMillis() and arraycopy() are native methods.

Recommended Readings:

Here is a simple example showing usage of modifier keywords in a Java program.


package com.journaldev.examples;

public class JavaKeywords {

	private int y = 20;
	protected int x = 10;
	final String name = "JavaKeywords";
	static int count = 0;
	transient Object mutex = new Object();
	volatile int v_random = 999;

	public void print(String s) {
		System.out.println(s);
	}

	synchronized void bar(int i) {
		count = i;
	}

}

abstract class Abs {
	abstract void foo();
}

3. Declarations Keywords

These keywords are used to create an entity in Java.

  1. class: used to create a class.
  2. interface: to create an interface.
  3. enum: added in Java 1.5 to create an enum.
  4. extends: used to create a subclass by extending another class.
  5. implements: used to implement an interface.
  6. package: defines the pacakage for the class, interface, or enum definitions.
  7. throws: used with methods to specify the exceptions that the method may throw.

package com.journaldev.examples;

class Cls{}
interface Int{}
enum En{}
class ClsChild extends Cls{}
class IntImpl implements Int{}

class Utils{
	void foo() throws Exception{}
}

4. Control Flow Keywords

These keywords are used to define the execution flow of the java code.

  1. if: used to create if statement.
  2. else: used in conjunction with if to create an if-else statement.
  3. try: used to create a block of code for exception handling.
  4. catch: used in conjunction with try block to catch the exceptions and process them.
  5. finally: used with try-catch block. The finally block code is always executed.
  6. do: used in conjunction with while to create a do-while loop.
  7. while: can be used to create while loop or do-while loop.
  8. for: used to create a for loop.
  9. continue: used in the loops to skip the execution of the current cycle and proceed with the next cycle.
  10. switch: used to create switch-case statements.
  11. case: used in conjunction with switch to create switch-case statements.
  12. default: used with the switch-case statements for the default case. From Java 8 onwards, it can also be used to create default methods in the interfaces. We can also use it to declare default value in an annotation.
  13. break: used in the loops to end the execution of the current loop body.
  14. throw: used to throw exceptions.
  15. return: used to return value from a method.

Here is an example showing the usage of the control flow keywords in Java.


package com.journaldev.examples;

public class JavaKeywords {
	static int x = 10;

	public static int foo() {

		if (x < 10) {
			// do something
		} else {
			// do something else
		}

		try {
			throw new Exception("Excp");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("Done");
		}

		do {
			// some code
		} while (false);

		for (int i = 0; i < x; i++) {
			if (i == 5)
				continue;
			if (i == 8)
				break;
			System.out.println(i);
		}

		switch (x) {
		case 1, 2, 3, 4, 5:
			System.out.println(x);
			break;
		default:
			System.out.println("NA");

		}
		return -1;
	}

}

5. Miscellaneous Keywords

  1. this: used to get access to the current object.
  2. new: used to create an instance by calling the constructor.
  3. super: used incase of inheritance to access superclass methods, constructors, and variables.
  4. import: used to import a class so that we can use its functions.
  5. instanceof: An operator to check if an object is instance of a class.
  6. null: used to define null values of a variable.
  7. true: a boolean literal, returned when a condition is true.
  8. false: a boolean literal, returned when a condition is false.
  9. strictfp: used to restrict the precision and rounding of floating point calculations to ensure portability.
  10. assert: added in Java 1.4 to create assertions.
  11. _ (underscore): added in Java 1.9 for underscore literals.
  12. goto: not used.
  13. const: not used.

package com.journaldev.examples;

import java.util.Arrays;

public class JavaKeywords {
	private int value;

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	public static void main(String[] args) {
		JavaKeywords jk = new JavaKeywords();
		System.out.println(Arrays.toString(new int[] { 1, 2, 3 }));
		String s = "abc";
		if (s instanceof String) {
			System.out.println(s);
		}
		s = null;
		boolean flag = false;
		flag = true;
	}
}

class Base {
	Base(int i) {
	}
}

class Child extends Base {

	Child(int i) {
		super(i);
	}

}

How to Check if a String is a Keyword?

We can use SourceVersion.isKeyword() method to check if a string is part of reserved keywords or not.


package com.journaldev.examples;

import javax.lang.model.SourceVersion;

public class JavaKeywords {

	public static void main(String[] args) {
		String key = "try";
		if (SourceVersion.isKeyword(key)) {
			System.out.println(key + " is a keyword");
		} else {
			System.out.println(key + " is not a keyword");
		}
	}
}

Conclusion

Java keywords define the way to write the code. It's the rulebook for the java compiler to interpret the code and generate bytecode.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages