Basics
Quick reference guide for Java basics.
🚌 Fundamentals
Input & Output
// Printing to console
System.out.println("Hello, World!");
// Hello, World!
int a = 1;
System.out.println("Hello world! " + a);
// Hello world! 1
// Reading input
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
// Enter your name: Sid
// Hello, Sid!
Variables & Data Types
// Primitive Types
int age = 25; // Integer
double price = 19.99; // Floating point
char grade = 'A'; // Character
boolean isStudent = true; // Boolean
// Reference Types
String name = "Alice"; // String
Integer count = 10; // Wrapper class
Double amount = 15.75; // Wrapper class
// Arrays
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
// Constants
final double PI = 3.14159;
Operators
// Arithmetic operators
int sum = 5 + 3; // 8
int diff = 5 - 3; // 2
int product = 5 * 3; // 15
int quotient = 5 / 2; // 2 (integer division)
double result = 5.0 / 2.0; // 2.5
int remainder = 5 % 2; // 1
// Compound assignment
int number = 10;
number += 5; // number = number + 5
number -= 3; // number = number - 3
number *= 2; // number = number * 2
number /= 4; // number = number / 4
// Increment/decrement
int count = 0;
count++; // count = count + 1
int prefixInc = ++count; // increment first, then assign
int postfixInc = count++; // assign first, then increment
Conditionals
String name = "George";
if (name.equals("Debora")) {
System.out.println("Hi Debora!");
} else if (name.equals("George")) {
System.out.println("Hi George!");
}
// Hi George!
int x = 10;
if (x > 5) {
System.out.println("Greater");
} else if (x == 5) {
System.out.println("Equal");
} else {
System.out.println("Smaller");
}
// Greater
Switch Statement
// Basic switch
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("Other day");
}
// Wednesday
// Switch expression (Java 14+)
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> "Weekend";
};
System.out.println(dayName); // Wednesday
Loops
// For loop
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
// 0
// 1
// 2
// Enhanced for loop (for-each)
String[] pets = {"Bella", "Milo", "Loki"};
for (String pet : pets) {
System.out.println(pet);
}
// Bella
// Milo
// Loki
// While loop
int x = 3;
while (x > 0) {
System.out.println(x);
x--;
}
// 3
// 2
// 1
// Do-while loop
int y = 1;
do {
System.out.println("Executed at least once: " + y);
y++;
} while (y < 3);
// Executed at least once: 1
// Executed at least once: 2
Continue and Break
// Continue - skips current iteration
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip when i is 2
}
System.out.println(i);
}
// 0
// 1
// 3
// 4
// Break - exits the loop
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // Exit loop when i is 3
}
System.out.println(i);
}
// 0
// 1
// 2
Strings
// String creation
String name = "Java";
String greeting = new String("Hello there!");
// String concatenation
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // John Doe
// StringBuilder for efficient string manipulation
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
System.out.println(result); // Hello World
// String length
String text = "Hello";
System.out.println(text.length()); // 5
// String methods
String sentence = "java programming";
System.out.println(sentence.toUpperCase()); // JAVA PROGRAMMING
System.out.println(sentence.substring(0, 4)); // java
System.out.println(sentence.replace('a', 'o')); // jovo progromming
System.out.println(sentence.contains("gram")); // true
System.out.println(sentence.charAt(0)); // j
// String comparison
String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // false
System.out.println(s1.equalsIgnoreCase(s2)); // true
🚀 Functions (Methods)
Method Declaration
// Basic method
public void sayHello(String name) {
System.out.println("Hello " + name);
}
// Method with return value
public int add(int a, int b) {
return a + b;
}
// Method with variable arguments
public double average(double... numbers) {
double sum = 0;
for (double num : numbers) {
sum += num;
}
return numbers.length > 0 ? sum / numbers.length : 0;
}
// Method call examples
sayHello("Carlos"); // Hello Carlos
int sum = add(7, 8); // 15
double avg = average(1.0, 2.0, 3.0); // 2.0
Method Overloading
// Method overloading - same name, different parameters
public void display(int number) {
System.out.println("Integer: " + number);
}
public void display(String text) {
System.out.println("String: " + text);
}
public void display(double number) {
System.out.println("Double: " + number);
}
// Method calls
display(10); // Integer: 10
display("Hello"); // String: Hello
display(5.5); // Double: 5.5
📚 Collections
ArrayList
import java.util.ArrayList;
// Creating ArrayList
ArrayList<String> names = new ArrayList<>();
// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Accessing elements
String firstName = names.get(0); // Alice
// Modifying elements
names.set(1, "Robert"); // Replace "Bob" with "Robert"
// Removing elements
names.remove(2); // Remove "Charlie"
names.remove("Alice"); // Remove by value
// Size of ArrayList
int size = names.size();
// Checking if empty
boolean isEmpty = names.isEmpty();
// Iterating through ArrayList
for (String name : names) {
System.out.println(name);
}
// Clearing ArrayList
names.clear();
HashMap
import java.util.HashMap;
import java.util.Map;
// Creating HashMap
HashMap<String, Integer> ages = new HashMap<>();
// Adding key-value pairs
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
// Accessing values
int aliceAge = ages.get("Alice"); // 25
// Checking if key exists
boolean hasKey = ages.containsKey("Bob"); // true
// Checking if value exists
boolean hasValue = ages.containsValue(40); // false
// Removing entries
ages.remove("Charlie");
// Size of HashMap
int size = ages.size();
// Iterating through HashMap
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Iterating through keys
for (String key : ages.keySet()) {
System.out.println(key);
}
// Iterating through values
for (Integer value : ages.values()) {
System.out.println(value);
}
HashSet
import java.util.HashSet;
// Creating HashSet
HashSet<String> fruits = new HashSet<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // Duplicate, won't be added
// Size of HashSet
int size = fruits.size(); // 3 (no duplicates)
// Checking if element exists
boolean hasApple = fruits.contains("Apple"); // true
// Removing elements
fruits.remove("Banana");
// Iterating through HashSet
for (String fruit : fruits) {
System.out.println(fruit);
}
// Clearing HashSet
fruits.clear();
🔄 LinkedList
import java.util.LinkedList;
// Creating LinkedList
LinkedList<String> list = new LinkedList<>();
// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Special operations (besides ArrayList methods)
list.addFirst("First"); // Add at beginning
list.addLast("Last"); // Add at end
String first = list.getFirst(); // Get first element
String last = list.getLast(); // Get last element
list.removeFirst(); // Remove first element
list.removeLast(); // Remove last element
📝 Exception Handling
// Basic try-catch
try {
int result = 10 / 0; // Will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
}
// Try-catch-finally
try {
String text = null;
System.out.println(text.length()); // Will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Error: Null reference");
} finally {
System.out.println("This will always execute");
}
// Multiple catch blocks
try {
int[] numbers = new int[5];
numbers[10] = 50; // Will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds");
} catch (Exception e) {
System.out.println("Error: General exception");
}
// Throwing exceptions
public void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
// Try-with-resources (Java 7+)
try (Scanner scanner = new Scanner(System.in)) {
String input = scanner.nextLine();
System.out.println("You entered: " + input);
} // Scanner will be automatically closed
🧩 Classes and Objects
// Class definition
public class Person {
// Instance variables
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
// Method
public void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
// Static method
public static Person createAdult(String name) {
return new Person(name, 18);
}
}
// Using the class
Person person1 = new Person("Alice", 25);
person1.introduce(); // Hi, I'm Alice and I'm 25 years old.
Person person2 = new Person();
person2.setName("Bob");
person2.setAge(30);
System.out.println(person2.getName()); // Bob
Person adult = Person.createAdult("Charlie");
adult.introduce(); // Hi, I'm Charlie and I'm 18 years old.
🔄 Inheritance and Polymorphism
// Parent class
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
// Child class
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // Call parent constructor
this.breed = breed;
}
// Override parent method
@Override
public void makeSound() {
System.out.println("Woof! Woof!");
}
// Additional method
public void fetch() {
System.out.println(name + " is fetching the ball!");
}
}
// Using polymorphism
Animal myPet = new Dog("Buddy", "Golden Retriever");
myPet.makeSound(); // Woof! Woof!
// Type casting
if (myPet instanceof Dog) {
Dog myDog = (Dog) myPet;
myDog.fetch(); // Buddy is fetching the ball!
}
🔒 Interfaces and Abstract Classes
// Interface
public interface Drawable {
void draw(); // Abstract method (no body)
// Default method (Java 8+)
default void display() {
System.out.println("Displaying drawable object");
}
}
// Abstract class
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
// Abstract method
public abstract double calculateArea();
// Concrete method
public void displayColor() {
System.out.println("Color: " + color);
}
}
// Concrete class implementing interface and extending abstract class
public class Circle extends Shape implements Drawable {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public void draw() {
System.out.println("Drawing a " + color + " circle");
}
}
// Using the classes
Circle circle = new Circle("Red", 5.0);
circle.draw(); // Drawing a Red circle
circle.display(); // Displaying drawable object
circle.displayColor(); // Color: Red
System.out.println("Area: " + circle.calculateArea()); // Area: 78.53981633974483