JAVA KEYWORDS
Introduction
In Java, keywords are reserved words — they have a predefined meaning in the language syntax. You can’t use them as identifiers (like variable names, class names, method names). Java’s compiler would freak out if you try.
Example:
if you want to create a variable with name "class" you cant.
int class = 5; // Compiler: “Man, are you serious?”
So, think of keywords as special signals — they tell the compiler what kind of thing you’re writing: is it a method? A condition? A loop? An access rule? Each keyword has a job.
Why Keywords Matter in Java
- They define structure (e.g., class, interface, enum).
- They control flow (if, for, while).
- They handle memory and behavior (static, final, volatile).
- They power OOP principles (extends, implements, super, this).
In short: No keywords, no Java.
Reserved vs. Contextual
Java doesn’t really have “contextual” keywords like some modern languages (e.g., yield in Python is contextual). In Java, if it’s a keyword, it’s always reserved.
BUT — newer features like var look like keywords but are technically not “reserved words” in the original sense. Quirky, right?
Classification of Java Keywords
Java has 50-ish keywords (depending on the version). Here’s how they stack up:
A) Access Modifiers
- public
- protected
- private
B) Class/Interface/Record Modifiers
- abstract
- final
- strictfp
- static
- transient
- volatile
- synchronized
- native
- sealed
- non-sealed
C) Flow Control
- if
- else
- switch
- case
- default
- for
- while
- do
- break
- continue
- return
- yield
D) Exception Handling
- try
- catch
- finally
- throw
- throws
E) Primitive Types
- boolean
- byte
- char
- short
- int
- long
- float
- double
F) OOP Concepts
- class
- interface
- enum
- extends
- implements
- super
- this
- new
- instanceof
- record
G) Miscellaneous
- package
- import
- assert
- void
- null (special literal, not a keyword per se)
- var (technically not reserved, but acts like it)
H) Reserved But Unused
- const
- goto
These two are fossils — Java keeps them reserved so no one accidentally tries to use them.
Deep Dive into Each Keyword
let’s discuss about all keywords one by one
abstract
What it does:
Marks a class or method as incomplete — you can’t create an object of an abstract class directly. And abstract methods have no body — subclasses must override them.
Syntax:
abstract class Animal {
abstract void makeSound(); // No body!
}
Example:
abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Zzz...");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Woof!
d.sleep(); // Zzz...
}
}
Pro Tip:
You can mix abstract and non-abstract methods in an abstract class.
Gotcha:
If you declare a method abstract, the whole class must be abstract too.
Trivia:
You cannot make an abstract constructor — because constructors are never inherited.
assert
What it does:
Used for debugging — checks an expression; if it’s false, it throws an AssertionError. Helps devs catch bugs early.
Syntax:
assert expression;
assert expression : detailMessage;
Example:
public class Main {
public static void main(String[] args) {
int age = -5;
assert age >= 0 : "Age cannot be negative!";
System.out.println("Age: " + age);
}
}
Run with:
java -ea Main (-ea = enable assertions)
Pro Tip:
Assertions are disabled by default at runtime — so don’t use them for real error handling.
Gotcha:
Don’t use assert for validating user input in production. They can be turned off, so your check might just poof.
Trivia:
assert was added in Java 1.4 — old-school code might not have it.
boolean
What it does:
Primitive data type — holds true or false. Literally the backbone of all your ifs, whiles, and loops.
Syntax:
boolean isJavaFun = true;
Example:
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // true
System.out.println(isFishTasty); // false
}
}
Pro Tip:
Unlike C/C++, Java has real booleans — no int pretending to be true or false.
Gotcha:
You cannot cast numbers to booleans directly — if(1) is illegal in Java.
Trivia:
Only two possible values: true and false. That’s it. Clean and simple.
break
What it does:
Exits a loop or switch immediately. Handy when you wanna get the heck out of a loop early.
Syntax:
break;
break labelName;
Example:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Jump out
}
System.out.println(i);
}
}
}
// Output: 0 1 2 3 4
Pro Tip:
You can use break with labels for nested loops:
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break outer; // breaks the outer loop!
}
}
}
Gotcha:
Some devs hate labeled break — it can make code harder to read. Use wisely.
Trivia:
break is also used in switch to stop “fall-through” behavior.
byte
What it does:
Primitive type — 8-bit signed integer. Range: -128 to 127. Used when you wanna save memory in large arrays.
Syntax:
byte age = 25;
Example:
public class Main {
public static void main(String[] args) {
byte a = 100;
byte b = 28;
byte sum = (byte) (a + b); // Cast required!
System.out.println(“Sum: ” + sum);
}
}
Pro Tip:
When you do arithmetic, Java promotes byte to int — so you often need to cast back.
Gotcha:
Overflow is easy with byte — adding 1 to 127 wraps it to -128.
Trivia:
Good for memory-constrained devices like embedded systems.
case
What it does:
Used inside a switch statement to define possible values.
Syntax:
switch (value) {
case 1:
// do something
break;
}
Example:
public class Main {
public static void main(String[] args) {
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”);
}
}
}
// Output: Tuesday
Pro Tip:
From Java 14+, you can use case with the new switch expression:
String result = switch (day) {
case 1 -> “Monday”;
case 2 -> “Tuesday”;
default -> “Other”;
};
Gotcha:
Don’t forget break! Without it, you get “fall-through” — which sometimes is useful but usually a bug.
Trivia:
The switch statement originally only worked with int and char — Java 7 added String.
catch
What it does:
Handles exceptions thrown in a try block. If an exception occurs, catch blocks grab it and do something about it so your app doesn’t faceplant.
Syntax:
try {
// risky code
} catch (ExceptionType e) {
// handle it
}
Example:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // whoops
} catch (ArithmeticException e) {
System.out.println(“Can’t divide by zero, genius!”);
}
}
}
// Output: Can’t divide by zero, genius!
Pro Tip:
You can chain multiple catch blocks:
try {
// risky stuff
} catch (IOException e) {
// file stuff
} catch (Exception e) {
// fallback
}
Java 7+ lets you multi-catch:
catch (IOException | SQLException ex) {
// one handler for both
}
Gotcha:
Order matters! More specific exceptions must come before more general ones — otherwise you get unreachable code errors.
Trivia:
If no catch, you must have a finally to clean up.
char
What it does:
Primitive type — holds a single 16-bit Unicode character.
Syntax:
char letter = ‘A’;
Example:
public class Main {
public static void main(String[] args) {
char letter = ‘Z’;
char unicodeChar = ‘\u263A’; //
System.out.println(letter); // Z
System.out.println(unicodeChar); //
}
}
Pro Tip:
Java char is always 16-bit — so you can store international characters, emojis (kinda), etc.
Gotcha:
Remember: ‘A’ (char) is different from “A” (String). Rookie mistake.
Trivia:
char uses Unicode, unlike C/C++ char which is ASCII by default.
class
What it does:
Defines a class — the blueprint for objects. No class, no OOP, no Java.
Syntax:
class Dog {
String breed;
void bark() {
System.out.println(“Woof!”);
}
}
Example:
public class Main {
static class Dog {
String name;
void bark() {
System.out.println(name + ” says: Woof!”);
}
}
public static void main(String[] args) {
Dog d = new Dog();
d.name = “Buddy”;
d.bark();
}
}
// Output: Buddy says: Woof!
Pro Tip:
A .java file can have multiple classes, but only one public class — and the filename must match that class name.
Gotcha:
Java doesn’t allow multiple inheritance for classes. You can extend only one class but implement multiple interfaces.
Trivia:
You can have inner classes, anonymous classes, static nested classes, and even local classes inside methods.
const
What it does:
Trick question: it does nothing in Java! const is reserved but unused. Java uses final instead.
Syntax:
Nope. Doesn’t exist.
Example:
// Illegal:
const int max = 10; // Nope
Use final:
final int max = 10; // Correct
Pro Tip:
Ignore const. If you see it in legacy pseudo-code, it means final.
Trivia:
It’s reserved because Java’s creators wanted to leave room for future use — but they never used it. Like a closet you never clean out.
continue
What it does:
Skips the current iteration of a loop and jumps to the next one.
Syntax:
continue;
continue labelName;
Example:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // skip 2
}
System.out.println(i);
}
}
}
// Output: 0 1 3 4
Pro Tip:
Like break, you can use continue with labels for nested loops:
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) continue outer; // skip outer loop iteration
System.out.println(i + “,” + j);
}
}
Gotcha:
Overusing continue can make loops messy. It’s useful — but don’t sprinkle it everywhere like coriander on biryani.
default
What it does:
Used in two places:
- switch: fallback if no case matches.
- Interfaces (Java 8+): to define default methods.
Syntax:
Switch:
switch (value) {
default:
// fallback
}
Interface:
interface MyInterface {
default void show() {
System.out.println(“Default implementation”);
}
}
Example:
public class Main {
public static void main(String[] args) {
int num = 7;
switch (num) {
case 1: System.out.println(“One”); break;
default: System.out.println(“Not One”);
}
}
}
// Output: Not One
Interface:
interface Greeting {
default void sayHello() {
System.out.println(“Hello!”);
}
}
class MyGreeting implements Greeting {}
public class Main {
public static void main(String[] args) {
MyGreeting g = new MyGreeting();
g.sayHello(); // Hello!
}
}
Pro Tip:
Default methods let interfaces evolve without breaking old implementations.
Gotcha:
Don’t confuse default in switch with default methods in interfaces — same word, different vibe.
Trivia:
Before Java 8, interfaces couldn’t have any method bodies. default changed the game.
do
What it does:
Starts a do-while loop — which always runs at least once because it checks the condition after the block runs.
Syntax:
do {
// run this block
} while (condition);
Example:
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(“i is: ” + i);
i++;
} while (i < 3);
}
}
// Output:
// i is: 0
// i is: 1
// i is: 2
Pro Tip:
Use do-while if you need the body to run at least once, no matter what.
Gotcha:
Don’t forget the semicolon after while. Rookie mistake:
} while (condition); // Good
Trivia:
One of the few Java statements that puts the condition after the block.
double
What it does:
Primitive type — 64-bit floating-point number. Good ol’ decimals.
Syntax:
double salary = 34567.89;
Example:
public class Main {
public static void main(String[] args) {
double pi = 3.14159;
double radius = 5.0;
double area = pi * radius * radius;
System.out.println(“Area: ” + area);
}
}
// Output: Area: 78.53975
Pro Tip:
If you need even more precision, look into BigDecimal. double has rounding issues for critical financial calculations.
Gotcha:
double literals default to double — but float needs an f suffix: float x = 3.14f;
Trivia:
IEEE 754 standard — same as C, C++, Python. Floating point fun never ends.
else
What it does:
Defines what happens if an if condition is false.
Syntax:
if (condition) {
// do this
} else {
// do that
}
Example:
public class Main {
public static void main(String[] args) {
int temp = 35;
if (temp > 30) {
System.out.println(“Hot!”);
} else {
System.out.println(“Pleasant!”);
}
}
}
// Output: Hot!
Pro Tip:
You can chain else if for multiple conditions:
if (x > 0) {
…
} else if (x < 0) {
…
} else {
…
}
Gotcha:
Always use braces {} — nested if-else without braces can lead to “dangling else” confusion.
enum
What it does:
Declares an enumeration — a list of named constants.
Syntax:
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class Main {
public static void main(String[] args) {
Day today = Day.FRIDAY;
switch (today) {
case FRIDAY:
System.out.println(“Party time!”);
break;
default:
System.out.println(“Work day…”);
}
}
}
// Output: Party time!
Pro Tip:
Java enums are more powerful than C enums — they can have fields, methods, and constructors.
enum Color {
RED(“FF0000”), GREEN(“00FF00”), BLUE(“0000FF”);
String hex;
Color(String hex) {
this.hex = hex;
}
}
Gotcha:
Enums extend java.lang.Enum implicitly, so you can’t extend anything else.
Trivia:
Enums were added in Java 5 — thank generics and annotations for making Java 5 a game-changer.
extends
What it does:
Defines inheritance — a class extends another class, or an interface extends another interface.
Syntax:
class Dog extends Animal { }
interface B extends A { }
Example:
class Animal {
void eat() {
System.out.println(“Animal eats.”);
}
}
class Dog extends Animal {
void bark() {
System.out.println(“Woof!”);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Animal eats.
d.bark(); // Woof!
}
}
Pro Tip:
Java only supports single inheritance for classes — but interfaces can extend multiple interfaces.
interface A {}
interface B {}
interface C extends A, B {} // Totally fine
Gotcha:
You can’t extend a final class — the compiler will slap you with an error.
final
What it does:
Locks things down:
- Final variable → can’t change value.
- Final method → can’t override.
- Final class → can’t extend.
Syntax:
final int MAX = 100;
final class MyClass { }
final void method() { }
Example:
public class Main {
public static void main(String[] args) {
final int MAX_USERS = 50;
// MAX_USERS = 60; // Compiler will complain
System.out.println(“Max users: ” + MAX_USERS);
}
}
final class Vehicle {
// can’t extend Vehicle
}
class Parent {
final void show() {
System.out.println(“Can’t override me!”);
}
}
class Child extends Parent {
// void show() {} Not allowed
}
Pro Tip:
Use final for immutability — especially in multi-threaded code.
Gotcha:
final and finally are totally different! finalize is different too — the classic Java “F-words” trap.
Trivia:
Marking parameters as final in method signatures helps avoid accidental reassignment.
finally
What it does:
Part of exception handling — a finally block always runs after try/catch, no matter what. Used for clean-up: close files, release resources, slam that door shut.
Syntax:
try {
// risky stuff
} catch (Exception e) {
// handle stuff
} finally {
// always runs
}
Example:
public class Main {
public static void main(String[] args) {
try {
System.out.println(“Try block”);
int x = 5 / 0;
} catch (ArithmeticException e) {
System.out.println(“Catch block”);
} finally {
System.out.println(“Finally block”);
}
}
}
// Output:
// Try block
// Catch block
// Finally block
Pro Tip:
Even if you return in try or catch — finally still runs. Sneaky.
public int test() {
try {
return 1;
} finally {
System.out.println(“Still runs!”);
}
}
Gotcha:
If both try and finally have return statements, finally overrides. Mega gotcha.
float
What it does:
Primitive type — 32-bit floating-point number. Less precise than double.
Syntax:
float price = 19.99f; // Note the ‘f’
Example:
public class Main {
public static void main(String[] args) {
float pi = 3.14f; // f is mandatory
float radius = 2.5f;
float area = pi * radius * radius;
System.out.println(“Area: ” + area);
}
}
// Output: Area: 19.625
Pro Tip:
Always add the f or F suffix — otherwise, Java assumes it’s double.
Gotcha:
Don’t expect perfect decimal accuracy — float is for quick estimates, not banking apps.
for
What it does:
Starts a for loop — your go-to for repeating stuff a fixed number of times.
Syntax:
for (init; condition; update) {
// loop body
}
Example:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(“i: ” + i);
}
}
}
// Output: i: 0 … i: 4
Enhanced For Loop:
AKA for-each — best for arrays, collections.
String[] names = {“Shashwat”, “Java”, “GPT”};
for (String name : names) {
System.out.println(name);
}
Pro Tip:
Use enhanced for for readability — but you can’t modify the collection structure inside it.
Gotcha:
Be careful with continue and break inside loops — don’t make spaghetti.
goto
What it does:
Nothing. Like const, goto is reserved but never implemented.
Java doesn’t want your messy goto spaghetti jumping all over the place.
Syntax:
Nope.
Example:
Doesn’t exist. Use break with labels instead if you really need jump-like behavior.
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break outer;
}
}
Pro Tip:
If you see goto in C/C++, fine. In Java? Forget it exists.
Trivia:
One of two Java “ghost keywords” — the other is const.
if
What it does:
Conditional logic — if true, do stuff. The backbone of decision making.
Syntax:
if (condition) {
// do this
}
Example:
public class Main {
public static void main(String[] args) {
int score = 90;
if (score >= 50) {
System.out.println(“Pass”);
} else {
System.out.println(“Fail”);
}
}
}
// Output: Pass
Pro Tip:
Always use {} for clarity, even for single-line ifs.
if (flag)
doSomething(); // works, but brace it anyway!
Gotcha:
if conditions must be boolean. if (1)? Compiler goes brrr:
implements
What it does:
Tells a class to promise it’ll fulfill an interface’s contract — like signing a contract with the compiler.
Syntax:
class MyClass implements MyInterface { }
Example:
interface Animal {
void makeSound();
}
class Cat implements Animal {
public void makeSound() {
System.out.println(“Meow”);
}
}
public class Main {
public static void main(String[] args) {
Cat c = new Cat();
c.makeSound();
}
}
// Output: Meow
Pro Tip:
A class can implements multiple interfaces:
class Dog implements Animal, Pet { }
Gotcha:
When you implement an interface, you must provide implementations for all methods — unless your class is abstract.
import
What it does:
Brings other packages/classes into scope — saves you from writing long fully-qualified names every 2 seconds.
Syntax:
import java.util.Scanner;
import java.util.*; // Wildcard
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“Type something: “);
String input = sc.nextLine();
System.out.println(“You typed: ” + input);
}
}
Pro Tip:
import static brings in static members:
import static java.lang.Math.PI;
System.out.println(PI); // 3.141592…
Gotcha:
Wildcard imports (import java.util.*;) don’t import subpackages.
import java.util.*; won’t magically pull in java.util.concurrent.*;.
Trivia:
import is compile-time only — it’s just for your convenience. JVM doesn’t care.
instanceof
What it does:
Checks if an object is an instance of a class/interface. Super handy for type safety.
Syntax:
object instanceof ClassName
Example:
public class Main {
public static void main(String[] args) {
String s = “hello”;
if (s instanceof String) {
System.out.println(“Yep, it’s a String”);
}
}
}
// Output: Yep, it’s a String
Pattern Matching (Java 16+):
if (obj instanceof String str) {
System.out.println(str.toUpperCase());
}
Pro Tip:
If null instanceof Something → always false.
Gotcha:
Overusing instanceof might mean you’re missing polymorphism. Don’t use it for everything.
int
What it does:
Primitive type — 32-bit signed integer. The bread and butter of all your counting loops.
Syntax:
int x = 42;
Example:
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println(“Sum: ” + sum);
}
}
// Output: Sum: 30
Pro Tip:
int defaults to 0. Uninitialized local int though? Compiler yells at you.
Gotcha:
Overflow is real — 2147483647 + 1 wraps to negative.
interface
What it does:
Declares an interface — a 100% abstract contract that classes implement.
Syntax:
interface Animal {
void makeSound();
}
Example:
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println(“Woof!”);
}
}
public class Main {
public static void main(String[] args) {
Animal d = new Dog();
d.makeSound(); // Woof!
}
}
Pro Tip:
Since Java 8, interfaces can have default and static methods.
Gotcha:
No constructors in interfaces — they’re blueprints, not buildings.
Trivia:
Multiple inheritance is possible through interfaces. So Java kinda cheats at “single inheritance.”
long
What it does:
Primitive type — 64-bit signed integer. When int just ain’t big enough.
Syntax:
long bigNumber = 1234567890L; // ‘L’ is important!
Example:
public class Main {
public static void main(String[] args) {
long population = 8000000000L; // L is key
System.out.println(“Population: ” + population);
}
}
Pro Tip:
Always use L or l — or Java will treat it as int.
Gotcha:
Don’t use lowercase l — it looks like 1 — L is clearer.
native
What it does:
Declares a method implemented outside Java — usually in C/C++ via JNI (Java Native Interface).
Syntax:
public native void myNativeMethod();
Example:
A real native example needs C code too — here’s just the vibe:
class Example {
public native void sayHello();
static {
System.loadLibrary(“MyLibrary”);
}
}
Pro Tip:
native is used when you need low-level OS interaction or legacy code.
Gotcha:
Native code can break Java’s portability and safety guarantees. Use carefully.
Trivia:
Old-school Java AWT used native under the hood to talk to the OS windowing system.
new
What it does:
Allocates memory for a new object or array — fires up constructors, brings classes to life.
Syntax:
ClassName obj = new ClassName();
Example:
public class Dog {
Dog() {
System.out.println(“Dog created!”);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog(); // Dog created!
}
}
Arrays:
int[] numbers = new int[5];
Pro Tip:
new always calls a constructor — you can’t skip it for objects.
Gotcha:
When you do new, you get a new instance — always. No reuse magic. If you want reuse, look into Singleton or factory patterns.
Trivia:
new can’t be overridden or overloaded. It’s baked into the JVM.
null
What it does:
Represents the absence of an object reference. Means: “This variable points to nothing. Nada. Zilch.”
Syntax:
String name = null;
Example:
public class Main {
public static void main(String[] args) {
String s = null;
if (s == null) {
System.out.println(“s is null”);
}
}
}
// Output: s is null
Pro Tip:
null is not an object, not a value — it’s a literal.
Gotcha:
Dereferencing null → NullPointerException (NPE) → the horror of every Java dev.
String s = null;
System.out.println(s.length()); // BOOM! NPE
Trivia:
Since Java 14, you get better NullPointerException messages with -XX:+ShowCodeDetailsInExceptionMessages. Huge win.
package
What it does:
Defines a namespace for your classes. Organizes code, avoids name clashes.
Syntax:
package com.shashwat.blog;
Example:
package myapp.utils;
public class Helper {
public static void greet() {
System.out.println(“Hello from Helper!”);
}
}
Pro Tip:
Package name = folder structure. So package com.shashwat.blog; means your .java file sits in /com/shashwat/blog/.
Gotcha:
First non-comment line in the .java file must be the package declaration.
Trivia:
Java has default package — no package line → compiler puts it in an unnamed package. Not recommended for real projects.
private
What it does:
Access modifier — restricts access to class members. Only visible inside that class.
Syntax:
class Person {
private String name;
}
Example:
class Person {
private String name = “Shashwat”;
private void secret() {
System.out.println(“My secret”);
}
public void showName() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
// p.name = “ABC”; // Can’t access
// p.secret(); // Can’t access
p.showName(); // Can access via public method
}
}
Pro Tip:
private + getter/setter = encapsulation 101.
Gotcha:
private means private to the class, not to the object. So another method in the same class can access it for any object.
protected
What it does:
Access modifier — visible within the same package and in subclasses (even if the subclass is in a different package).
Syntax:
protected int age;
Example:
class Parent {
protected void show() {
System.out.println(“Protected method”);
}
}
class Child extends Parent {
void display() {
show(); // Can access protected member
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.display();
}
}
Pro Tip:
protected is rarely used for fields — mostly for methods you want subclasses to override.
Gotcha:
Outside package + not a subclass? Can’t touch it.
public
What it does:
Access modifier — open to the world. Anyone, anywhere can access it.
Syntax:
public class Car {
public void drive() { }
}
Example:
public class Animal {
public void sound() {
System.out.println(“Animal sound”);
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
a.sound();
}
}
Pro Tip:
A .java file can have only one public top-level class — and its name must match the filename.
Gotcha:
Public doesn’t mean safe — you still need good design. Don’t make everything public just because you can!
return
What it does:
Ends a method and optionally hands a value back to whoever called it. Basically: “I’m done. Take this and get out.”
Syntax:
return value;
Example:
public class Main {
static int add(int a, int b) {
return a + b; // Send back result
}
public static void main(String[] args) {
int sum = add(5, 10);
System.out.println(“Sum: ” + sum);
}
}
// Output: Sum: 15
Pro Tip:
void methods still use return; to break out early.
void check(int x) {
if (x < 0) return;
System.out.println(“x is positive”);
}
Gotcha:
Method’s declared return type must match the returned value — no sneaky type swaps.
short
What it does:
Primitive type — 16-bit signed integer. Saves memory compared to int but barely used these days.
Syntax:
short age = 25;
Example:
public class Main {
public static void main(String[] args) {
short a = 1000;
short b = 2000;
short sum = (short) (a + b); // Casting needed!
System.out.println(“Sum: ” + sum);
}
}
// Output: Sum: 3000
Pro Tip:
Arithmetic ops promote short to int. So you’ll usually cast back.
Gotcha:
Overflow is real: short max is 32,767. Add one → wraps negative.
static
What it does:
Marks members that belong to the class, not to an instance. Think: “One copy for everyone.”
Syntax:
static int count = 0;
Example:
class Counter {
static int count = 0;
Counter() {
count++;
}
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(“Objects created: ” + Counter.count);
}
}
// Output: Objects created: 2
Static methods:
class MathUtil {
static int square(int x) {
return x * x;
}
}
Pro Tip:
main is static because the JVM runs it without creating an object.
Gotcha:
static methods can’t use this — no instance context.
strictfp
What it does:
Controls floating-point precision for portability — makes FP math behave the same on all platforms.
Syntax:
strictfp class MyClass { }
strictfp void myMethod() { }
Example:
strictfp class Calc {
strictfp double compute(double a, double b) {
return a * b / 3.14;
}
}
Pro Tip:
Rarely used — today’s JVMs already follow IEEE 754, but strictfp enforces it just in case.
Gotcha:
Can only be used on classes, interfaces, and methods — not variables.
super
What it does:
Refers to the parent class. Use it to:
- Call the superclass constructor.
- Access a superclass method/field.
Syntax:
super();
super.methodName();
Example:
class Animal {
void sound() {
System.out.println(“Animal sound”);
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Call parent version
System.out.println(“Dog barks”);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
// Output:
// Animal sound
// Dog barks
Constructor:
class Animal {
Animal() {
System.out.println(“Animal constructor”);
}
}
class Dog extends Animal {
Dog() {
super(); // Calls Animal()
System.out.println(“Dog constructor”);
}
}
Pro Tip:
super must be the first statement in a constructor if you use it.
Gotcha:
You can’t use super in a static context — no instance, no parent.
switch
What it does:
Multi-way branch. Picks which case to run based on a value.
Syntax:
switch (value) {
case X: break;
default: break;
}
Example:
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: System.out.println(“Monday”); break;
case 2: System.out.println(“Tuesday”); break;
default: System.out.println(“Other day”);
}
}
}
// Output: Other day
Java 14+:
Switch expressions are cooler now:
int day = 2;
String name = switch (day) {
case 1 -> “Monday”;
case 2 -> “Tuesday”;
default -> “Other”;
};
Pro Tip:
switch works with byte, short, char, int, String (Java 7+) and enums.
Gotcha:
Forgetting break → fall-through chaos.
synchronized
What it does:
Locks a method or block so only one thread can execute it at a time. Essential for safe multi-threading.
Syntax:
synchronized void method() { … }
synchronized (object) {
// block of code
}
Example:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
Block:
synchronized (this) {
// thread-safe code here
}
Pro Tip:
Synchronize only what’s needed — too much = performance hit.
Gotcha:
Deadlocks are real. Two threads, two locks, wrong order → eternal hug of death.
this
What it does:
Refers to the current object. Used for:
- Disambiguating fields & params
- Calling other constructors
- Passing the current object
Syntax:
this.variable
this()
Example:
class Person {
String name;
Person(String name) {
this.name = name; // clarify field vs param
}
void sayHello() {
System.out.println(“Hello, ” + this.name);
}
}
Call another constructor:
Person() {
this(“Shashwat”); // calls Person(String)
}
Pro Tip:
this is also used to pass the current instance:
public class A {
void show() {
B b = new B(this);
}
}
Gotcha:
this inside static? Compiler goes — static context has no instance.
throw
What it does:
Throws an exception right now. Yeet that error.
Syntax:
throw new ExceptionType(“message”);
Example:
public class Main {
static void check(int age) {
if (age < 18) {
throw new IllegalArgumentException(“Too young!”);
}
System.out.println(“Welcome!”);
}
public static void main(String[] args) {
check(15); // Boom! Exception thrown.
}
}
Pro Tip:
Custom exceptions = define your own classes extending Exception or RuntimeException.
Gotcha:
After throw, nothing runs in that method — it yeets and bails.
throws
What it does:
Declares that a method might throw checked exceptions — so caller knows to handle it.
Syntax:
void myMethod() throws IOException, SQLException { … }
Example:
import java.io.*;
public class Main {
static void readFile() throws IOException {
FileReader fr = new FileReader(“file.txt”);
fr.close();
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println(“Caught: ” + e);
}
}
}
Pro Tip:
Checked exceptions (IOException, SQLException, etc.) must be declared or handled.
Gotcha:
throws just declares, doesn’t handle. try-catch actually handles it.
transient
What it does:
Marks a field to be skipped during serialization. So it won’t be saved to disk or transferred.
Syntax:
transient int secret;
Example:
import java.io.*;
class User implements Serializable {
String name;
transient String password; // won’t be saved
}
public class Main {
public static void main(String[] args) throws Exception {
User u = new User();
u.name = “Shashwat”;
u.password = “12345”;
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(“user.ser”));
out.writeObject(u);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“user.ser”));
User loaded = (User) in.readObject();
System.out.println(“Name: ” + loaded.name); // Shashwat
System.out.println(“Password: ” + loaded.password); // null!
}
}
Pro Tip:
Use for sensitive info you don’t want serialized — like passwords, keys, temp caches.
Gotcha:
Doesn’t encrypt — it just skips. You’re still responsible for security.
try
What it does:
Starts a block where you test risky code that might throw an exception.
Syntax:
try {
// risky stuff
} catch (Exception e) {
// handle it
} finally {
// always runs
}
Example:
public class Main {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(“Can’t divide by zero!”);
} finally {
System.out.println(“Done!”);
}
}
}
// Output:
// Can’t divide by zero!
// Done!
Try-with-resources (Java 7+):
try (FileReader fr = new FileReader(“file.txt”)) {
// auto-closes fr
} catch (IOException e) {
e.printStackTrace();
}
Pro Tip:
Try-with-resources auto-closes anything that implements AutoCloseable.
Gotcha:
At least one catch or finally must follow a try.
void
What it does:
Means a method returns nothing. It does the thing, then leaves.
Your classic main is void — it just runs and exits.
Syntax:
void methodName() { … }
Example:
public class Main {
static void greet() {
System.out.println(“Hey Shashwat!”);
}
public static void main(String[] args) {
greet(); // Hey Shashwat!
}
}
Pro Tip:
void only works with methods — not variables.
Gotcha:
If you return something in a void method — compiler yells:
void oops() {
return 1; // Nope!
}
volatile
What it does:
Tells the JVM that a variable may be modified by multiple threads — so don’t cache it, always read from main memory.
Syntax:
volatile boolean flag;
Example:
class Shared {
volatile boolean running = true;
void stop() {
running = false;
}
void run() {
while (running) {
// do stuff
}
}
}
Pro Tip:
volatile guarantees visibility, not atomicity.
So volatile int counter still needs synchronized or AtomicInteger for counter++.
Gotcha:
Doesn’t magically make your code thread-safe. It just stops stale reads.
while
What it does:
Runs a block of code as long as a condition is true. The OG loop buddy.
Syntax:
while (condition) {
// do stuff
}
Example:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(“i: ” + i);
i++;
}
}
}
// Output: i: 0 … i: 4
Do-While:
Runs at least once — condition checked after body.
int j = 0;
do {
System.out.println(“j: ” + j);
j++;
} while (j < 3);
Pro Tip:
Infinite while (true) loops are common in servers, game loops, etc.
Just don’t forget a break or your CPU will hate you.
NOW YOU NOW KNOW ALL 51 JAVA KEYWORDS