Strongly-typed and object-oriented from the ground up - the language behind AP Computer Science A, Android, and huge chunks of enterprise software. Copy-paste examples plus live Run/Submit exercises.
Every Java file's public class name must match the filename - this one is Main.java.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
javac Main.java, then run with java Main - Java compiles to bytecode, run by the Java Virtual Machine (JVM), not directly by your OS.main's String[] args parameter holds whatever gets typed after the program name when you launch it - java Main hello world gives args = {"hello", "world"}.
public class Main {
public static void main(String[] args) {
System.out.println("Hello " + args[0]);
}
}
// running "java Main World" prints "Hello World"
args[0] when no argument was actually passed throws ArrayIndexOutOfBoundsException - this is a runtime error, not something the compiler can catch for you.int age = 25;
double price = 9.99;
char grade = 'A';
boolean isValid = true;
String name = "Sam"; // capital S - String is a class, not a primitive
int, double, char, boolean) hold their value directly - think "cash in your pocket." Objects like String hold a reference to where the data lives - think "an IOU pointing at the real thing."int x = 10, y = 3;
System.out.println(x / y); // 3 - integer division truncates!
System.out.println(x / 2.0); // 5.0 - use a double literal to keep the decimal
System.out.println(x % y); // 1 - remainder
x += 5; // x = x + 5
x++; // increment
x--; // decrement
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
sc.nextLine(); // flush the leftover newline before the next nextLine() call
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println(name + " is " + age);
nextInt()/nextDouble() read the number but leave the trailing newline in the input buffer - the very next nextLine() call then reads that leftover empty line instead of waiting for real input. Throw in an extra sc.nextLine(); right after any nextInt()/nextDouble() to clear it.System.out.printf("%s is %d\n", "Sam", 25); // %s string, %d int, %f float/double, %c char, %b boolean
System.out.printf("%.2f\n", 3.14159); // 3.14 - precision
System.out.printf("%04d\n", 7); // 0007 - zero-padded width
System.out.printf("%-6d|\n", 7); // "7 |" - left-justify
// String.format uses the SAME %-codes, but RETURNS a string instead of printing it
String greeting = String.format("Hello, %s!", "Caleb");
System.out.println(greeting);
println, printf does not add a newline automatically - include \n yourself. Reach for String.format when you need the formatted text as a value (to store, pass around, or concatenate) rather than print it immediately.System.out.println(Math.PI); // 3.141592653589793
System.out.println(Math.pow(2, 10)); // 1024.0
System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.abs(-5)); // 5
System.out.println(Math.max(3, 9)); // 9
System.out.println(Math.round(4.6)); // 5
import java.util.Random;
Random random = new Random();
int roll = random.nextInt(6) + 1; // nextInt(6) gives 0-5, so +1 for a 1-6 die
double d = random.nextDouble();
boolean b = random.nextBoolean();
nextInt(bound)'s upper bound is exclusive - nextInt(6) can never actually return 6.int age = 20;
if (age >= 18) {
System.out.println("Adult");
} else if (age >= 13) {
System.out.println("Teen");
} else {
System.out.println("Child");
}
Java 14+'s enhanced switch (arrow syntax) is the modern go-to over a long if/else-if chain - no break needed, and it can return a value directly.
int day = 3;
String name = switch (day) {
case 1, 7 -> "Weekend"; // comma-separated multi-value case
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Invalid";
};
System.out.println(name);
int temp = 22;
if (temp > 0 && temp < 30) { // AND - both must be true
System.out.println("Comfortable");
}
boolean isWeekend = false;
if (isWeekend || temp > 28) { // OR - at least one true
System.out.println("Relax");
}
if (!isWeekend) { // NOT - flips it
System.out.println("Back to work");
}
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
int n = 3;
while (n > 0) {
System.out.println(n);
n--;
}
int choice;
Scanner sc = new Scanner(System.in);
do { // runs the body at least ONCE, checks the condition after
System.out.print("Enter 1-3: ");
choice = sc.nextInt();
} while (choice < 1 || choice > 3);
for (int i = 0; i < 10; i++) {
if (i == 5) break; // stop button - exits the loop entirely
if (i % 2 == 0) continue; // skip button - skips just this iteration
System.out.println(i); // prints 1, 3
}
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
int[] nums = {10, 20, 30};
System.out.println(nums[0]); // 10
System.out.println(nums.length); // 3 - length is a field, not a method
for (int n : nums) { // enhanced for loop
System.out.println(n);
}
import java.util.Arrays;
Arrays.sort(nums); // sorts in place (Arrays.parallelSort for very large arrays)
System.out.println(Arrays.toString(nums));
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false - different array objects
System.out.println(a.equals(b)); // false - array .equals() is STILL identity-based!
System.out.println(Arrays.equals(a, b)); // true - this is the one that compares CONTENTS
int[] filled = new int[5];
Arrays.fill(filled, 7); // {7, 7, 7, 7, 7}
0..length-1 throws ArrayIndexOutOfBoundsException - unlike C, Java always checks bounds for you (at a small runtime cost). And arrays never override .equals(), so it silently falls back to identity comparison - always use Arrays.equals() (or Arrays.deepEquals() for a 2D array) to compare contents.String[] names = {"Ada", "Linus", "Grace"};
String target = "Linus";
boolean found = false;
for (String n : names) {
if (n.equals(target)) { found = true; break; }
}
System.out.println(found);
String with == checks identity, not content - always use .equals() when searching for a matching value.A resizable array - the everyday alternative to fixed-size arrays. Elements must be objects (wrapper classes for primitives), hence the diamond <>.
import java.util.ArrayList;
import java.util.Collections;
ArrayList<String> names = new ArrayList<>();
names.add("Ada");
names.add("Linus");
names.set(0, "Grace"); // replace at index
System.out.println(names.get(0)); // Grace
System.out.println(names.size()); // 2
names.remove("Linus");
Collections.sort(names);
Collections.reverse(names); // flips the current order in place
import java.util.Arrays;
import java.util.List;
List<String> fixed = Arrays.asList("Ada", "Linus"); // quick array-to-List, one line
List is the interface - the "steering wheel." ArrayList and LinkedList are two different "engines" underneath it, both usable through the exact same List methods.
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
List<Integer> grades = new ArrayList<>(); // fast random access by index
List<Integer> queue = new LinkedList<>(); // fast insert/remove at the ends
grades.add(90);
queue.add(1);
// both are used identically through the List interface - .add/.get/.size all work the same
List interface (rather than declaring a variable as ArrayList directly) means you can swap the underlying implementation later without touching any of the code that uses it.String name = " Mo Salah ";
System.out.println(name.length()); // includes the spaces
System.out.println(name.trim()); // "Mo Salah" - strips leading/trailing whitespace
System.out.println(name.toUpperCase()); // " MO SALAH "
System.out.println(name.trim().substring(0, 2)); // "Mo"
System.out.println(name.contains("Salah")); // true
System.out.println(name.indexOf("Salah")); // index where it starts
System.out.println(name.replace("Mo", "M."));
System.out.println(name.trim().equalsIgnoreCase("mo salah")); // true
String a = "hi", b = "hi";
System.out.println(a == b); // true - identical literals share ONE cached object ("interning")
String c = new String("hi");
System.out.println(a == c); // false - c was built fresh, a separate object in memory
== compares object identity in Java, not content. Always use .equals() (or .equalsIgnoreCase()) to compare String values - == can *look* like it works for simple literals (Java caches/"interns" identical literals to the same object), but that's a coincidence of the cache, not a content comparison, and it breaks the moment a string is built with new String(...) or produced at runtime.public static int add(int a, int b) {
return a + b;
}
Java is always pass-by-value - but for an object parameter, the "value" being copied is the reference itself, not the object. So the copy still points at the exact same object, and mutating its fields through that copy is visible to the caller.
static void changeInt(int x) {
x++; // only the LOCAL copy changes
}
static void changeName(StringBuilder name) {
name.append("!"); // mutates the SAME object the caller has
}
public static void main(String[] args) {
int n = 5;
changeInt(n);
System.out.println(n); // 5 - untouched
StringBuilder sb = new StringBuilder("Hi");
changeName(sb);
System.out.println(sb); // "Hi!" - the caller's object WAS changed
}
An ellipsis (...) lets a method accept any number of arguments, packed into an array automatically - avoids writing separate overloads for 2, 3, 4โฆ arguments.
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
// sum(1, 2), sum(1, 2, 3, 4) - both work with the same method
Two methods can share a name as long as their parameter lists differ - the combination of name + parameter types is called the method's signature, and signatures must be unique.
public static int add(int a, int b) { return a + b; }
public static double add(double a, double b) { return a + b; }
// Java picks the right one based on the argument types you pass
public class Example {
int value = 10; // class-level (instance) scope - visible to every method in this class
public void show() {
int value = 99; // LOCAL - shadows the class-level "value" inside this method only
System.out.println(value); // 99
}
}
static members belong to the class itself, shared by every instance, rather than to any one object.
public class Friend {
static int numOfFriends = 0; // ONE shared counter for every Friend object
String name;
Friend(String name) {
this.name = name;
numOfFriends++;
}
}
// new Friend("Ada"); new Friend("Linus");
// Friend.numOfFriends is now 2 - access static members via the CLASS name
static and private methods are the exception: they belong to the class (or are invisible outside it), so they can't be overridden.final means "can't be changed again," applied to three different things.
final int Y = 5;
Y = 10; // compile error: Y cannot be assigned a new value
public class User {
public final void sayHello() { /* ... */ } // a subclass CANNOT override this method
}
public final class Teacher extends User { } // no class can extend Teacher at all
final variable is C's/most languages' idea of a constant - convention names them in ALL_CAPS, often as public static final class-level fields (e.g. public static final double PI = 3.14159;).public class Dog {
String name;
int age;
Dog(String n, int a) { // constructor
name = n;
age = a;
}
public void bark() {
System.out.println(name + " says woof!");
}
}
// Dog d = new Dog("Rex", 3); d.bark();
this refers to "the object currently being built/used" - needed when a parameter name shadows a field. A class can also have several constructors with different parameter lists.
public class Student {
String name;
int age;
Student(String name) { // only a name given - default the age
this.name = name; // this.name = the FIELD, name = the PARAMETER
this.age = 18;
}
Student(String name, int age) { // overloaded constructor - both given
this.name = name;
this.age = age;
}
}
public class Animal {
String name;
Animal(String name) { this.name = name; }
public void eat() { System.out.println(name + " is eating..."); }
}
public class Cat extends Animal { // Cat inherits everything from Animal
Cat(String name) {
super(name); // must call the parent's constructor first
}
public void meow() { System.out.println("Meow!"); }
}
// Cat c = new Cat("Whiskers"); c.eat(); c.meow(); -- both work
A subclass can replace ("override") an inherited method with its own version. @Override tells the compiler to double-check the signature actually matches - it catches typos that would otherwise silently create a brand-new method instead of overriding.
public class Animal {
public void speak() { System.out.println("..."); }
}
public class Dog extends Animal {
@Override
public void speak() { System.out.println("Woof!"); } // overrides the parent version
@Override
public String toString() { // every object inherits a default (unhelpful) toString()
return "Dog object"; // print/println/printf all call this automatically
}
}
An abstract class can't be instantiated directly - it exists to be extended. It can mix abstract methods (no body; subclasses must implement them) with regular, fully-implemented methods that subclasses just inherit.
public abstract class Shape {
public abstract double area(); // no body - every subclass MUST implement this
public void describe() { // concrete - inherited as-is
System.out.println("Area: " + area());
}
}
public class Circle extends Shape {
double radius;
Circle(double r) { radius = r; }
public double area() { return Math.PI * radius * radius; }
}
An object can be treated as its supertype, and Java decides at runtime which overridden method actually runs, based on the object's real type - not the variable's declared type.
Shape[] shapes = { new Circle(2), new Circle(5) };
for (Shape s : shapes) {
s.describe(); // each call runs the correct subclass's area() automatically
}
An interface defines a contract - any class that implements it must provide those methods. A class can implement multiple interfaces (unlike single-parent-only inheritance).
public interface Prey {
void flee();
}
public interface Predator {
void hunt();
}
public class Fox implements Prey, Predator { // implements BOTH
public void flee() { System.out.println("Fox runs away"); }
public void hunt() { System.out.println("Fox hunts a rabbit"); }
}
Keep fields private and expose controlled access through getters/setters - this lets a setter validate input, and a missing setter makes a field effectively read-only from outside the class.
public class Product {
private double price;
public double getPrice() { return price; }
public void setPrice(double p) {
if (p >= 0) price = p; // validation lives right here, in one place
}
}
// a field with a getter but NO setter - the only way to set it is through the constructor,
// so once the object exists, that value can never change again
public class Point {
private final int x;
Point(int x) { this.x = x; }
public int getX() { return x; }
}
Aggregation ("has-a"): a Library has Book objects, but those books can exist independently of the library. Composition ("part-of," tighter): a Car is composed of an Engine - conceptually, the engine only makes sense as part of that specific car.
public class Engine { int horsepower; }
public class Car {
private final Engine engine = new Engine(); // composition: Car OWNS its Engine
}
public class Library {
ArrayList<Book> books; // aggregation: books can outlive the Library
}
Every primitive has an object "wrapper" (intโInteger, doubleโDouble, charโCharacter, booleanโBoolean) - needed anywhere Java requires an object, like collections. Modern Java converts back and forth automatically ("autoboxing").
Integer a = 123; // autoboxed from int automatically
int b = a; // auto-unboxed back to a primitive
System.out.println(Integer.parseInt("42") + 8); // 50 - parseInt returns a primitive int
Integer boxed = Integer.valueOf("42"); // valueOf returns an Integer OBJECT instead
System.out.println(Character.isLetter('A')); // true
System.out.println(Integer.MAX_VALUE); // 2147483647 - largest int
System.out.println(Integer.MIN_VALUE); // -2147483648
System.out.println(Integer.compare(3, 9)); // negative - first three-way compare
System.out.println(Double.isNaN(Math.sqrt(-1))); // true - sqrt of a negative isn't a real number
System.out.println(Math.pow(99999, 99999)); // Infinity - silently overflows, doesn't crash
Double.POSITIVE_INFINITY/NEGATIVE_INFINITY or NaN ("not a number"). Check for these explicitly with Double.isNaN()/isInfinite()/isFinite() rather than assuming a normal number came back.double/float are floating-point and lose tiny amounts of precision - fine for most math, risky for money. BigDecimal is fixed-point and exact.
import java.math.BigDecimal;
BigDecimal price = new BigDecimal("19.99"); // build from a STRING, not a double literal
BigDecimal tax = new BigDecimal("1.72");
System.out.println(price.add(tax)); // exact: 21.71, no floating-point drift
try/catch/finally handles runtime errors instead of crashing. Catch the most specific exception types first, and a generic Exception last, as a safety net.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero");
} catch (Exception e) {
System.out.println("Something else went wrong");
} finally {
System.out.println("This always runs");
}
import java.io.FileWriter;
import java.io.IOException;
try (FileWriter writer = new FileWriter("notes.txt")) {
writer.write("Score: 95");
} catch (IOException e) {
System.out.println("Couldn't write the file");
}
import java.io.BufferedReader;
import java.io.FileReader;
try (BufferedReader reader = new BufferedReader(new FileReader("notes.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Couldn't read the file");
}
try (...) "try-with-resources" form automatically closes the writer/reader for you, even if an exception is thrown.import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
LocalDate today = LocalDate.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/yyyy");
System.out.println(today.format(fmt));
LocalDate birthday = LocalDate.of(2010, 6, 15);
System.out.println(birthday.isBefore(today));
A generic class works with a placeholder type (<T>) decided when it's actually used - this is exactly how ArrayList<E> itself is built.
public class Box<T> {
private T content;
public void set(T content) { this.content = content; }
public T get() { return content; }
}
Box<String> box = new Box<>();
box.set("hello");
System.out.println(box.get());
Key-value pairs - keys are unique (adding a duplicate key overwrites the old value), values can repeat.
import java.util.HashMap;
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Ada", 28);
ages.put("Linus", 34);
System.out.println(ages.get("Ada")); // 28
System.out.println(ages.containsKey("Linus")); // true
for (String key : ages.keySet()) {
System.out.println(key + ": " + ages.get(key));
}
A fixed set of named constants - clearer and safer than comparing raw strings/numbers. Enum constants can even carry their own fields and constructor.
public enum Day {
SUNDAY(1), MONDAY(2), TUESDAY(3); // each constant gets its own constructor call
private final int number;
Day(int number) { this.number = number; }
public int getNumber() { return number; }
}
Day today = Day.MONDAY;
System.out.println(today.getNumber()); // 2
A one-off, nameless class definition - handy when you need a single custom object and don't want to declare a whole named subclass just for it.
abstract class Greeting {
abstract void say();
}
Greeting g = new Greeting() { // defines AND instantiates a one-time subclass, right here
void say() { System.out.println("Hi there!"); }
};
g.say();
import java.util.Timer;
import java.util.TimerTask;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("Time's up!");
timer.cancel(); // stop future scheduling
}
}, 3000); // delay in milliseconds
Implementing Runnable (preferred over extending Thread, since Java only allows single inheritance) lets a task run concurrently. .join() makes the main thread wait for a worker thread to finish.
public class Countdown implements Runnable {
public void run() {
try {
for (int i = 3; i > 0; i--) {
System.out.println(i);
Thread.sleep(1000);
}
} catch (InterruptedException e) { }
}
}
Thread t = new Thread(new Countdown());
t.start();
t.join(); // main thread waits here until t finishes
Full runnable programs, compiled and run in a real Java sandbox - same workspace as the other cheat sheets.
public class Main {
public static void main(String[] args) {
int[] nums = {4, 8, 15, 16, 23, 42};
int sum = 0;
for (int n : nums) sum += n;
System.out.println(sum);
}
}
public class Main {
public static void main(String[] args) {
String s = "pointers";
String reversed = new StringBuilder(s).reverse().toString();
System.out.println(reversed);
}
}
public class Main {
public static void main(String[] args) {
double kg = 10;
System.out.printf("%.2f kg = %.2f lb\n", kg, kg * 2.2046);
}
}
public class Main {
public static void main(String[] args) {
double celsius = 100;
double f = celsius * 9 / 5 + 32;
String note = (f > 212) ? "boiling+" : "normal";
System.out.printf("%.1fF (%s)\n", f, note);
}
}
public class Main {
static class Friend {
static int count = 0;
Friend() { count++; }
}
public static void main(String[] args) {
new Friend(); new Friend(); new Friend();
System.out.println(Friend.count); // 3 - shared across every instance
}
}
public class Main {
enum Day { MONDAY, SATURDAY, SUNDAY }
public static void main(String[] args) {
Day today = Day.SATURDAY;
String type = switch (today) {
case SATURDAY, SUNDAY -> "Weekend";
default -> "Weekday";
};
System.out.println(type);
}
}
public class Main {
static class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
int getX() { return x; }
int getY() { return y; }
}
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p.getX() + ", " + p.getY()); // 3, 4 - no setter exists, so this can never change
}
}
public class Main {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
int[] numbers = {2, 15, 17, 21, 29, 1};
for (int n : numbers) {
System.out.println(n + " is prime: " + isPrime(n));
}
}
}
public class Main {
static boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) return false;
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String[] words = {"level", "hello", "racecar", "java"};
for (String w : words) {
System.out.println(w + " -> " + isPalindrome(w));
}
}
}
public class Main {
static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
int a = 48;
int b = 18;
int g = gcd(a, b);
int l = (a * b) / g;
System.out.println("GCD of " + a + " and " + b + " is " + g);
System.out.println("LCM of " + a + " and " + b + " is " + l);
}
}
public class Main {
public static void main(String[] args) {
String text = "Hello World from Java";
int vowels = 0;
int consonants = 0;
String lower = text.toLowerCase();
for (int i = 0; i < lower.length(); i++) {
char c = lower.charAt(i);
if (c >= 'a' && c <= 'z') {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
public class Main {
static int digitSum(int n) {
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
static int reverseNumber(int n) {
int reversed = 0;
while (n != 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
public static void main(String[] args) {
int number = 4827;
System.out.println("Digit sum of " + number + " is " + digitSum(number));
System.out.println("Reversed " + number + " is " + reverseNumber(number));
}
}
public class Main {
static boolean isLeapYear(int year) {
if (year % 4 != 0) return false;
if (year % 100 != 0) return true;
return year % 400 == 0;
}
public static void main(String[] args) {
int[] years = {2000, 1900, 2024, 2023};
for (int year : years) {
System.out.println(year + " is a leap year: " + isLeapYear(year));
}
}
}
public class Main {
static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i;
}
return -1;
}
public static void main(String[] args) {
int[] numbers = {8, 3, 19, 5, 12, 7};
int target = 12;
int index = linearSearch(numbers, target);
if (index != -1) {
System.out.println("Found " + target + " at index " + index);
} else {
System.out.println(target + " not found");
}
}
}
public class Main {
static double average(int... values) {
int total = 0;
for (int v : values) {
total += v;
}
return (double) total / values.length;
}
static int max(int... values) {
int best = values[0];
for (int v : values) {
if (v > best) best = v;
}
return best;
}
static int min(int... values) {
int best = values[0];
for (int v : values) {
if (v < best) best = v;
}
return best;
}
public static void main(String[] args) {
System.out.println("Average: " + average(4, 8, 15, 16, 23, 42));
System.out.println("Max: " + max(4, 8, 15, 16, 23, 42));
System.out.println("Min: " + min(4, 8, 15, 16, 23, 42));
}
}
public class Main {
public static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
System.out.println(fib(10));
}
}
public class Main {
static class Rectangle {
double width, height;
Rectangle(double w, double h) { width = w; height = h; }
double area() { return width * height; }
}
public static void main(String[] args) {
Rectangle r = new Rectangle(4, 5);
System.out.println(r.area());
}
}
public class Main {
public static void main(String[] args) {
double principal = 1000, rate = 0.05, years = 10;
int n = 12;
double amount = principal * Math.pow(1 + rate / n, n * years);
System.out.printf("$%.2f\n", amount);
}
}
public class Main {
public static void main(String[] args) {
double a = 9, b = 0;
char op = '/';
String result = switch (op) {
case '+' -> String.valueOf(a + b);
case '-' -> String.valueOf(a - b);
case '*' -> String.valueOf(a * b);
case '/' -> (b == 0) ? "Cannot divide by zero" : String.valueOf(a / b);
default -> "Invalid operator";
};
System.out.println(result);
}
}
public class Main {
public static void main(String[] args) {
int secret = 42;
int[] guesses = {10, 60, 42}; // simulated, since this exercise has fixed output
int tries = 0;
for (int g : guesses) {
tries++;
if (g < secret) System.out.println("Too low!");
else if (g > secret) System.out.println("Too high!");
else { System.out.println("Got it in " + tries + " tries!"); break; }
}
}
}
public class Main {
static double deposit(double amount) {
return (amount < 0) ? 0 : amount;
}
static double withdraw(double balance, double amount) {
return (amount > balance) ? 0 : amount;
}
public static void main(String[] args) {
double balance = 100;
balance += deposit(50);
balance -= withdraw(balance, 30);
System.out.printf("Balance: $%.2f\n", balance);
}
}
public class Main {
static class Box<T> {
private T content;
void set(T c) { content = c; }
T get() { return content; }
}
public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.set(42);
Box<String> strBox = new Box<>();
strBox.set("hello");
System.out.println(intBox.get());
System.out.println(strBox.get());
}
}
public class Main {
static double safeDivide(double a, double b) {
try {
if (b == 0) throw new ArithmeticException("divide by zero");
return a / b;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
return 0;
}
}
public static void main(String[] args) {
System.out.println(safeDivide(10, 2));
System.out.println(safeDivide(10, 0));
}
}
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal itemPrice = new BigDecimal("19.99");
BigDecimal quantity = new BigDecimal("3");
System.out.println(itemPrice.multiply(quantity)); // 59.97 - exact, no floating-point drift
}
}
public class Main {
static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] numbers = {64, 25, 12, 22, 11, 90, 5};
bubbleSort(numbers);
System.out.print("Sorted:");
for (int n : numbers) {
System.out.print(" " + n);
}
System.out.println();
}
}
public class Main {
static int binarySearch(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] sorted = {2, 5, 8, 12, 16, 23, 38, 45, 56, 72};
int target = 23;
int result = binarySearch(sorted, target);
System.out.println("Index of " + target + ": " + result);
System.out.println("Index of 99: " + binarySearch(sorted, 99));
}
}
public class Main {
static int[] rotateLeft(int[] arr, int k) {
int n = arr.length;
k = k % n;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = arr[(i + k) % n];
}
return result;
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7};
int[] rotated = rotateLeft(numbers, 3);
System.out.print("Rotated:");
for (int n : rotated) {
System.out.print(" " + n);
}
System.out.println();
}
}
public class Main {
static boolean isArmstrong(int n) {
int original = n;
int digits = String.valueOf(n).length();
int sum = 0;
while (n != 0) {
int digit = n % 10;
int power = 1;
for (int i = 0; i < digits; i++) {
power *= digit;
}
sum += power;
n /= 10;
}
return sum == original;
}
public static void main(String[] args) {
int[] numbers = {153, 9474, 123, 370};
for (int n : numbers) {
System.out.println(n + " is an Armstrong number: " + isArmstrong(n));
}
}
}
import java.util.Arrays;
public class Main {
static boolean isAnagram(String a, String b) {
char[] first = a.toLowerCase().replace(" ", "").toCharArray();
char[] second = b.toLowerCase().replace(" ", "").toCharArray();
if (first.length != second.length) return false;
Arrays.sort(first);
Arrays.sort(second);
return Arrays.equals(first, second);
}
public static void main(String[] args) {
System.out.println(isAnagram("listen", "silent"));
System.out.println(isAnagram("Dormitory", "Dirty Room"));
System.out.println(isAnagram("hello", "world"));
}
}
public class Main {
static void describe(int n) {
System.out.println("An int: " + n);
}
static void describe(String s) {
System.out.println("A String: " + s);
}
static void describe(int n, String unit) {
System.out.println(n + " " + unit);
}
public static void main(String[] args) {
describe(42);
describe("hello");
describe(5, "apples");
}
}
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String text = "the cat sat on the mat the cat ran";
HashMap<String, Integer> counts = new HashMap<>();
for (String word : text.split(" ")) {
counts.put(word, counts.getOrDefault(word, 0) + 1);
}
for (String key : counts.keySet()) {
System.out.println(key + ": " + counts.get(key));
}
}
}
public class Main {
public static void main(String[] args) {
String[] questions = {
"What color is the sky?",
"How many days in a week?"
};
char[] answerKey = {'A', 'B'};
char[] guesses = {'a', 'b'}; // simulated, lowercase on purpose
int score = 0;
for (int i = 0; i < questions.length; i++) {
System.out.println(questions[i]);
char guess = Character.toUpperCase(guesses[i]);
if (guess == answerKey[i]) score++;
}
System.out.println("Score: " + score + "/" + questions.length);
}
}
public class Main {
static abstract class Shape {
abstract double area();
}
static class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
static class Square extends Shape {
double side;
Square(double side) { this.side = side; }
double area() { return side * side; }
}
public static void main(String[] args) {
Shape[] shapes = { new Circle(3), new Square(4) };
for (Shape s : shapes) {
System.out.printf("%.2f\n", s.area()); // each call resolves to the right subclass at runtime
}
}
}
Prints six rows of Pascal's triangle by tracking each binomial coefficient incrementally instead of using factorials.
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 0; i < rows; i++) {
int value = 1;
for (int j = 0; j <= i; j++) {
System.out.print(value + " ");
value = value * (i - j) / (j + 1);
}
System.out.println();
}
}
}
A perfect number equals the sum of its proper divisors (e.g. 6 = 1 + 2 + 3).
public class Main {
static boolean isPerfect(int n) {
if (n <= 1) return false;
int sum = 1;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
sum += i;
int pair = n / i;
if (pair != i) sum += pair;
}
}
return sum == n;
}
public static void main(String[] args) {
int[] numbers = {6, 28, 12, 496, 33};
for (int n : numbers) {
System.out.println(n + " is perfect: " + isPerfect(n));
}
}
}
Validates the triangle inequality first, then classifies as equilateral, isosceles, or scalene.
public class Main {
static String classify(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) {
return "Not a valid triangle";
}
if (a == b && b == c) {
return "Equilateral";
} else if (a == b || b == c || a == c) {
return "Isosceles";
} else {
return "Scalene";
}
}
public static void main(String[] args) {
System.out.println(classify(3, 3, 3));
System.out.println(classify(5, 5, 8));
System.out.println(classify(4, 5, 6));
System.out.println(classify(1, 2, 10));
}
}
A fixed-capacity stack built from a plain int[] and a top index - no java.util.Stack involved.
public class Main {
static class IntStack {
private int[] data;
private int top;
IntStack(int capacity) {
data = new int[capacity];
top = -1;
}
void push(int value) {
if (top == data.length - 1) {
System.out.println("Stack overflow, cannot push " + value);
return;
}
top++;
data[top] = value;
}
int pop() {
if (top == -1) {
System.out.println("Stack is empty");
return -1;
}
int value = data[top];
top--;
return value;
}
boolean isEmpty() {
return top == -1;
}
}
public static void main(String[] args) {
IntStack stack = new IntStack(5);
stack.push(10);
stack.push(20);
stack.push(30);
while (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
}
System.out.println("Popped from empty: " + stack.pop());
}
}
An ArrayList<Student> gradebook where each Student computes its own average from an array of scores.
import java.util.ArrayList;
public class Main {
static class Student {
private String name;
private int[] scores;
Student(String name, int[] scores) {
this.name = name;
this.scores = scores;
}
double average() {
int total = 0;
for (int s : scores) {
total += s;
}
return (double) total / scores.length;
}
String getName() {
return name;
}
}
public static void main(String[] args) {
ArrayList<Student> gradebook = new ArrayList<>();
gradebook.add(new Student("Alice", new int[]{90, 85, 92}));
gradebook.add(new Student("Bob", new int[]{70, 75, 68}));
gradebook.add(new Student("Carla", new int[]{88, 91, 95}));
for (Student s : gradebook) {
System.out.printf("%s: %.2f%n", s.getName(), s.average());
}
}
}
An abstract Employee base class with two subclasses that each override calculateSalary() differently - resolved polymorphically at runtime.
public class Main {
static abstract class Employee {
protected String name;
protected double baseSalary;
Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
}
abstract double calculateSalary();
@Override
public String toString() {
return name + " earns $" + calculateSalary();
}
}
static class Manager extends Employee {
private double bonus;
Manager(String name, double baseSalary, double bonus) {
super(name, baseSalary);
this.bonus = bonus;
}
@Override
double calculateSalary() {
return baseSalary + bonus;
}
}
static class Developer extends Employee {
private int overtimeHours;
Developer(String name, double baseSalary, int overtimeHours) {
super(name, baseSalary);
this.overtimeHours = overtimeHours;
}
@Override
double calculateSalary() {
return baseSalary + overtimeHours * 25.0;
}
}
public static void main(String[] args) {
Employee[] staff = {
new Manager("Diane", 5000, 800),
new Developer("Raj", 4500, 10)
};
for (Employee e : staff) {
System.out.println(e);
}
}
}
An interface contract implemented by two unrelated classes, each satisfying it in its own way.
public class Main {
interface Payable {
double getAmountDue();
}
static class Invoice implements Payable {
private String client;
private double amount;
Invoice(String client, double amount) {
this.client = client;
this.amount = amount;
}
@Override
public double getAmountDue() {
return amount;
}
}
static class Employee implements Payable {
private String name;
private double hours;
private double rate;
Employee(String name, double hours, double rate) {
this.name = name;
this.hours = hours;
this.rate = rate;
}
@Override
public double getAmountDue() {
return hours * rate;
}
}
public static void main(String[] args) {
Payable[] items = {
new Invoice("Acme Corp", 1250.50),
new Employee("Sam", 40, 22.5)
};
double total = 0;
for (Payable p : items) {
System.out.println("Amount due: " + p.getAmountDue());
total += p.getAmountDue();
}
System.out.println("Total payable: " + total);
}
}
A hand-written Exception subclass, thrown with throws/throw and caught with a specific catch.
public class Main {
static class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
static void withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Cannot withdraw $" + amount + ", balance is only $" + balance);
}
System.out.println("Withdrew $" + amount + ", remaining balance: $" + (balance - amount));
}
public static void main(String[] args) {
double balance = 100.0;
double[] attempts = {30.0, 150.0};
for (double amount : attempts) {
try {
withdraw(balance, amount);
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
An enum whose own method computes the next state, driven by an enhanced switch on this.
public class Main {
enum TrafficLight {
RED, GREEN, YELLOW;
TrafficLight next() {
switch (this) {
case RED -> {
return GREEN;
}
case GREEN -> {
return YELLOW;
}
case YELLOW -> {
return RED;
}
default -> {
return RED;
}
}
}
}
public static void main(String[] args) {
TrafficLight light = TrafficLight.RED;
for (int i = 0; i < 6; i++) {
System.out.println(light);
light = light.next();
}
}
}
A two-type-parameter generic class, used both with mixed types and matching types.
public class Main {
static class Pair<A, B> {
private A first;
private B second;
Pair(A first, B second) {
this.first = first;
this.second = second;
}
A getFirst() {
return first;
}
B getSecond() {
return second;
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
public static void main(String[] args) {
Pair<String, Integer> nameAge = new Pair<>("Ethan", 27);
Pair<Integer, Integer> coordinate = new Pair<>(3, 8);
System.out.println(nameAge);
System.out.println(coordinate);
System.out.println("Name: " + nameAge.getFirst() + ", Age: " + nameAge.getSecond());
}
}
Uses put, get, and containsKey to track and adjust stock levels.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("Widgets", 50);
inventory.put("Gadgets", 20);
inventory.put("Gizmos", 35);
inventory.put("Widgets", inventory.get("Widgets") - 5);
if (inventory.containsKey("Gadgets")) {
System.out.println("Gadgets in stock: " + inventory.get("Gadgets"));
}
String[] toCheck = {"Widgets", "Sprockets"};
for (String item : toCheck) {
if (inventory.containsKey(item)) {
System.out.println(item + ": " + inventory.get(item));
} else {
System.out.println(item + " is not in inventory");
}
}
}
}
Computes a sum on a worker thread via an anonymous Runnable, then .join()s before reading the result on the main thread.
public class Main {
public static void main(String[] args) throws InterruptedException {
int[] sumHolder = new int[1];
Runnable task = new Runnable() {
@Override
public void run() {
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
sumHolder[0] = total;
}
};
Thread worker = new Thread(task);
worker.start();
worker.join();
System.out.println("Sum computed on worker thread: " + sumHolder[0]);
System.out.println("Main thread finished after join");
}
}