Table of Contents
Java keywords are also known as reserved words. Keywords are particular words which acts as a key to a code. These are predefined words by Java so it cannot be used as a variable or object name.
- Primitive types and void: 9 keywords
- Modifiers: 10 keywords
- Declarations: 7 keywords
- Control Flow: 15 keywords
- Miscellaneous: 13 keywords
- Special identifiers: 2 keywords
Let’s have a brief look into all these keywords.
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.
- boolean: creates a boolean variable. The only possible values are true and false and the default value is false.
- byte: creates a byte variable. A byte takes 8-bits and ranges from -128 to 127.
- char: used to create a character variable. It takes 2-bytes and it’s unsigned. The value ranges from 0 to 65,536.
- short: create a short variable of 2-bytes. The value ranges from -32,768 to 32,767.
- int: create an integer variable, takes 4-bytes and the range is from -2,147,483,648 to 2,147,483,647
- 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. - float: creates a signed floating point variable using 4-bytes.
- double: creates a signed double using 8-bytes.
- 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.codeyz.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;
}
}
Modifiers Keywords
These keywords are used to specify the scope of the variable, methods, and class.
- public: used with class, methods, and fields to define their scope. The private identifiers can be accessed from anywhere.
- 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.
- private: the private keyword is used with class variables, methods, and inner classes. The private members are accessible only within the class code.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
Here is a simple example showing usage of modifier keywords in a Java program.
package com.codeyz.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 = 777;
public void print(String s) {
System.out.println(s);
}
synchronized void bar(int i) {
count = i;
}
}
abstract class Abs {
abstract void foo();
}
Declarations Keywords
These keywords are used to create an entity in Java.
- class: used to create a class.
- interface: to create an interface.
- enum: added in Java 1.5 to create an enum.
- extends: used to create a subclass by extending another class.
- implements: used to implement an interface.
- package: defines the pacakage for the class, interface, or enum definitions.
- throws: used with methods to specify the exceptions that the method may throw.
package com.codeyz.examples;
class Cls{}
interface Int{}
enum En{}
class ClsChild extends Cls{}
class IntImpl implements Int{}
class Utils{
void foo() throws Exception{}
}
Control Flow Keywords
These keywords are used to define the execution flow of the java code.
- if: used to create if statement.
- else: used in conjunction with if to create an if-else statement.
- try: used to create a block of code for exception handling.
- catch: used in conjunction with try block to catch the exceptions and process them.
- finally: used with try-catch block. The finally block code is always executed.
- do: used in conjunction with while to create a do-while loop.
- while: can be used to create while loop or do-while loop.
- for: used to create a for loop.
- continue: used in the loops to skip the execution of the current cycle and proceed with the next cycle.
- switch: used to create switch-case statements.
- case: used in conjunction with switch to create switch-case statements.
- 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.
- break: used in the loops to end the execution of the current loop body.
- throw: used to throw exceptions.
- return: used to return value from a method.
Here is an example showing the usage of the control flow keywords in Java.
package com.codeyz.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;
}
}
Miscellaneous Keywords
- this: used to get access to the current object.
- new: used to create an instance by calling the constructor.
- super: used incase of inheritance to access superclass methods, constructors, and variables.
- import: used to import a class so that we can use its functions.
- instanceof: An operator to check if an object is instance of a class.
- null: used to define null values of a variable.
- true: a boolean literal, returned when a condition is true.
- false: a boolean literal, returned when a condition is false.
- strictfp: used to restrict the precision and rounding of floating point calculations to ensure portability.
- assert: added in Java 1.4 to create assertions.
- goto: not used.
- const: not used.
package com.codeyz.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);
}
}
Special identifiers
- var – A special identifier that cannot be used as a type name (since Java 10).[
- _ – Added in Java 11, the underscore has become a keyword and cannot be used as a variable name anymore.
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.codeyz.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");
}
}
}
Hi! Why goto not used in Java?