Object-oriented programming with Java
Simple class example with constructors, getters, and setters:
// Simple class example
public class Person {
// Instance variables
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Setter methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
}
If-else statements, switch, and ternary operators:
public class ControlFlow {
// if-else statement
public static String checkNumber(int num) {
if (num > 0) {
return "positive";
} else if (num < 0) {
return "negative";
} else {
return "zero";
}
}
// switch statement
public static String getDayName(int day) {
switch (day) {
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
default:
return "Invalid day";
}
}
// Ternary operator
public static int max(int a, int b) {
return (a > b) ? a : b;
}
}
For loops, while loops, and enhanced for loops:
public class Loops {
// for loop
public static void printNumbers() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
// enhanced for loop (for-each)
public static void printArray(String[] array) {
for (String item : array) {
System.out.println(item);
}
}
// while loop
public static int factorial(int n) {
int result = 1;
int i = 1;
while (i <= n) {
result *= i;
i++;
}
return result;
}
// do-while loop
public static void doWhileExample() {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
}
// break and continue
public static void breakContinueExample() {
for (int i = 0; i < 10; i++) {
if (i == 3) {
continue; // Skip 3
}
if (i == 7) {
break; // Stop at 7
}
System.out.println(i);
}
}
}
Working with arrays, ArrayList, HashMap, and HashSet:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Collections {
// Arrays
public static void arrayExample() {
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
// Multi-dimensional array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
}
// ArrayList
public static void arrayListExample() {
ArrayList list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Iterate
for (String fruit : list) {
System.out.println(fruit);
}
// Access by index
String first = list.get(0);
list.remove(1);
int size = list.size();
}
// HashMap
public static void hashMapExample() {
HashMap map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
int age = map.get("Alice");
boolean hasKey = map.containsKey("Bob");
// Iterate
for (String name : map.keySet()) {
System.out.println(name + ": " + map.get(name));
}
}
// HashSet
public static void hashSetExample() {
HashSet set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
set.add(2); // Duplicate ignored
boolean contains = set.contains(2);
set.remove(3);
}
}
Try-catch-finally, try-with-resources, and custom exceptions:
public class ExceptionHandling {
// Try-catch
public static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.err.println("Cannot divide by zero");
return 0;
}
}
// Try-catch-finally
public static void readFile(String filename) {
FileReader reader = null;
try {
reader = new FileReader(filename);
// Read file...
} catch (FileNotFoundException e) {
System.err.println("File not found: " + filename);
} catch (IOException e) {
System.err.println("Error reading file");
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
}
// Try-with-resources (Java 7+)
public static void readFileModern(String filename) {
try (FileReader reader = new FileReader(filename)) {
// Read file...
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
// Throwing exceptions
public static void validateAge(int age) throws IllegalArgumentException {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Invalid age: " + age);
}
}
// Custom exception
public static class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}
}
Base classes, derived classes, and method overriding:
// Base class
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Derived class
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // Call parent constructor
this.breed = breed;
}
// Override method
@Override
public void eat() {
System.out.println(name + " the dog is eating");
}
// New method
public void bark() {
System.out.println(name + " says: Woof!");
}
}
// Another derived class
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void eat() {
System.out.println(name + " the cat is eating");
}
public void meow() {
System.out.println(name + " says: Meow!");
}
}
Interface definitions and implementations:
// Interface definition
public interface Drawable {
void draw();
void setColor(String color);
String getColor();
}
// Another interface
public interface Resizable {
void resize(double factor);
}
// Implementing single interface
public class Circle implements Drawable {
private double radius;
private String color;
public Circle(double radius) {
this.radius = radius;
this.color = "black";
}
@Override
public void draw() {
System.out.println("Drawing a " + color + " circle");
}
@Override
public void setColor(String color) {
this.color = color;
}
@Override
public String getColor() {
return color;
}
}
// Implementing multiple interfaces
public class Rectangle implements Drawable, Resizable {
private double width;
private double height;
private String color;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
this.color = "black";
}
@Override
public void draw() {
System.out.println("Drawing a " + color + " rectangle");
}
@Override
public void setColor(String color) {
this.color = color;
}
@Override
public String getColor() {
return color;
}
@Override
public void resize(double factor) {
width *= factor;
height *= factor;
}
}
Abstract classes with abstract and concrete methods:
// Abstract class
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
// Abstract method (no implementation)
public abstract double area();
// Concrete method
public void printArea() {
System.out.println("Area: " + area());
}
}
// Concrete implementation
public class Square extends Shape {
private double side;
public Square(double side, String color) {
super(color);
this.side = side;
}
@Override
public double area() {
return side * side;
}
}
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height, String color) {
super(color);
this.base = base;
this.height = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
}
Generic classes, methods, and bounded type parameters:
// Generic class
public class Box {
private T value;
public void set(T value) {
this.value = value;
}
public T get() {
return value;
}
}
// Using generic class
public static void genericExample() {
Box stringBox = new Box<>();
stringBox.set("Hello");
String s = stringBox.get();
Box intBox = new Box<>();
intBox.set(42);
int i = intBox.get();
}
// Generic method
public static void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
// Bounded type parameters
public static > T max(T a, T b) {
return (a.compareTo(b) > 0) ? a : b;
}
// Generic interface
public interface Pair {
K getKey();
V getValue();
}
Simple and complex enum definitions:
// Simple enum
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// Enum with fields and methods
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6),
MARS(6.421e+23, 3.3972e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double getMass() {
return mass;
}
public double getRadius() {
return radius;
}
public double surfaceGravity() {
final double G = 6.67300E-11;
return G * mass / (radius * radius);
}
}
// Using enums
public static void enumExample() {
Day today = Day.MONDAY;
switch (today) {
case MONDAY:
System.out.println("Start of week");
break;
case FRIDAY:
System.out.println("Almost weekend!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekend!");
break;
default:
System.out.println("Midweek");
}
double earthGravity = Planet.EARTH.surfaceGravity();
}
Static members, constants, and final classes:
public class MathUtils {
// Static constant
public static final double PI = 3.14159;
// Static variable
private static int instanceCount = 0;
// Static method
public static int add(int a, int b) {
return a + b;
}
// Static initializer block
static {
System.out.println("MathUtils class loaded");
instanceCount = 0;
}
// Instance method
public MathUtils() {
instanceCount++;
}
public static int getInstanceCount() {
return instanceCount;
}
}
// Using static members
public static void staticExample() {
double circumference = 2 * MathUtils.PI * 5;
int sum = MathUtils.add(3, 4);
MathUtils m1 = new MathUtils();
MathUtils m2 = new MathUtils();
int count = MathUtils.getInstanceCount(); // 2
}
// Final class (cannot be extended)
public final class ImmutableClass {
private final String value;
public ImmutableClass(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
Functional interfaces, lambdas, and method references:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class LambdaExamples {
// Functional interface
@FunctionalInterface
interface Operation {
int apply(int a, int b);
}
public static void lambdaExample() {
// Lambda expression
Operation add = (a, b) -> a + b;
Operation multiply = (a, b) -> a * b;
System.out.println(add.apply(5, 3)); // 8
System.out.println(multiply.apply(5, 3)); // 15
// Using lambdas with collections
List names = Arrays.asList("Alice", "Bob", "Charlie");
// forEach with lambda
names.forEach(name -> System.out.println(name));
// Filter with lambda
names.stream()
.filter(name -> name.startsWith("A"))
.forEach(System.out::println);
// Map with lambda
names.stream()
.map(name -> name.toUpperCase())
.forEach(System.out::println);
// Reduce with lambda
List numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
}
// Method reference
public static void methodReferenceExample() {
List names = Arrays.asList("Alice", "Bob", "Charlie");
// Instance method reference
names.forEach(System.out::println);
// Static method reference
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Stream API for functional-style operations on collections:
import java.util.*;
import java.util.stream.*;
public class StreamExamples {
public static void streamExample() {
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filter even numbers
List evens = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// Map and collect
List squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
// Sum using reduce
int sum = numbers.stream()
.reduce(0, Integer::sum);
// Find first
Optional first = numbers.stream()
.filter(n -> n > 5)
.findFirst();
// Count
long count = numbers.stream()
.filter(n -> n % 2 == 0)
.count();
// Sorting
List sorted = Arrays.asList("Charlie", "Alice", "Bob")
.stream()
.sorted()
.collect(Collectors.toList());
// Distinct
List distinct = Arrays.asList(1, 2, 2, 3, 3, 3)
.stream()
.distinct()
.collect(Collectors.toList());
// Limit and skip
List limited = numbers.stream()
.skip(3)
.limit(4)
.collect(Collectors.toList());
}
}