Learn Java Programming
Master Java from basics to advanced topics with concise lessons and practical examples. Follow a structured path inspired by reputable learning resources.
Reference guide: Programiz — Getting Started with Java [0]
Loops in Java
Loops repeat a block of code until a condition is met. Java provides for, enhanced for-each, while, and do-while loops, plus break and continue for flow control.
for Loop
// Basic for loop: init; condition; update
for (int i = 1; i <= 5; i++) {
System.out.print(i + " "); // 1 2 3 4 5
}
// Counting backwards
for (int i = 10; i >= 0; i -= 2) {
System.out.print(i + " "); // 10 8 6 4 2 0
}
// Nested loops: multiplication table
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= 5; col++) {
System.out.printf("%4d", row * col);
}
System.out.println();
}
Enhanced for-each Loop
// Iterating arrays
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
// Iterating collections
List<String> fruits = List.of("Apple", "Banana", "Cherry");
for (String fruit : fruits) {
System.out.println(fruit.toUpperCase());
}
// Iterating a Map
Map<String, Integer> scores = Map.of("Alice", 90, "Bob", 85);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
The for-each loop is the preferred way to iterate arrays and collections. It is cleaner, less error-prone (no off-by-one), and clearly communicates intent.
while and do-while Loops
// while — checks condition FIRST
int count = 1;
while (count <= 5) {
System.out.print(count + " ");
count++;
}
// Output: 1 2 3 4 5
// do-while — runs body FIRST, then checks condition
int attempts = 0;
boolean success = false;
do {
attempts++;
success = tryConnection(); // runs at least once
System.out.println("Attempt #" + attempts);
} while (!success && attempts < 5);
// Practical: read input until valid
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
break, continue, and Labels
// break — exit the loop immediately
for (int i = 1; i <= 10; i++) {
if (i == 6) break;
System.out.print(i + " "); // 1 2 3 4 5
}
// continue — skip current iteration, jump to next
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
System.out.print(i + " "); // 1 3 5 7 9
}
// Labeled break — exit outer loop from inner loop
outer:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking at i=" + i + " j=" + j);
break outer; // exits BOTH loops
}
}
}
When to Use Which Loop
| Loop | Best For | Example |
|---|---|---|
for | Known iteration count | Print 1–100, process N items |
for-each | Iterating arrays/collections | Display all list items |
while | Unknown iterations, condition-based | Read until EOF, retry logic |
do-while | Must execute at least once | Menu prompt, input validation |
Key Takeaways
- Use for-each for arrays and collections — cleaner and no index errors.
- Use for when you need the index or a specific step pattern.
whilechecks first;do-whileguarantees at least one execution.breakexits the loop;continueskips to the next iteration.- Labeled breaks exit outer loops from nested loops — use sparingly.
- For complex collection transformations, prefer Streams (Java 8+) over loops.
for-each for simple iteration and stream().filter().map() for transformations.Java Tutorial FAQs
How do I run Java online?
How do I install Java on Windows?
JAVA_HOME and update the Path variable to include the JDK bin directory. Verify with java --version. [0]How do I install Java on macOS?
export JAVA_HOME=$(/usr/libexec/java_home) and update PATH to include $JAVA_HOME/bin. Verify with java --version. [0]Do I need the JDK to compile Java?
javac) and tools needed to build Java applications. For quick tests, the online compiler is a convenient alternative.What is Java used for?
Learn Java the Practical Way
Whether you’re new to programming or expanding your skills, this Java tutorial focuses on hands-on learning. Each topic pairs clear explanations with short, working examples that you can run online. Move from fundamentals—variables, data types, and control flow—to core OOP concepts like classes, inheritance, and interfaces. Along the way, you’ll see idiomatic Java patterns and simple best practices that build confidence.
Why this guide? It’s designed for real-world use: fast to read, easy to try, and friendly on mobile. Bookmark it and return whenever you need a refresher or a quick example.
Java Programming Tutorial — Learn Java Step by Step
Java is one of the most widely-used programming languages in the world, powering Android apps, enterprise backends, cloud services, and scientific computing. This tutorial teaches Java from the ground up with practical, runnable examples you can try in our free Java Compiler or any local IDE.
Each topic includes multiple code examples with explanations, expected output, and best practices. Whether you are a complete beginner or refreshing your knowledge of a specific feature, every page gives you immediately usable code.
What This Tutorial Covers
- Basics: Hello World, variables, data types, operators
- Control Flow: if/else, switch, for, while, break/continue
- Methods: Parameters, return types, overloading, recursion
- Arrays & Strings: Declaration, manipulation, StringBuilder
- OOP: Classes, objects, constructors, encapsulation
- Inheritance: extends, super, abstract classes, final
- Interfaces: Abstraction, default methods, functional interfaces
- Collections: ArrayList, HashMap, HashSet, LinkedList
- Exceptions: try/catch/finally, custom exceptions
- Generics: Type parameters, bounded types, wildcards
- Streams (Java 8+): filter, map, reduce, collect
- File I/O: BufferedReader, Files API, serialisation
Why Learn Java in 2026?
- Enterprise dominance: Java powers most Fortune 500 backends via Spring Boot and Jakarta EE
- Android development: Java + Kotlin build apps for 3+ billion active Android devices
- Job market: Top 3 most-demanded language on LinkedIn, Indeed, and Stack Overflow survey
- Platform independence: Write once, run anywhere — bytecode runs on any JVM
- Modern evolution: Java 17/21 LTS added records, sealed classes, virtual threads, pattern matching
- Ecosystem: Maven/Gradle, IntelliJ IDEA, 100,000+ libraries, massive community
How to Get Started
- Run code online: Use our Java Compiler — no installation needed
- Install JDK locally: Download OpenJDK 17+ from adoptium.net
- Choose an IDE: IntelliJ IDEA Community (free), Eclipse, or VS Code with Java Extension Pack
- Follow topics in order: Start from Hello World and progress sequentially
- Build a project: After OOP, build a small CRUD app to solidify your knowledge
Frequently Asked Questions
No. This tutorial starts from absolute basics (Hello World, variables) and progresses to advanced topics. Each concept builds on the previous one.
Java 17 (LTS) is recommended. All examples in this tutorial work on Java 17+. Our online compiler uses the latest stable release.
Basics take 4–6 weeks of daily practice. Intermediate topics (collections, generics) add 4–6 more weeks. Job-readiness typically requires 3–6 months total.
Yes, completely free. No account, no sign-up. All topics and examples are available without any restriction.
Who Is This For?
Complete beginners choosing Java as their first language. CS students preparing for university courses and exams. Self-taught developers building a strong OOP foundation. Python/JS developers learning Java for backend or Android work. Interview candidates practising Java data structures. Professional developers needing a quick reference for specific Java features.