Java
CheatSheet
TABLE OF CONTENTS
1. Introduction to Java
What is Java?
History and Features
Java Editions (JSE, JEE, JME)
JVM, JRE, and JDK
How Java Works
2. Basic Syntax
Structure of a Java Program
Comments
Main Method Explained
Data Types and Variables
Type Casting
Keywords
Input/Output (Scanner, [Link])
3. Operators
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
Ternary Operator
Operator Precedence
4. Control Statements
if, else if, else
switch Statement
Nested if Statements
5. Loops
for, while, do...while
Enhanced for-each Loop
Loop Control (break, continue)
6. Arrays
Single-Dimensional Arrays
Multi-Dimensional Arrays
Array Methods
Array Iteration
TABLE OF CONTENTS
7. Strings
String Declaration
String Methods (length, charAt, concat, compareTo, equals, etc.)
StringBuilder and StringBuffer
String Formatting
8. Methods (Functions)
Defining and Calling Methods
Method Overloading
Recursion
static Keyword
9. Object-Oriented Programming (OOP)
Classes and Objects
Constructors
this Keyword
Inheritance
super Keyword
Method Overriding
Polymorphism (Compile-time and Runtime)
Abstraction (abstract Classes)
Encapsulation
Interfaces
Access Modifiers (private, public, protected, default)
10. Exception Handling
try, catch, finally
throw and throws
Custom Exceptions
Common Exceptions
11. Packages & Imports
Built-in Packages
Creating Custom Packages
import Statement
static import
TABLE OF CONTENTS
12. Java Collections Framework
List, Set, Map Interfaces
ArrayList, LinkedList
HashSet, TreeSet
HashMap, TreeMap
Stack, Queue, PriorityQueue
Iterators and Enhanced for-each
13. File Handling
FileReader, FileWriter
BufferedReader, BufferedWriter
Scanner for File Input
File Class Operations
14. Multithreading
Threads using Thread Class and Runnable Interface
Thread Lifecycle
Synchronization
wait() and notify()
15. Java 8+ Features
Lambda Expressions
Functional Interfaces
Streams API
Optional Class
Method References
forEach and filter
16. Generics
Why Generics?
Generic Classes and Methods
Bounded Type Parameters
Wildcards (<?>, <? extends>, <? super>)
17. Annotations
Built-in Annotations (@Override, @Deprecated, etc.)
Custom Annotations
18. Wrapper Classes
Autoboxing and Unboxing
Common Methods
TABLE OF CONTENTS
19. Enums
Declaring and Using Enums
Enum Methods
20. Date and Time API
LocalDate, LocalTime, LocalDateTime
DateTimeFormatter
Legacy Date Classes (Date, Calendar)
21. Java Math & Utility Classes
Math Class
Random Class
Arrays Utility Class
Collections Utility Class
22. Basic GUI (Optional)
Swing Components Overview
AWT Basics
23. Java Best Practices
Naming Conventions
Code Optimization Tips
Clean Coding Principles
24. Mini Projects
Calculator
ATM Simulation
To-Do List Console App
File Encryption Tool
25. Java Interview Questions (Bonus)
Core Java Concepts
OOP-based Questions
Code Snippet Challenges
1. INTRODUCTION TO JAVA
1.1 What is Java?
Java is a computer language that helps us tell computers what to do. It can
be used to make:
Games
Mobile apps
Websites
Big computer programs
Just like how we use Gujarati, Hindi, or English to talk, computers use Java
to understand us.
1.2 History and Features
Java was created in 1995 by a company named Sun Microsystems.
It was later bought by Oracle (a big tech company).
Cool Features of Java:
Write once, run anywhere: You write Java code once and it can work on
many computers.
Object-Oriented: Java organizes code in reusable blocks called "objects".
Secure: Java is safe from hackers.
Simple and powerful: Easy to learn, but also very strong.
1.3 Java Editions (JSE, JEE, JME)
Java comes in 3 types (or editions), like 3 types of chocolate:
JSE (Java Standard Edition):
Used for basic things like games, calculators, and simple apps.
JEE (Java Enterprise Edition):
Used to make big programs for companies like Amazon or Flipkart.
JME (Java Micro Edition):
Used in small devices like old phones, washing machines, etc.
1.4 JVM, JRE, and JDK
These are like parts of a machine that help Java work.
JDK (Java Development Kit):
A box of tools that helps you create and run Java programs.
JRE (Java Runtime Environment):
A smaller box that lets you only run Java programs (not create them).
JVM (Java Virtual Machine):
The brain of Java. It reads your Java program and makes the computer
understand it.
1. INTRODUCTION TO JAVA
1.5 How Java Works
You write your program in Java.
Java turns it into something called Bytecode.
The JVM reads the bytecode and tells the computer what to do.
It’s like:
You write a letter in Java.
Java translates it to bytecode.
JVM reads that letter and tells the computer.
2. BASIC SYNTAX
2.1 Structure of a Java Program
A simple program in Java looks like this:
What it does:
It prints "Hello, world!" on the screen.
2.2 Comments
Comments are notes for humans reading the code. Computers ignore
comments.
2.3 Main Method Explained
This is the starting point of every Java program. It's like the "Start" button
in a game.
2.4 Data Types and Variables
Variables are like boxes to store information.
Data types tell us what kind of information is in the box.
2. BASIC SYNTAX
2.5 Type Casting
Changing from one type to another:
Or manually:
2.6 Keywords
Java has special words that are already reserved. You can't use them as
names.
Examples: class, int, if, else, while
2.7 Input/Output (Scanner, [Link])
[Link]() is used to show output on screen.
Scanner is used to take input from the user:
3. OPERATORS
3.1 Arithmetic Operators
Used to do math:
3.2 Assignment Operators
Used to give values to variables:
3.3 Comparison Operators
Used to compare things:
3. OPERATORS
3.4 Logical Operators
Used to combine conditions:
3.5 Bitwise Operators
Used in advanced calculations using 0s and 1s.
(Not needed for beginners.)
3.6 Ternary Operator
Shortcut for if...else:
It means: if a > b, then max = a, else max = b.
3.7 Operator Precedence
Some operators happen before others.
Because multiplication happens before addition.
4. CONTROL STATEMENTS
4.1 if, else if, else
Used to make decisions:
4.2 switch Statement
Checks many values:
4.3 Nested if Statements
One if inside another:
5. LOOPS
5.1 for, while, do...while
for loop:
while loop:
do...while loop:
5.2 Enhanced for-each Loop
Used for arrays (list of items):
5.3 Loop Control (break, continue)
break = stop the loop
continue = skip to the next loop
5. LOOPS
5.3 Loop Control (break, continue)
6. ARRAYS
6.1 Single-Dimensional Arrays
An array is like a row of boxes 🧃 where each box holds a value (like
numbers, names, etc.).
You can also create an empty array:
6.2 Multi-Dimensional Arrays
These are like tables or grids (rows and columns).
First number = row, second = column.
6.3 Array Methods
Java has helpful tools (methods) to work with arrays:
Other common methods:
[Link]()
[Link]()
[Link]()
6. ARRAYS
6.4 Array Iteration
You can go through each item using a loop:
Or use for-each:
7. STRINGS
7.1 String Declaration
A String is a group of characters (letters, words).
You can also do:
7.2 String Methods
Here are some magic tricks 🪄 you can do with Strings:
7.3 StringBuilder and StringBuffer
Both are used to build strings faster (like for games or apps where speed
matters):
StringBuffer is similar but safe for multi-users (thread-safe).
7.4 String Formatting
You can make strings look fancy:
8. METHODS (FUNCTIONS)
8.1 Defining and Calling Methods
Methods are blocks of code that do a task.
You can also send info:
8.2 Method Overloading
You can make methods with the same name, but different inputs:
8.3 Recursion
When a method calls itself:
It’s like a loop, but using self-calls.
8. METHODS (FUNCTIONS)
8.4 static Keyword
If a method or variable is marked as static, it belongs to the class — not
just one object.
You don’t need to create an object to use static methods.
9. OBJECT-ORIENTED PROGRAMMING (OOP)
Object-Oriented Programming helps you organize your code better using
objects. Think of it like building things in real life: You make blueprints
(classes) and then build objects from them.
9.1 Classes and Objects
A class is like a blueprint. An object is something you create from that
blueprint.
9.2 Constructors
A constructor is a special method that runs when an object is created.
You can also create constructors with parameters:
9. OBJECT-ORIENTED PROGRAMMING (OOP)
9.3 this Keyword
The this keyword refers to the current object.
9.4 Inheritance
Inheritance means a class can use things from another class.
9.5 super Keyword
super is used to call the parent class methods or constructors.
9. OBJECT-ORIENTED PROGRAMMING (OOP)
9.6 Method Overriding
When a child class changes a method from the parent class.
9.7 Polymorphism (Compile-time and Runtime)
Polymorphism means "many forms".
Compile-time (Method Overloading):
Runtime (Method Overriding):
9. OBJECT-ORIENTED PROGRAMMING (OOP)
9.8 Abstraction (abstract Classes)
Abstraction hides unnecessary details. Use abstract classes to create base
templates.
9.9 Encapsulation
Encapsulation means hiding data using private and accessing it with
methods.
9.10 Interfaces
Interfaces are like 100% abstract classes. All methods are without body.
9. OBJECT-ORIENTED PROGRAMMING (OOP)
9.11 Access Modifiers (private, public, protected, default)
private: Only inside the same class
public: Accessible everywhere
protected: Accessible in the same package and child classes
default (no keyword): Same package only
10. EXCEPTION HANDLING
10.1 try, catch, finally
Java handles errors using try-catch blocks.
10.2 throw and throws
throw is used to throw an exception.
throws is used in method signature:
10.3 Custom Exceptions
You can create your own exception class.
10. EXCEPTION HANDLING
10.4 Common Exceptions
ArithmeticException – divide by zero
NullPointerException – object is null
ArrayIndexOutOfBoundsException – index too big
NumberFormatException – wrong format for numbers
IOException – input/output error
11. PACKAGES & IMPORTS
11.1 Built-in Packages
Java comes with many ready-made packages (groups of classes).
Example:
[Link] – for tools like ArrayList, Scanner
[Link] – for reading/writing files
11.2 Creating Custom Packages
A package is a folder to organize your Java files.
11.3 import Statement
“import” helps bring in other classes or packages into your file.
11. PACKAGES & IMPORTS
11.4 static import
You can use static import to use methods directly without writing class
name.
12. JAVA COLLECTIONS FRAMEWORK
The Collection Framework lets you store and manage groups of data (like
a list of names or scores).
12.1 List, Set, Map Interfaces
List = Ordered collection (can have duplicates)
Set = No duplicates allowed
Map = Key-value pairs (like a dictionary)
12.2 ArrayList, LinkedList
ArrayList – fast to access, like an expandable array
LinkedList – better for inserting/deleting elements
12.3 HashSet, TreeSet
HashSet – no duplicates, no order
TreeSet – sorted automatically
12.4 HashMap, TreeMap
HashMap – key-value pair, fast access
12. JAVA COLLECTIONS FRAMEWORK
12.4 HashMap, TreeMap
TreeMap – sorted keys
12.5 Stack, Queue, PriorityQueue
Stack – Last In First Out (LIFO)
Queue – First In First Out (FIFO)
PriorityQueue – sorted automatically
12.6 Iterators and Enhanced for-each
Iterator – moves through a collection
Enhanced for-each
13. FILE HANDLING
13.1 FileReader, FileWriter
FileWriter – write to a file
FileReader – read from file
13.2 BufferedReader, BufferedWriter
Reads/writes faster by using a buffer.
13.3 Scanner for File Input
13. FILE HANDLING
13.4 File Class Operations
Check if file exists, or get file info:
14. MULTITHREADING
Java can do many tasks at once using threads.
14.1 Threads using Thread Class and Runnable Interface
Using Thread class:
Using Runnable:
14.2 Thread Lifecycle
States:
New
Runnable
Running
Blocked
Terminated
14.3 Synchronization
Stops threads from interfering with each other.
14. MULTITHREADING
14.4 wait() and notify()
wait() – pauses the thread
notify() – wakes up waiting thread
15. JAVA 8+ FEATURES
15.1 Lambda Expressions
Short way to write a method.
15.2 Functional Interfaces
Interfaces with only one abstract method.
15.3 Streams API
For working with data like lists.
15.4 Optional Class
Helps avoid null pointer errors.
15. JAVA 8+ FEATURES
15.5 Method References
Use :: to call methods.
15.6 forEach and filter
forEach – loop through each item
filter – choose only some items
16. GENERICS
Generics allow you to create classes, methods, and interfaces that work
with any data type without losing type safety.
16.1 Why Generics?
Generics help to reuse the same code for different data types without
worrying about type errors.
For example, if you want a list to store numbers, you use “List<Integer>”.
16.2 Generic Classes and Methods
Generic Class:
You can create a class that works with any type.
Usage:
Generic Methods:
A method can also be generic to accept different data types.
16. GENERICS
16.3 Bounded Type Parameters
You can restrict the types to specific classes.
16.4 Wildcards (<?>, <? extends>, <? super>)
Wildcards let you use unknown types.
<?> – Any type
<? extends T> – Any type that is a subclass of T
<? super T> – Any type that is a superclass of T
17. ANNOTATIONS
Annotations are special labels that add metadata to your code.
17.1 Built-in Annotations
@Override – tells the program that a method is overriding a parent
method.
@Deprecated – marks a method as old or no longer used.
@SuppressWarnings – prevents warnings from appearing for specific
code.
17.2 Custom Annotations
You can create your own annotations.
18. WRAPPER CLASSES
Wrapper classes allow you to treat primitive data types (like int, char) as
objects.
18.1 Autoboxing and Unboxing
Autoboxing – automatically converts primitive types to wrapper objects.
Unboxing – automatically converts wrapper objects back to primitive
types.
18.2 Common Methods
intValue() – returns the int value from an Integer object
doubleValue() – returns the double value from a Double object
19. ENUMS
Enums are used to represent fixed sets of constants.
19.1 Declaring and Using Enums
19.2 Enum Methods
Enums come with built-in methods like:
values() – returns an array of all enum constants.
ordinal() – returns the position of the constant.
20. DATE AND TIME API
Java provides special classes to work with dates and times.
20.1 LocalDate, LocalTime, LocalDateTime
LocalDate – represents only the date (e.g., 2025-05-07)
LocalTime – represents only the time (e.g., 10:30 AM)
LocalDateTime – represents both date and time
20.2 DateTimeFormatter
You can format dates and times with DateTimeFormatter.
20.3 Legacy Date Classes (Date, Calendar)
Date – represents a specific point in time, now outdated.
Calendar – used for calculating date/time (e.g., adding days).
21. JAVA MATH & UTILITY CLASSES
Java has built-in classes that help with mathematical operations and
various utilities for better coding practices.
21.1 Math Class
The Math class is used for mathematical operations like rounding, square
roots, trigonometric functions, etc.
[Link](a, b) – raises a to the power of b.
[Link]() – rounds a number to the nearest integer.
21.2 Random Class
The Random class is used to generate random numbers.
21.3 Arrays Utility Class
The Arrays class helps with operations on arrays, such as sorting and
searching.
21.4 Collections Utility Class
The Collections class is used for manipulating collections like lists and sets.
22. BASIC GUI (OPTIONAL)
Creating a Graphical User Interface (GUI) allows you to build applications
with windows, buttons, text fields, and other interactive elements.
22.1 Swing Components Overview
Swing is a popular library for creating GUI applications in Java. It provides
components like:
JFrame – represents a window.
JButton – represents a button.
JLabel – represents a text label.
JTextField – represents a text input field.
Example of a simple window with a button:
22.2 AWT Basics
AWT (Abstract Window Toolkit) is an older toolkit used for GUI creation. It
includes components like buttons, labels, and text areas.
23. JAVA BEST PRACTICES
Following best practices helps you write clean, efficient, and maintainable
code.
23.1 Naming Conventions
Java has specific naming rules:
Classes: Start with an uppercase letter, e.g., MyClass.
Variables: Start with a lowercase letter, e.g., myVariable.
Constants: Use all uppercase letters, e.g., MAX_SIZE.
Methods: Start with a lowercase letter, e.g., calculateTotal().
23.2 Code Optimization Tips
Use loops efficiently, avoid unnecessary calculations.
Use StringBuilder for string concatenation to improve performance.
Always use final for variables that should not change.
23.3 Clean Coding Principles
Meaningful variable names – e.g., totalAmount instead of a.
Comment only when necessary – code should be self-explanatory.
Avoid magic numbers – use constants instead, e.g., final int
MAX_STUDENTS = 30;
24. MINI PROJECTS
Building small projects is a great way to practice Java and improve your
skills.
24.1 Calculator
A simple console-based calculator app that performs operations like
addition, subtraction, etc.
24.2 ATM Simulation
A simulation of an ATM where the user can check balance, withdraw, and
deposit money.
24.3 To-Do List Console App
A simple To-Do List application where you can add, view, and delete tasks.
24.4 File Encryption Tool
This tool can encrypt and decrypt files using basic cryptography
techniques.
25. JAVA INTERVIEW QUESTIONS (BONUS)
Here’s a list of common Java interview questions you can prepare for:
25.1 Core Java Concepts
What is the difference between JVM, JRE, and JDK?
What are interfaces and abstract classes?
How does exception handling work in Java?
25.2 OOP-based Questions
What is inheritance in Java?
Explain the concept of polymorphism with an example.
How does encapsulation help in making code more secure?
25.3 Code Snippet Challenges
Write a program to reverse a string.
Write a program to find the factorial of a number.
Write a program to sort an array without using built-in methods.
Was this post helpful ?
Follow Our 2nd Account
Follow For More
Tap Here