🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Java keywords are reserved words that have a predefined meaning in the language. They are used to perform various operations and cannot be used as identifiers (such as variable names, function names, etc.). This cheat sheet provides a quick reference to all the Java keywords along with a brief description of their use.
Java Keywords Cheat Sheet
| Keyword | Description |
|---|---|
byte |
Used to declare primitive byte type of variables. |
short |
Used to declare primitive short type of variables. |
int |
Used to declare primitive integer type of variables. |
long |
Used to declare primitive long type of variables. |
float |
Used to declare primitive float type of variables. |
double |
Used to declare primitive double type of variables. |
char |
Used to declare primitive character type of variables. |
boolean |
Used to declare primitive boolean type of variables. |
var |
Used to declare a variable of any type (introduced in Java 10). |
if |
Used to define if condition statements or blocks. |
else |
Used in if-else blocks. |
for |
Used to define for loops. |
while |
Used to define while loops. |
do |
Used in do-while loops. |
switch |
Used to define switch blocks or switch expressions (from Java 12). |
case |
Used to define case labels in a switch block. |
break |
Used to break a loop or a block. |
continue |
Used to stop the execution of current iteration and start the next iteration. |
default |
Used in switch blocks to define default case labels and default methods (from Java 8). |
yield |
Used in switch expressions (from Java 13). |
class |
Used to define a class in Java. |
new |
Used while instantiating a class. |
static |
Used to define static members of a class. |
interface |
Used to define an interface. |
extends |
Used when a class is extending or inheriting another class. |
implements |
Used to implement an interface. |
super |
Used to access superclass members inside a subclass. |
this |
Used to access other members of the same class. |
abstract |
Used to define abstract classes and abstract methods. |
final |
Used to define final classes and final methods. |
package |
Used to specify a package for the current file. |
enum |
Used to define enum types. |
private |
Used to define private fields, methods, and constructors. |
protected |
Used to define protected fields, methods, and constructors. |
public |
Used to define public classes, fields, methods, and constructors. |
try |
Used to define a try block. |
catch |
Used to define a catch block. |
finally |
Used to define a finally block. |
throw |
Used to throw an exception manually. |
throws |
Used to specify the exceptions which may be thrown by the current method. |
synchronized |
Used to define synchronized blocks. |
volatile |
Used to define a volatile field whose value is always read from the main memory. |
module |
Used to define a module (introduced in Java 9). |
exports |
Used to export all public members of a package in a module. |
requires |
Used to specify required libraries inside a module. |
open |
Used to create an open module that grants reflective access to other modules. |
opens |
Used to expose specific packages for reflective access by other modules. |
uses |
Specifies the services consumed by the current module. |
provides |
Specifies services provided by the current module. |
sealed |
Used to define sealed classes and interfaces (introduced in Java 17). |
non-sealed |
Used to define non-sealed classes and interfaces. |
permits |
Used to specify the subclasses that can extend the sealed class directly. |
void |
Indicates that a method returns nothing. |
return |
Used to return a value from a method or a block. |
transient |
Used in serialization to indicate that a variable should not be serialized. |
strictfp |
Ensures strict precision of floating-point calculations on different platforms. |
import |
Used to import external resources into the current Java file. |
instanceof |
Used to check whether an object is of a specified type. |
native |
Indicates that a method is implemented in native code using JNI. |
record |
Used to define a special type of classes that act as data carriers (introduced in Java 14). |
assert |
Used in debugging to make an assertion. |
const |
Reserved but not used. |
goto |
Reserved but not used. |
_ |
From Java 9, _ (underscore) has become a keyword and cannot be used as an identifier. |
Explanation and Examples of Java Keywords
byte
Used to declare primitive byte type of variables.
Example:
byte b = 100;
Explanation: Declares a byte variable b and assigns it the value 100.
short
Used to declare primitive short type of variables.
Example:
short s = 1000;
Explanation: Declares a short variable s and assigns it the value 1000.
int
Used to declare primitive integer type of variables.
Example:
int number = 10;
Explanation: Declares an int variable number and assigns it the value 10.
long
Used to declare primitive long type of variables.
Example:
long bigNumber = 100000L;
Explanation: Declares a long variable bigNumber and assigns it the value 100000.
float
Used to declare primitive float type of variables.
Example:
float pi = 3.14f;
Explanation: Declares a float variable pi and assigns it the value 3.14.
double
Used to declare primitive double type of variables.
Example:
double pi = 3.14159;
Explanation: Declares a double variable pi and assigns it the value 3.14159.
char
Used to declare primitive character type of variables.
Example:
char letter = 'A';
Explanation: Declares a char variable letter and assigns it the value 'A'.
boolean
Used to declare primitive boolean type of variables.
Example:
boolean isJavaFun = true;
Explanation: Declares a boolean variable isJavaFun and assigns it the value true.
var
Used to declare a variable of any type (introduced in Java 10).
Example:
var number = 10;
Explanation: The var keyword infers the type of the variable number as int.
if
Used to define if condition statements or blocks.
Example:
if (number > 5) {
System.out.println("Number is greater than 5");
}
Explanation: The if block executes if the condition number > 5 is true.
else
Used in if-else blocks.
Example:
if (number < 5) {
System.out.println("Number is less than 5");
} else {
System.out.println("Number is 5 or greater");
}
Explanation: The else block executes if the if condition is false.
for
Used to define for loops.
Example:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Explanation: The for loop iterates from i = 0 to i < 5.
while
Used to define while loops.
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Explanation: The while loop executes as long as the condition i < 5 is true.
do
Used in do-while loops.
Example:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
Explanation: The do block executes at least once before checking the condition.
switch
Used to define switch blocks or switch expressions (from Java 12).
Example:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}
Explanation: The switch statement tests the value of day and executes the corresponding case block.
case
Used to define case labels in a switch block.
Example:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}
Explanation: The case statement checks the value of day and executes the corresponding block of code.
break
Used to break a loop or a block.
Example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Explanation: The break statement exits the for loop when i equals 5.
continue
Used to stop the execution of the current iteration and start the next iteration in a loop. Example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
Explanation: The continue statement skips the current iteration when i is even.
default
Used in switch blocks to define default case labels and default methods (from Java 8). Example:
int day = 7;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}
Explanation: The default block executes if none of the case conditions are met.
yield
Used in switch expressions (from Java 13).
Example:
int day = 2;
String result = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Other day";
};
System.out.println(result);
Explanation: The yield keyword returns a value from a switch expression.
class
Used to define a class in Java.
Example:
class MyClass {
int x = 5;
}
Explanation: Declares a class MyClass with a member variable x.
new
Used while instantiating a class.
Example:
Dog myDog = new Dog();
Explanation: The new keyword creates a new instance of the Dog class.
static
Used to define static members of a class.
Example:
class MyClass {
static int count = 0;
}
Explanation: The count variable is static and belongs to the MyClass class rather than its instances.
interface
Used to define an interface.
Example:
interface Animal {
void makeSound();
}
Explanation: The interface keyword declares an interface Animal with an abstract method makeSound().
extends
Used when a class is extending or inheriting another class.
Example:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
Explanation: The Dog class extends the Animal class, inheriting its eat() method.
implements
Used to implement an interface.
Example:
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
Explanation: The Dog class implements the Animal interface by providing an implementation of the makeSound() method.
super
Used to access superclass members inside a subclass.
Example:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void eat() {
super.eat();
System.out.println("Dog is eating...");
}
}
Explanation: The super keyword calls the eat() method of the superclass Animal.
this
Used to access other members of the same class.
Example:
class MyClass {
int x;
MyClass(int x) {
this.x = x;
}
}
Explanation: The this keyword refers to the current instance variable x.
abstract
Used to define abstract classes and abstract methods.
Example:
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
Explanation: The Animal class is abstract and has an abstract method makeSound(). The Dog class extends Animal and provides an implementation for the makeSound() method.
final
Used to define final classes and final methods.
Example:
final class MyClass {
final void display() {
System.out.println("Hello");
}
}
Explanation: The final keyword prevents the MyClass class from being subclassed, and the display() method from being overridden.
package
Used to specify a package for the current file.
Example:
package mypackage;
Explanation: The package keyword declares that the class belongs to the mypackage package.
enum
Used to define enum types.
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Explanation: The enum keyword declares an enumeration Day with constants representing days of the week.
private
Used to define private fields, methods, and constructors.
Example:
class MyClass {
private int x = 5;
}
Explanation: The x variable is private and can only be accessed within the MyClass class.
protected
Used to define protected fields, methods, and constructors.
Example:
class Animal {
protected void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
Explanation: The eat() method is protected and can be accessed by the Dog class, which extends Animal.
public
Used to define public classes, fields, methods, and constructors.
Example:
public class MyClass {
public int x = 5;
}
Explanation: The x variable is public and can be accessed by any other class.
try
Used to define a try block.
Example:
try {
int division = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Explanation: The try block contains code that might throw an exception.
catch
Used to define a catch block.
Example:
try {
int division = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Explanation: The catch block catches the ArithmeticException thrown by the division by zero.
finally
Used to define a finally block.
Example:
try {
int division = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This is the finally block");
}
Explanation: The finally block executes regardless of whether an exception is thrown or not.
throw
Used to throw an exception.
Example:
void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
}
Explanation: The throw keyword throws an ArithmeticException if the age is less than 18.
throws
Used to specify the exceptions which may be thrown by the current method.
Example:
void myMethod() throws IOException {
throw new IOException("File not found");
}
Explanation: The throws keyword indicates that the myMethod can throw an IOException.
synchronized
Used to define synchronized blocks.
Example:
public synchronized void increment() {
count++;
}
Explanation: The synchronized keyword ensures that the increment method is accessed by only one thread at a time.
volatile
Used to define a volatile field whose value is always read from the main memory. Example:
class MyClass {
volatile int sharedVar;
}
Explanation: The volatile keyword ensures that the sharedVar is read from and written to main memory directly.
module
Used to define a module (introduced in Java 9).
Example:
module mymodule {
requires java.base;
exports com.example.mypackage;
}
Explanation: The module keyword declares a module named mymodule, specifies its dependencies, and exports its packages.
exports
Used to export all public members of a package in a module.
Example:
module mymodule {
exports com.example.mypackage;
}
Explanation: The exports keyword makes the public members of the com.example.mypackage package accessible to other modules.
requires
Used to specify required libraries inside a module.
Example:
module mymodule {
requires java.sql;
}
Explanation: The requires keyword specifies that the mymodule module depends on the java.sql module.
open
Used to create an open module that grants reflective access to other modules.
Example:
open module mymodule {
requires java.base;
}
Explanation: The open keyword allows all packages in the mymodule module to be reflectively accessed by other modules.
opens
Used to expose specific packages for reflective access by other modules.
Example:
module mymodule {
opens com.example.mypackage to some.other.module;
}
Explanation: The opens keyword allows the some.other.module module to reflectively access the com.example.mypackage package.
uses
Specifies the services consumed by the current module.
Example:
module mymodule {
uses com.example.MyService;
}
Explanation: The uses keyword indicates that the mymodule module depends on the com.example.MyService service.
provides
Specifies services provided by the current module.
Example:
module mymodule {
provides com.example.MyService with com.example.MyServiceImpl;
}
Explanation: The provides keyword indicates that the mymodule module provides an implementation of the com.example.MyService service.
sealed
Used to define sealed classes and interfaces (introduced in Java 17).
Example:
public sealed class Shape permits Circle, Square {
}
Explanation: The sealed keyword restricts which other classes can extend or implement the Shape class.
non-sealed
Used to define non-sealed classes and interfaces.
Example:
public non-sealed class Circle extends Shape {
}
Explanation: The non-sealed keyword allows the Circle class to be extended by other classes.
permits
Used to specify the subclasses that can extend the sealed class directly.
Example:
public sealed class Shape permits Circle, Square {
}
Explanation: The permits keyword specifies that only the Circle and Square classes can directly extend the Shape class.
void
Indicates that a method returns nothing.
Example:
void display() {
System.out.println("Hello");
}
Explanation: The void keyword indicates that the display method does not return a value.
return
Used to return a value from a method or a block.
Example:
public int sum(int a, int b) {
return a + b;
}
Explanation: The return statement exits the sum method and returns the sum of a and b.
transient
Used in serialization to indicate that a variable should not be serialized.
Example:
class MyClass implements Serializable {
transient int x;
}
Explanation: The transient keyword prevents the x field from being serialized.
strictfp
Ensures strict precision of floating-point calculations on different platforms.
Example:
strictfp class MyClass {
double num = 0.0;
}
Explanation: The strictfp keyword ensures that floating-point calculations conform to IEEE 754 standards.
import
Used to import external resources into the current Java file.
Example:
import java.util.ArrayList;
Explanation: The import statement imports the ArrayList class from the java.util package.
instanceof
Used to check whether an object is of a specified type.
Example:
Dog myDog = new Dog();
System.out.println(myDog instanceof Animal); // true
Explanation: The instanceof operator checks if myDog is an instance of the Animal class.
native
Indicates that a method is implemented in native code using JNI.
Example:
public class MyClass {
public native void nativeMethod();
}
Explanation: The native keyword indicates that the nativeMethod() is implemented in native code (e.g., C/C++).
record
Used to define a special type of classes that act as data carriers (introduced in Java 14). Example:
public record Point(int x, int y) {
}
Explanation: The record keyword defines a Point record class with two fields: x and y.
assert
Used in debugging to make an assertion.
Example:
int age = -5;
assert age > 0 : "Age cannot be negative";
Explanation: The assert statement checks if the age is positive. If not, it throws an AssertionError with the message "Age cannot be negative".
const
Reserved but not used.
Example: N/A
goto
Reserved but not used.
Example: N/A
_ (Underscore)
From Java 9, _ (underscore) has become a keyword and cannot be used as an identifier.
Example: N/A
Conclusion
This cheat sheet provides a comprehensive reference to all the Java keywords, helping you understand their usage and enhance your programming skills. Keep this guide handy to ensure you are using these keywords correctly and efficiently in your Java code. Happy coding!
Comments
Post a Comment
Leave Comment