Hello World
The classic first Java program.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Run Hello World in the Java compilerStudy complete Java programs, compare their output, and open any example in the online Java compiler.
The classic first Java program.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Run Hello World in the Java compilerDeclare int, double, boolean, char, String.
public class Main {
public static void main(String[] args) {
int age = 25;
double pi = 3.14159;
boolean isActive = true;
char grade = 'A';
String name = "Alice";
System.out.println(name + " | " + age + " | " + pi + " | " + grade + " | " + isActive);
}
}Run Variables & Data Types in the Java compilerImplicit and explicit type conversion.
public class Main {
public static void main(String[] args) {
int i = 10;
double d = i; // implicit
double pi = 3.99;
int truncated = (int) pi; // explicit
System.out.println(d + " " + truncated);
}
}Run Type Casting in the Java compiler+ - * / % and integer division.
public class Main {
public static void main(String[] args) {
int a = 17, b = 5;
System.out.println("Sum: " + (a + b));
System.out.println("Div: " + (a / b));
System.out.println("Mod: " + (a % b));
}
}Run Arithmetic Operators in the Java compilerprintf and String.format.
public class Main {
public static void main(String[] args) {
System.out.printf("Pi = %.2f%n", 3.14159);
String s = String.format("Score: %05d", 42);
System.out.println(s);
}
}Run String Formatting in the Java compilerUse Scanner to read an int from stdin.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("You entered: " + n);
}
}Run Read Integer from Input in the Java compilerRead a full line using nextLine().
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
System.out.println("Hello, " + line + "!");
}
}Run Read a Line of Text in the Java compilerRead several ints separated by spaces.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
System.out.println("Sum: " + (a + b + c));
}
}Run Read Multiple Values in the Java compilerFirst line: size. Second line: numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
int sum = 0;
for (int x : arr) sum += x;
System.out.println("Sum: " + sum);
}
}Run Read Array from Input in the Java compilerFaster than Scanner for large inputs.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] parts = br.readLine().trim().split(" ");
long sum = 0;
for (int i = 0; i < n; i++) sum += Long.parseLong(parts[i]);
System.out.println(sum);
}
}Run Fast I/O with BufferedReader in the Java compilerLoop with hasNext() until input ends.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = 0;
while (sc.hasNextInt()) total += sc.nextInt();
System.out.println("Total: " + total);
}
}Run Read Until EOF in the Java compilerlength() and charAt().
public class Main {
public static void main(String[] args) {
String s = "Hello";
System.out.println("Length: " + s.length());
System.out.println("First: " + s.charAt(0));
System.out.println("Last: " + s.charAt(s.length() - 1));
}
}Run String Length & Char Access in the Java compilerUsing StringBuilder.reverse().
public class Main {
public static void main(String[] args) {
String s = "Java";
String reversed = new StringBuilder(s).reverse().toString();
System.out.println(reversed);
}
}Run Reverse a String in the Java compilerTwo-pointer approach.
public class Main {
public static void main(String[] args) {
String s = "racecar";
int l = 0, r = s.length() - 1;
boolean ok = true;
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) { ok = false; break; }
}
System.out.println(ok);
}
}Run Palindrome Check in the Java compilerIterate and count a/e/i/o/u.
public class Main {
public static void main(String[] args) {
String s = "Programming";
int count = 0;
for (char c : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) >= 0) count++;
}
System.out.println(count);
}
}Run Count Vowels in the Java compilersplit() by delimiter.
public class Main {
public static void main(String[] args) {
String csv = "apple,banana,cherry";
String[] parts = csv.split(",");
for (String p : parts) System.out.println(p);
}
}Run Split a String in the Java compilerBuild a string efficiently.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) sb.append(i).append(" ");
System.out.println(sb.toString().trim());
}
}Run StringBuilder Loop in the Java compilerSort both strings and compare.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String a = "listen", b = "silent";
char[] ca = a.toCharArray();
char[] cb = b.toCharArray();
Arrays.sort(ca); Arrays.sort(cb);
System.out.println(Arrays.equals(ca, cb));
}
}Run Anagram Check in the Java compilerTwo ways to create arrays.
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[5];
for (int i = 0; i < b.length; i++) b[i] = i * i;
for (int x : b) System.out.print(x + " ");
}
}Run Declare & Initialize Array in the Java compilerSingle-pass linear scan.
public class Main {
public static void main(String[] args) {
int[] arr = {3, 8, 1, 9, 4, 7};
int max = arr[0];
for (int x : arr) if (x > max) max = x;
System.out.println("Max: " + max);
}
}Run Find Maximum in Array in the Java compilerTwo-pointer swap.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int l = 0, r = arr.length - 1;
while (l < r) {
int tmp = arr[l]; arr[l] = arr[r]; arr[r] = tmp;
l++; r--;
}
System.out.println(Arrays.toString(arr));
}
}Run Reverse Array In-Place in the Java compilerArrays.sort() built-in.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9, 3};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}Run Sort an Array in the Java compilerIterate rows and columns.
public class Main {
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}Run 2D Array (Matrix) in the Java compilerFind index of a value.
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30, idx = -1;
for (int i = 0; i < arr.length; i++) if (arr[i] == target) { idx = i; break; }
System.out.println("Index: " + idx);
}
}Run Linear Search in the Java compilerO(log n) on sorted array.
public class Main {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13};
int target = 7, lo = 0, hi = arr.length - 1, idx = -1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] == target) { idx = mid; break; }
else if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
System.out.println(idx);
}
}Run Binary Search in the Java compilerCompute totals over an array.
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int sum = 0;
for (int x : arr) sum += x;
System.out.println("Sum: " + sum + " Avg: " + (sum / (double) arr.length));
}
}Run Sum & Average in the Java compilerUsing a HashSet.
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5};
Set<Integer> seen = new LinkedHashSet<>();
for (int x : arr) seen.add(x);
System.out.println(seen);
}
}Run Remove Duplicates in the Java compilerPrint numbers 1 to 10.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) System.out.print(i + " ");
}
}Run For Loop in the Java compilerSum digits of a number.
public class Main {
public static void main(String[] args) {
int n = 12345, sum = 0;
while (n > 0) { sum += n % 10; n /= 10; }
System.out.println(sum);
}
}Run While Loop in the Java compilerGrade calculator.
public class Main {
public static void main(String[] args) {
int score = 78;
String grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else grade = "F";
System.out.println("Grade: " + grade);
}
}Run If/Else Conditions in the Java compilerDay of week.
public class Main {
public static void main(String[] args) {
int day = 3;
String name = switch (day) {
case 1 -> "Mon"; case 2 -> "Tue"; case 3 -> "Wed";
case 4 -> "Thu"; case 5 -> "Fri"; default -> "Weekend";
};
System.out.println(name);
}
}Run Switch Statement in the Java compilerClassic interview warmup.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 15 == 0) System.out.println("FizzBuzz");
else if (i % 3 == 0) System.out.println("Fizz");
else if (i % 5 == 0) System.out.println("Buzz");
else System.out.println(i);
}
}
}Run FizzBuzz in the Java compilerPrint a triangle pattern.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) System.out.print("* ");
System.out.println();
}
}
}Run Nested Loop — Stars in the Java compilerStatic method with parameters.
public class Main {
static int add(int a, int b) { return a + b; }
public static void main(String[] args) {
System.out.println(add(3, 4));
}
}Run Define a Method in the Java compilerSame name, different signatures.
public class Main {
static int sum(int a, int b) { return a + b; }
static double sum(double a, double b) { return a + b; }
static int sum(int a, int b, int c) { return a + b + c; }
public static void main(String[] args) {
System.out.println(sum(2, 3));
System.out.println(sum(1.5, 2.5));
System.out.println(sum(1, 2, 3));
}
}Run Method Overloading in the Java compilerVariable number of arguments.
public class Main {
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
public static void main(String[] args) {
System.out.println(sum(1, 2, 3, 4, 5));
}
}Run Varargs Method in the Java compilerDefine a class and create instances.
class Person {
String name;
int age;
Person(String name, int age) { this.name = name; this.age = age; }
void greet() { System.out.println("Hi, I'm " + name); }
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Alice", 30);
p.greet();
}
}Run Class & Object in the Java compilerextends keyword.
class Animal {
void eat() { System.out.println("eating"); }
}
class Dog extends Animal {
void bark() { System.out.println("woof"); }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); d.bark();
}
}Run Inheritance in the Java compilerMethod overriding via parent reference.
class Shape { double area() { return 0; } }
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Square extends Shape {
double s;
Square(double s) { this.s = s; }
double area() { return s * s; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(3), new Square(4) };
for (Shape sh : shapes) System.out.println(sh.area());
}
}Run Polymorphism in the Java compilerImplement an interface.
interface Greeter { String greet(String name); }
class English implements Greeter {
public String greet(String name) { return "Hello, " + name; }
}
public class Main {
public static void main(String[] args) {
Greeter g = new English();
System.out.println(g.greet("World"));
}
}Run Interface in the Java compilerprivate fields + getters/setters.
class Account {
private double balance;
public void deposit(double amt) { if (amt > 0) balance += amt; }
public double getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.deposit(100); a.deposit(50);
System.out.println(a.getBalance());
}
}Run Encapsulation in the Java compilerDynamic array with add/get/remove.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple"); list.add("banana"); list.add("cherry");
list.remove(1);
System.out.println(list);
}
}Run ArrayList Basics in the Java compilerKey-value store.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
for (var e : ages.entrySet()) System.out.println(e.getKey() + " = " + e.getValue());
}
}Run HashMap Basics in the Java compilerRemoves duplicates automatically.
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 3, 3, 4};
Set<Integer> set = new HashSet<>();
for (int x : arr) set.add(x);
System.out.println(set);
}
}Run HashSet — Unique Items in the Java compilerHashMap counting pattern.
import java.util.*;
public class Main {
public static void main(String[] args) {
String text = "the quick brown fox the lazy dog the fox";
Map<String, Integer> count = new HashMap<>();
for (String w : text.split(" ")) count.merge(w, 1, Integer::sum);
System.out.println(count);
}
}Run Word Frequency Counter in the Java compilerCollections.sort with comparator.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9));
Collections.sort(nums);
System.out.println(nums);
nums.sort(Comparator.reverseOrder());
System.out.println(nums);
}
}Run Sort a List in the Java compilerDeque used as stack.
import java.util.*;
public class Main {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2); stack.push(3);
while (!stack.isEmpty()) System.out.print(stack.pop() + " ");
}
}Run Stack (LIFO) in the Java compilerLinkedList as Queue.
import java.util.*;
public class Main {
public static void main(String[] args) {
Queue<String> q = new LinkedList<>();
q.offer("a"); q.offer("b"); q.offer("c");
while (!q.isEmpty()) System.out.print(q.poll() + " ");
}
}Run Queue (FIFO) in the Java compilern! via recursion.
public class Main {
static long fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
public static void main(String[] args) {
System.out.println(fact(10));
}
}Run Factorial (Recursive) in the Java compilerFirst 10 numbers.
public class Main {
static int fib(int n) { return n <= 1 ? n : fib(n-1) + fib(n-2); }
public static void main(String[] args) {
for (int i = 0; i < 10; i++) System.out.print(fib(i) + " ");
}
}Run Fibonacci Sequence in the Java compilerRecursion on integers.
public class Main {
static int sumDigits(int n) { return n == 0 ? 0 : n % 10 + sumDigits(n / 10); }
public static void main(String[] args) {
System.out.println(sumDigits(12345));
}
}Run Sum of Digits (Recursive) in the Java compilerRecursive exponentiation.
public class Main {
static long power(long a, int n) { return n == 0 ? 1 : a * power(a, n - 1); }
public static void main(String[] args) {
System.out.println(power(2, 10));
}
}Run Power (a^n) in the Java compilerHandle ArithmeticException.
public class Main {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Always runs");
}
}
}Run Try/Catch in the Java compilerextends Exception.
class TooYoungException extends Exception {
TooYoungException(String msg) { super(msg); }
}
public class Main {
static void verify(int age) throws TooYoungException {
if (age < 18) throw new TooYoungException("Must be 18+");
}
public static void main(String[] args) {
try { verify(15); }
catch (TooYoungException e) { System.out.println(e.getMessage()); }
}
}Run Custom Exception in the Java compilerFiles.writeString and readString.
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
Path p = Path.of("/tmp/note.txt");
Files.writeString(p, "Hello from Java!");
String content = Files.readString(p);
System.out.println(content);
}
}Run Write & Read File in the Java compilerpow, sqrt, abs, max, min.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(2, 10));
System.out.println(Math.sqrt(144));
System.out.println(Math.abs(-7));
System.out.println(Math.max(3, 9));
}
}Run Math Class Basics in the Java compilerO(sqrt(n)) primality test.
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) {
for (int i = 2; i <= 20; i++) if (isPrime(i)) System.out.print(i + " ");
}
}Run Prime Number Check in the Java compilerGreatest common divisor.
public class Main {
static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
public static void main(String[] args) {
System.out.println(gcd(48, 18));
}
}Run GCD (Euclidean) in the Java compilerjava.util.Random examples.
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random r = new Random(42);
for (int i = 0; i < 5; i++) System.out.print(r.nextInt(100) + " ");
}
}Run Random Numbers in the Java compiler