Java Basics
First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Data Types & Variables
byte smallNumber = 100; // 8-bit integer
short mediumNumber = 10000; // 16-bit integer
int age = 25; // 32-bit integer
long bigNumber = 1000000000L; // 64-bit integer
float salary = 2500.50f; // 32-bit floating point
double pi = 3.14159; // 64-bit floating point
char grade = 'A'; // 16-bit Unicode character
boolean isJavaFun = true; // true or false
// Reference data types
String name = "John Doe"; // String object
// Constants (use final keyword)
final float TAX_RATE = 0.15f;
Operators
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 1
// Relational operators
boolean result = (a == b); // false
result = (a != b); // true
result = (a > b); // true
// Logical operators
boolean x = true, y = false;
result = (x && y); // false
result = (x || y); // true
result = !x; // false
// Assignment operators
a += 5; // equivalent to a = a + 5
b *= 2; // equivalent to b = b * 2
Basic I/O
public class BasicIO {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Output
System.out.print("Enter your name: ");
// Input
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Formatted output
System.out.printf("Hello %s, you are %d years old%n", name, age);
scanner.close();
}
}
Control Flow
Conditional Statements
if (score >= 90) {
System.out.println("Grade: A");
}
// if-else statement
if (temperature > 30) {
System.out.println("It's hot outside");
} else {
System.out.println("It's not too hot");
}
// if-else if ladder
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'F';
}
// switch statement (Java 14+ enhanced)
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
// ... other cases
default -> System.out.println("Invalid day");
}
// Ternary operator
String result = (score >= 40) ? "Pass" : "Fail";
Loops
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
System.out.println();
// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
// while loop
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
// do-while loop
int num;
do {
System.out.print("Enter a positive number: ");
num = scanner.nextInt();
} while (num <= 0);
// break and continue
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // Skip 3
if (i == 7) break; // Exit at 7
System.out.print(i + " ");
}
Arrays & Strings
Arrays
int[] numbers; // Declaration
numbers = new int[5]; // Instantiation
int[] primes = {2, 3, 5, 7, 11}; // Declaration with initialization
int[] values = new int[]{1, 2, 3, 4, 5}; // Anonymous array
// Accessing array elements
primes[0] = 2; // First element
primes[4] = 11; // Last element
int length = primes.length; // Array length
// Multi-dimensional arrays
int[][] matrix = new int[3][3]; // 3x3 matrix
matrix[0][0] = 1;
matrix[1][1] = 1;
matrix[2][2] = 1;
// Jagged array (arrays of different sizes)
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[3];
jagged[2] = new int[4];
// Array methods (java.util.Arrays)
Arrays.sort(primes);
Arrays.fill(numbers, 0);
int index = Arrays.binarySearch(primes, 5);
boolean equal = Arrays.equals(primes, values);
Strings
String str1 = "Hello"; // String literal (stored in string pool)
String str2 = new String("Hello"); // String object
// String methods
int length = str1.length(); // 5
char ch = str1.charAt(1); // 'e'
String sub = str1.substring(1, 4); // "ell"
String upper = str1.toUpperCase(); // "HELLO"
String lower = str1.toLowerCase(); // "hello"
String trimmed = " Hello ".trim(); // "Hello"
String replaced = str1.replace('l', 'p'); // "Heppo"
// String comparison
boolean isEqual = str1.equals(str2); // true (content comparison)
isEqual = (str1 == str2); // false (reference comparison)
int result = str1.compareTo("Hello"); // 0 (lexicographical comparison)
// String concatenation
String greeting = "Hello" + " " + "World"; // "Hello World"
greeting = str1.concat(" World"); // "Hello World"
// StringBuilder (mutable, for frequent modifications)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String message = sb.toString(); // "Hello World"
Object-Oriented Programming
Classes & Objects
public class Car {
// Fields (instance variables)
private String brand;
private String model;
private int year;
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Default constructor
public Car() {
this.brand = "Unknown";
this.model = "Unknown";
this.year = 0;
}
// Methods
public void start() {
System.out.println("Car started");
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
// toString method
public String toString() {
return "Car{brand='" + brand + "', model='" + model + "', year=" + year + "}";
}
}
// Creating objects
Car myCar = new Car("Toyota", "Corolla", 2020);
Car defaultCar = new Car();
// Accessing methods
myCar.start();
String brand = myCar.getBrand();
System.out.println(myCar); // Calls toString() method
Inheritance & Polymorphism
public class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
public void honk() {
System.out.println("Beep beep!");
}
}
public class Bike extends Vehicle {
private int gears;
public Bike(String brand, int gears) {
super(brand); // Call parent constructor
this.gears = gears;
}
// Method overriding
public void honk() {
System.out.println("Ring ring!");
}
// Method overloading
public void honk(int times) {
for (int i = 0; i < times; i++) {
System.out.print("Ring! ");
}
System.out.println();
}
}
// Polymorphism
Vehicle myVehicle = new Bike("Giant", 21);
myVehicle.honk(); // Calls Bike's honk() method
// Casting
if (myVehicle instanceof Bike) {
Bike myBike = (Bike) myVehicle;
myBike.honk(3); // Ring! Ring! Ring!
}
// Abstract classes and methods
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI * radius * radius;
}
public double perimeter() {
return 2 * Math.PI * radius;
}
}
Exception Handling
Try-Catch Blocks
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}
// Multiple catch blocks
try {
int[] numbers = new int[5];
numbers[10] = 50; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
} catch (Exception e) {
System.out.println("Some other exception occurred");
}
// Finally block
try {
FileReader file = new FileReader("file.txt");
// Read from file
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
} finally {
// This block always executes
System.out.println("Finally block executed");
}
// Try-with-resources (Java 7+)
try (FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
} // Resources are automatically closed
Custom Exceptions
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds: " + amount);
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
// Using custom exception
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
}
// Handling custom exception
public class BankApp {
public static void main(String[] args) {
BankAccount account = new BankAccount(500);
try {
account.withdraw(600);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
}
}
}
// Common built-in exceptions
// - NullPointerException: Accessing null object reference
// - ArrayIndexOutOfBoundsException: Invalid array index
// - IllegalArgumentException: Illegal argument passed to method
// - IOException: Input/output operation failure
// - ClassNotFoundException: Class not found
// - UnsupportedOperationException: Unsupported operation
Collections Framework
Lists & Sets
// ArrayList (resizable array)
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
arrayList.remove("Banana");
String fruit = arrayList.get(0); // "Apple"
// LinkedList (doubly-linked list)
List<Integer> linkedList = new LinkedList<>();
linkedList.add(10);
linkedList.add(20);
linkedList.addFirst(5); // Adds to beginning
// HashSet (unordered, no duplicates)
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Apple"); // Duplicate, won't be added
boolean hasApple = hashSet.contains("Apple"); // true
// TreeSet (sorted set)
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(5);
treeSet.add(2);
treeSet.add(8);
// Elements will be in order: 2, 5, 8
// Iterating through collections
// Using for-each loop
for (String item : arrayList) {
System.out.println(item);
}
// Using iterator
Iterator<String> iterator = arrayList.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
}
// Using forEach with lambda (Java 8+)
arrayList.forEach(item -> System.out.println(item));
Maps
// HashMap (key-value pairs, no order)
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Apple", 10);
hashMap.put("Banana", 20);
hashMap.put("Cherry", 30);
int appleCount = hashMap.get("Apple"); // 10
boolean hasMango = hashMap.containsKey("Mango"); // false
// TreeMap (sorted by keys)
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Zucchini", 5);
treeMap.put("Apple");
treeMap.put("Banana");
// Keys will be sorted: Apple, Banana, Zucchini
// LinkedHashMap (maintains insertion order)
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("Zucchini", 5);
linkedHashMap.put("Apple");
linkedHashMap.put("Banana");
// Order will be: Zucchini, Apple, Banana
// Iterating through maps
// Using keySet()
for (String key : hashMap.keySet()) {
System.out.println(key + ": " + hashMap.get(key));
}
// Using entrySet() (more efficient)
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Using forEach with lambda (Java 8+)
hashMap.forEach((key, value) ->
System.out.println(key + ": " + value));
// Common Map methods
int size = hashMap.size();
boolean isEmpty = hashMap.isEmpty();
hashMap.remove("Banana");
hashMap.clear();
Practice is key to mastering Java programming!
Comprehensive Java Programming Cheatsheet Reference
This Java Programming cheatsheet on Nikhil Learn Hub collects syntax, commands, and practical snippets for quick revision. Practice Java syntax, OOP concepts, collections, exception handling, and programming techniques with simple examples.
Use the reference cards and examples above during coding sessions; return here instead of scattered searches when you need dependable reminders. New learners can pair this sheet with the Java tutorial. Follow the Java learning roadmap when you want structured lessons beyond one-page lookups.
Quick lookup coverage
- Syntax, commands, and API signatures
- Copy-ready examples and common patterns
- Terminology for coursework and interviews
- Cross-links to the matching learning roadmap
How to study with this sheet
- Production debugging and tuning reminders
- Security, performance, or scale cautions
- Integration with adjacent stacks on this site
- Deeper study through tutorials and roadmaps
Who Should Use This Cheatsheet
Students, self-taught developers, and professionals who need fast Java Programming lookups during labs, debugging, or interview revision should keep this page bookmarked.
Related Resources on Nikhil Learn Hub
- Java learning roadmapstructured learning path for the same technology
- Cheatsheets hubbrowse all quick-reference sheets
- Technology hubtutorials, roadmaps, and practice hubs