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]

Tutorial Contents

Java Operators

Operators perform computations, comparisons, and logical operations on values. Java supports arithmetic, relational, logical, bitwise, assignment, and ternary operators.

Arithmetic Operators

arithmetic.java
int a = 10, b = 3;
System.out.println(a + b);   // 13 (addition)
System.out.println(a - b);   // 7  (subtraction)
System.out.println(a * b);   // 30 (multiplication)
System.out.println(a / b);   // 3  (integer division — truncates!)
System.out.println(a % b);   // 1  (modulus — remainder)

// To get decimal result, cast one operand to double
System.out.println((double) a / b);  // 3.3333...

// Increment and decrement
int x = 5;
x++;        // x is now 6 (post-increment)
++x;        // x is now 7 (pre-increment)
x--;        // x is now 6 (post-decrement)

// Math class for advanced operations
System.out.println(Math.pow(2, 10));   // 1024.0
System.out.println(Math.sqrt(144));     // 12.0
System.out.println(Math.abs(-42));      // 42

Comparison (Relational) Operators

comparison.java
int x = 10, y = 20;
System.out.println(x == y);   // false (equal to)
System.out.println(x != y);   // true  (not equal to)
System.out.println(x > y);    // false (greater than)
System.out.println(x < y);    // true  (less than)
System.out.println(x >= 10);  // true  (greater than or equal)
System.out.println(x <= 10);  // true  (less than or equal)

// IMPORTANT: == for objects compares REFERENCES, not values!
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);       // false (different objects)
System.out.println(s1.equals(s2));  // true  (same content)

// String pool: literals share the same reference
String a1 = "hello";
String a2 = "hello";
System.out.println(a1 == a2);       // true (same pool object)
Critical Rule: Always use .equals() for comparing String and Object content. Use == only for primitives and intentional reference identity checks.

Logical Operators

logical.java
boolean isAdult = true;
boolean hasLicense = false;

// AND — both must be true
System.out.println(isAdult && hasLicense);  // false

// OR — at least one must be true
System.out.println(isAdult || hasLicense);  // true

// NOT — inverts the boolean
System.out.println(!isAdult);  // false

// Short-circuit evaluation: right side NOT evaluated if left determines result
String name = null;
if (name != null && name.length() > 0) {
    // Safe! If name is null, length() is never called
    System.out.println(name);
}

// Practical: validate before access
int[] arr = null;
boolean hasData = arr != null && arr.length > 0;

Assignment Operators

assignment.java
int x = 10;
x += 5;    // x = x + 5 = 15
x -= 3;    // x = 15 - 3 = 12
x *= 2;    // x = 12 * 2 = 24
x /= 4;    // x = 24 / 4 = 6
x %= 4;    // x = 6 % 4 = 2

// String concatenation with +=
String msg = "Hello";
msg += " World";  // "Hello World"

// Compound assignment also works with bitwise
int flags = 0b1100;
flags |= 0b0011;  // 0b1111 (set bits)
flags &= 0b1010;  // 0b1010 (clear bits)

Ternary Operator

ternary.java
int age = 20;

// condition ? valueIfTrue : valueIfFalse
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status);  // Adult

// Practical: safe null handling
String name = null;
String display = (name != null) ? name : "Guest";
// Or in Java 9+: Objects.requireNonNullElse(name, "Guest")

// Nested ternary (avoid — prefer if/else for readability)
String grade = (age >= 65) ? "Senior" : (age >= 18) ? "Adult" : "Minor";

instanceof Operator (Java 16+ Pattern Matching)

instanceof.java
Object obj = "Hello, World!";

// Traditional instanceof
if (obj instanceof String) {
    String s = (String) obj;  // manual cast
    System.out.println(s.length());
}

// Pattern matching instanceof (Java 16+) — cast built in!
if (obj instanceof String s) {
    System.out.println(s.length());  // s already cast, no explicit cast needed
}

Key Takeaways

  • Integer division truncates decimals: 5 / 2 == 2. Cast to double for decimal results.
  • Use .equals() for object content comparison; == compares references.
  • Logical && and || short-circuit — use this for null-safety guards.
  • Use the ternary operator for simple one-line conditionals; avoid nesting.
  • Pattern matching instanceof (Java 16+) eliminates manual casting.
  • Use parentheses to make operator precedence explicit in complex expressions.
Best Practice: When in doubt about operator precedence, add parentheses. It costs nothing at runtime and makes your intent clear to other developers reading the code.

Java Tutorial FAQs

How do I run Java online?
Use the Java Online Compiler to write and execute Java directly in your browser—no setup needed. Click "Try Java Online" above to get started.
How do I install Java on Windows?
Download the JDK installer, run it, then set 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?
Install the appropriate JDK DMG (x64 or ARM64). In your shell profile, set 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?
Yes. The JDK provides the compiler (javac) and tools needed to build Java applications. For quick tests, the online compiler is a convenient alternative.
What is Java used for?
Java powers cross-platform applications including web services, Android apps, enterprise systems, and tooling built on the JVM. Its strong OOP model and rich libraries make it versatile.

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

  1. Run code online: Use our Java Compiler — no installation needed
  2. Install JDK locally: Download OpenJDK 17+ from adoptium.net
  3. Choose an IDE: IntelliJ IDEA Community (free), Eclipse, or VS Code with Java Extension Pack
  4. Follow topics in order: Start from Hello World and progress sequentially
  5. Build a project: After OOP, build a small CRUD app to solidify your knowledge

Frequently Asked Questions

Do I need prior programming experience?

No. This tutorial starts from absolute basics (Hello World, variables) and progresses to advanced topics. Each concept builds on the previous one.

Which Java version should I use?

Java 17 (LTS) is recommended. All examples in this tutorial work on Java 17+. Our online compiler uses the latest stable release.

How long does it take to learn Java?

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.

Is this tutorial free?

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.