Java

This Java cheatsheet provides a complete

This Java cheatsheet is designed for students and developers to provide a complete reference to Java syntax and features. It covers basics, control flow, functions, OOP, exception handling, file handling, multithreading, collections, and advanced topics.

Hello World

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }

Data Types

Java data types fall into two main categories:

Primitive Data Types (8 types)

These store simple values directly in memory.

Data TypeSizeDefaultExampleRange
byte8-bit0byte b = 100;-128 to 127
short16-bit0short s = 10000;-32,768 to 32,767
int32-bit0int i = 50000;-2,147,483,648 to 2,147,483,647
long64-bit0Llong l = 100000L;Very large range
float32-bit0.0ffloat f = 3.14f;~6-7 decimal digits
double64-bit0.0ddouble d = 3.1415;~15-16 decimal digits
char16-bit'\u0000'char c = 'A';Unicode characters
boolean1-bit*falseboolean isTrue = true;true or false
  • Actual size of boolean is JVM-dependent, typically 1 byte.

Non-Primitive Data Types (Reference Types)

These store references to objects.

TypeExampleDescription
StringString name = "Hacker Bytez";Sequence of characters (not primitive)
Arrayint[] nums = {1, 2, 3};Collection of elements of same type
ClassMyClass obj = new MyClass();Custom object with fields and methods
InterfaceRunnable r = () -> {}Blueprint for classes

Java Code Example

public class DataTypeDemo { public static void main(String[] args) { int age = 25; float height = 5.9f; char grade = 'A'; boolean isPassed = true; String name = "Hacker Bytez"; System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Height: " + height); System.out.println("Grade: " + grade); System.out.println("Passed: " + isPassed); } }

Output:

Name: Hacker Bytez
Age: 25
Height: 5.9
Grade: A
Passed: true

Variables and Constants

What is a Variable?

A variable is a named memory location used to store data that can change during program execution.

Syntax:

dataType variableName = value;

Example:

int age = 25; String name = "Bablu"; boolean isActive = true;

Types of Variables:

Java has three types of variables:

TypeScope & Behavior
LocalDeclared inside methods or blocks. Accessible only within that scope.
InstanceDeclared inside a class but outside methods. Each object gets its own copy.
StaticDeclared with static keyword. Shared across all instances of the class.

Example with All Three:

public class User { static String company = "TechNova"; // Static variable String name; // Instance variable void setName(String newName) { String greeting = "Hello"; // Local variable name = newName; System.out.println(greeting + ", " + name); } }

Constants in Java

What is a Constant?

A constant is a variable whose value cannot be changed once assigned.

Syntax:

final dataType CONSTANT_NAME = value;

Example:

final double PI = 3.14159; final int MAX_USERS = 100;

Best Practices:

public static final String API_KEY = "XYZ123";

Key Differences

FeatureVariableConstant
MutabilityCan change during executionCannot change once assigned
KeywordNonefinal
NamingcamelCaseUPPERCASE_WITH_UNDERSCORES
Use CaseDynamic valuesFixed values like config or limits

Comments

Single-Line Comment

// This is a single line comment

Multi-Line Comment

/* This is a multi-line comment */

Input/Output

Console Input and Output

Output: System.out

Used to display information to the console.

System.out.print("Hello "); // prints without newline System.out.println("World!"); // prints with newline System.out.printf("Age: %d\n", 25); // formatted output

Input: Scanner Class

Used to read user input from the keyboard.

import java.util.Scanner; public class ConsoleIO { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.println("Hello " + name + ", age " + age); } }

Scanner supports methods like nextInt(), nextFloat(), nextLine(), etc.

File Input and Output

Java uses the java.io and java.nio packages for file operations.

Writing to a File

import java.io.FileWriter; import java.io.IOException; public class WriteToFile { public static void main(String[] args) { try { FileWriter writer = new FileWriter("output.txt"); writer.write("Hello Bablu!\nWelcome to Java I/O."); writer.close(); System.out.println("File written successfully."); } catch (IOException e) { System.out.println("An error occurred."); } } }

Reading from a File

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFromFile { public static void main(String[] args) { try { File file = new File("output.txt"); Scanner reader = new Scanner(file); while (reader.hasNextLine()) { String line = reader.nextLine(); System.out.println(line); } reader.close(); } catch (FileNotFoundException e) { System.out.println("File not found."); } } }

Bonus: Standard Streams

StreamPurpose
System.inStandard input (keyboard)
System.outStandard output (console)
System.errStandard error output

These can be wrapped with classes like Scanner, BufferedReader, or PrintWriter for more control.

Control Structures

control structures are the backbone of program logic—they determine the flow of execution based on conditions, loops, and branching. Let’s break them down with clear examples and best practices so you can master them for any project.

Types of Control Structures in Java

Java has three main categories of control structures:

Conditional Branching

Used to make decisions based on conditions.

if, if-else, if-else if

int score = 85; if (score >= 90) { System.out.println("Excellent!"); } else if (score >= 75) { System.out.println("Good job!"); } else { System.out.println("Keep improving."); }

switch Statement

Efficient for multiple discrete cases.

int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); }

Ternary Operator

Shorthand for simple if-else.

int age = 20; String status = (age >= 18) ? "Adult" : "Minor"; System.out.println(status);

Loops (Iteration)

Used to repeat code blocks.

🔹 for Loop

for (int i = 0; i < 5; i++) { System.out.println("Iteration: " + i); }

while Loop

int i = 0; while (i < 5) { System.out.println("While loop: " + i); i++; }

do-while Loop

Executes at least once.

int i = 0; do { System.out.println("Do-while loop: " + i); i++; } while (i < 5);

Branching Statements

Used to alter loop flow.

break

Exits the loop or switch.

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

continue

Skips current iteration.

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

return

Exits from a method.

public int square(int x) { return x * x; }

Functions / Methods

A block of reusable code performing a specific task.

public static int add(int a, int b) { return a + b; } public static void main(String[] args) { System.out.println(add(10, 20)); }

Recursion

A method calling itself to solve a problem.

public static int factorial(int n) { if (n == 1) return 1; return n * factorial(n - 1); } public static void main(String[] args) { System.out.println(factorial(5)); }

Arrays

Ordered, fixed-size collections.

int[] numbers = {10, 20, 30, 40, 50}; for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); }

Strings

Strings are sequences of characters.

String str = "Hello, Java!"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase());

Object-Oriented Programming

Class

class Employee { String name; int salary; void display() { System.out.println("Name: " + name + ", Salary: " + salary); } }

Object

Employee emp = new Employee(); emp.name = "Alice"; emp.salary = 5000; emp.display();

Constructor

class Employee { String name; int salary; Employee(String n, int s) { // Constructor name = n; salary = s; } } Employee emp = new Employee("Alice", 5000);

Inheritance

class Person { String name; } class Student extends Person { int rollNo; } Student s = new Student(); s.name = "Bob"; s.rollNo = 101;

Polymorphism

class Shape { void area() { System.out.println("Area of shape"); } } class Circle extends Shape { void area() { System.out.println("Area of circle"); } } Shape obj = new Circle(); obj.area(); // Outputs "Area of circle"

Encapsulation

class Employee { private int salary; public void setSalary(int s) { salary = s; } public int getSalary() { return salary; } } Employee emp = new Employee(); emp.setSalary(5000); System.out.println(emp.getSalary());

Exception Handling

try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Execution finished"); }

File Handling

import java.io.*; try { FileWriter fw = new FileWriter("example.txt"); fw.write("Hello, file!"); fw.close(); BufferedReader br = new BufferedReader(new FileReader("example.txt")); String line = br.readLine(); System.out.println(line); br.close(); } catch (IOException e) { e.printStackTrace(); }

Multithreading

class MyThread extends Thread { public void run() { System.out.println("Thread is running"); } } MyThread t1 = new MyThread(); t1.start();

Collections

ArrayList

import java.util.ArrayList; ArrayList<String> list = new ArrayList<>(); list.add("Alice"); list.add("Bob"); System.out.println(list);

HashMap

import java.util.HashMap; HashMap<String, Integer> map = new HashMap<>(); map.put("Alice", 25); map.put("Bob", 30); System.out.println(map);

Lambda Expressions

Runnable r = () -> System.out.println("Lambda Thread"); new Thread(r).start();

Streams

import java.util.Arrays; Arrays.asList(1,2,3,4).stream() .filter(x -> x % 2 == 0) .forEach(System.out::println);