Write once, run anywhere. Enterprise apps, Android, and 3 billion devices run Java.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("Name: " + args[0]);
}
}
// Compile: javac Hello.java
// Run: java Hello Mayank
int, double, char, boolean, String. Java is strict — every variable must have a type.
public class Vars {
public static void main(String[] args) {
int age = 15;
double pi = 3.14159;
char grade = 'A';
boolean passed = true;
String name = "Mayank";
System.out.println(name + " age=" + age);
System.out.println("pi=" + pi);
System.out.println("passed=" + passed);
// Type casting
int x = 10;
double y = x; // implicit
int z = (int) 3.14; // explicit
}
}
public class Ops {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println(a + "+" + b + "=" + (a+b));
System.out.println(a + "/" + b + "=" + (a/b));
System.out.println(a + "%" + b + "=" + (a%b));
// String concatenation
System.out.println("Score: " + 100);
// Ternary
int max = (a > b) ? a : b;
System.out.println("max=" + max);
}
}
import java.util.*;
public class Flow {
public static void main(String[] args) {
int score = 85;
if (score >= 90) System.out.println("A");
else if (score >= 80) System.out.println("B");
else System.out.println("C");
// Enhanced for
int[] nums = {10, 20, 30, 40, 50};
for (int n : nums) System.out.print(n + " ");
System.out.println();
// Switch
String day = "MONDAY";
switch (day) {
case "MONDAY": System.out.println("Start"); break;
case "FRIDAY": System.out.println("End"); break;
default: System.out.println("Other");
}
}
}
Arrays are fixed-size. ArrayList grows automatically. HashMap for key-value pairs.
import java.util.*;
public class Collections {
public static void main(String[] args) {
// Array
int[] arr = {5, 3, 1, 4, 2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
// ArrayList
List<String> list = new ArrayList<>();
list.add("Python"); list.add("Java"); list.add("Go");
list.remove(0);
System.out.println(list);
// HashMap
Map<String, Integer> ages = new HashMap<>();
ages.put("Mayank", 15); ages.put("Alice", 20);
System.out.println(ages.get("Mayank"));
// Iterating
for (var entry : ages.entrySet())
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
public class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public void bark() {
System.out.println(name + ": Woof!");
}
public String getName() { return name; }
public int getAge() { return age; }
@Override
public String toString() {
return "Dog{" + name + "," + age + "}";
}
public static void main(String[] args) {
Dog d = new Dog("Rex", 5);
d.bark();
System.out.println(d);
}
}
extends for IS-A, implements for CAN-DO. Java has single inheritance but multiple interfaces.
interface Animal { void speak(); }
interface Pet { void play(); }
class AnimalBase {
String name;
AnimalBase(String n) { name = n; }
}
class Cat extends AnimalBase implements Animal, Pet {
Cat(String n) { super(n); }
public void speak() { System.out.println(name + ": Meow!"); }
public void play() { System.out.println(name + " plays with yarn"); }
}
public class Main {
public static void main(String[] args) {
Cat c = new Cat("Whiskers");
c.speak(); c.play();
}
}
public class Box<T> {
private T value;
public Box(T v) { value = v; }
public T get() { return value; }
public void set(T v) { value = v; }
@Override public String toString() { return "Box{" + value + "}"; }
}
public class Main {
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
public static void main(String[] args) {
Box<Integer> bi = new Box<>(42);
Box<String> bs = new Box<>("Hello");
System.out.println(bi + " " + bs);
System.out.println(max(3, 7));
System.out.println(max("abc", "xyz"));
}
}
try/catch/finally. Checked exceptions must be caught. Unchecked are RuntimeExceptions.
public class Exceptions {
static int divide(int a, int b) throws ArithmeticException {
if (b == 0) throw new ArithmeticException("/ by zero");
return a / b;
}
public static void main(String[] args) {
try {
System.out.println(divide(10, 3));
System.out.println(divide(10, 0));
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Always runs");
}
// Try-with-resources
try (var r = new java.io.BufferedReader(
new java.io.FileReader("test.txt"))) {
System.out.println(r.readLine());
} catch (Exception e) {
System.out.println("File error: " + e.getMessage());
}
}
}
Process collections functionally. filter, map, reduce, collect — chain operations together.
import java.util.*;
import java.util.stream.*;
public class Streams {
public static void main(String[] args) {
List<Integer> nums = List.of(1,2,3,4,5,6,7,8,9,10);
// Filter even, double them, sum
int result = nums.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * 2)
.sum();
System.out.println("Sum of doubled evens: " + result);
// Collect to list
List<String> names = List.of("Alice","Bob","Charlie","Dave");
List<String> shortNames = names.stream()
.filter(n -> n.length() <= 3)
.collect(Collectors.toList());
System.out.println(shortNames);
// Grouping
Map<Boolean, List<Integer>> grouped = nums.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("Evens: " + grouped.get(true));
System.out.println("Odds: " + grouped.get(false));
// Reduce
int product = nums.stream().reduce(1, (a,b) -> a*b);
System.out.println("Product: " + product);
}
}
Anonymous functions. @FunctionalInterface marks single-method interfaces for lambda use.
@FunctionalInterface
interface MathOp { int apply(int a, int b); }
@FunctionalInterface
interface Predicate<T> { boolean test(T t); }
public class Lambdas {
static int operate(int a, int b, MathOp op) { return op.apply(a, b); }
public static void main(String[] args) {
MathOp add = (a, b) -> a + b;
MathOp mul = (a, b) -> a * b;
System.out.println(operate(3, 4, add));
System.out.println(operate(3, 4, mul));
Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("Hello"));
System.out.println(isLong.test("Hello World"));
// Method reference
List<String> names = List.of("alice","bob","charlie");
names.stream().map(String::toUpperCase).forEach(System.out::println);
}
}
import java.nio.file.*;
import java.io.*;
import java.util.*;
public class FileIO {
public static void main(String[] args) throws Exception {
// Write
Files.writeString(Path.of("test.txt"), "Hello Java!\nLine 2\n");
// Read all lines
List<String> lines = Files.readAllLines(Path.of("test.txt"));
lines.forEach(System.out::println);
// Read entire file
String content = Files.readString(Path.of("test.txt"));
System.out.println(content);
// Stream lines (memory efficient)
Files.lines(Path.of("test.txt")).forEach(System.out::println);
// Directory listing
Files.list(Path.of(".")).forEach(p -> System.out.println(p.getFileName()));
}
}
Java 16+ records for immutable data. Sealed classes restrict who can extend.
// Record — auto-generates constructor, getters, equals, hashCode, toString
public record Point(int x, int y) {
public Point { if (x < 0 || y < 0) throw new IllegalArgumentException(); }
public double distanceTo(Point other) {
return Math.sqrt(Math.pow(x-other.x, 2) + Math.pow(y-other.y, 2));
}
}
// Sealed class (Java 17+)
sealed interface Shape permits Circle, Rect {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
public class Main {
public static void main(String[] args) {
var p1 = new Point(3, 4);
var p2 = new Point(0, 0);
System.out.println(p1);
System.out.println("dist=" + p1.distanceTo(p2));
Shape s = new Circle(5);
String desc = switch (s) {
case Circle c -> "Circle r=" + c.r();
case Rect r -> "Rect " + r.w() + "x" + r.h();
};
System.out.println(desc);
}
}
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Concurrency {
static AtomicInteger counter = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
// Thread basics
Thread t = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.incrementAndGet();
});
t.start(); t.join();
System.out.println("counter: " + counter.get());
// ExecutorService
var pool = Executors.newFixedThreadPool(4);
var futures = new java.util.ArrayList<Future<Integer>>();
for (int i = 0; i < 10; i++) {
int n = i;
futures.add(pool.submit(() -> n * n));
}
for (var f : futures) System.out.print(f.get() + " ");
System.out.println();
pool.shutdown();
// CompletableFuture
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);
}
}
Metadata for code. @Override, @Deprecated, custom annotations. Reflection inspects classes at runtime.
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Log { String value() default ""; }
class Service {
@Log("Starting service")
public void start() { System.out.println("Service started"); }
public void stop() { System.out.println("Service stopped"); }
}
public class Main {
public static void main(String[] args) throws Exception {
// Reflection
Class<?> cls = Service.class;
System.out.println("Methods in " + cls.getName() + ":");
for (Method m : cls.getDeclaredMethods()) {
System.out.println(" " + m.getName());
if (m.isAnnotationPresent(Log.class)) {
Log log = m.getAnnotation(Log.class);
System.out.println(" -> @Log: " + log.value());
}
}
// Dynamic instantiation
Object svc = cls.getDeclaredConstructor().newInstance();
Method start = cls.getMethod("start");
start.invoke(svc);
}
}
Java 17+ pattern matching for switch, text blocks for multi-line strings, switch expressions.
public class ModernJava {
static String format(Object obj) {
return switch (obj) {
case Integer i when i > 0 -> "Positive int: " + i;
case Integer i -> "Non-positive int: " + i;
case String s -> "String: " + s;
case null -> "null";
default -> obj.getClass().getSimpleName();
};
}
public static void main(String[] args) {
System.out.println(format(42));
System.out.println(format(-1));
System.out.println(format("hello"));
System.out.println(format(null));
// Text blocks
String json = """
{
"name": "Mayank",
"age": 15,
"langs": ["Java", "Python", "Go"]
}
""";
System.out.println(json);
// Switch expression with yield
int day = 3;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Unknown";
};
System.out.println(type);
}
}
Java 21+ lightweight threads. Millions of concurrent tasks without the overhead.
import java.util.concurrent.*;
import java.time.*;
public class VirtualThreads {
public static void main(String[] args) throws Exception {
// Platform thread
long start = System.nanoTime();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
var futures = new java.util.ArrayList<Future<String>>();
for (int i = 0; i < 100_000; i++) {
int id = i;
futures.add(executor.submit(() -> {
Thread.sleep(Duration.ofMillis(10));
return "task-" + id;
}));
}
// All done in ~10ms, not 1000s of seconds!
System.out.println("Completed " + futures.size() + " tasks");
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("Time: " + ms + "ms");
// Structured concurrency (Preview)
// try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
// var user = scope.fork(() -> fetchUser());
// var order = scope.fork(() -> fetchOrder());
// scope.join();
// return new Result(user.get(), order.get());
// }
}
}