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]
Strings in Java
Strings in Java are immutable objects that represent sequences of characters. The String class provides dozens of methods for searching, comparing, and transforming text. For mutable string operations, use StringBuilder.
Creating Strings
// String literals (stored in the String Pool)
String greeting = "Hello, World!";
String empty = "";
// Using new keyword (creates a separate object on the heap)
String s = new String("Hello");
// String Pool: identical literals share the same object
String a = "Java";
String b = "Java";
System.out.println(a == b); // true (same pool reference)
System.out.println(a.equals(b)); // true (same content)
// Text Blocks (Java 13+) for multi-line strings
String json = """
{
"name": "Alice",
"age": 25
}
""";
System.out.println(json);
Common String Methods
String text = " Hello, Java World! ";
// Length and checking
System.out.println(text.length()); // 22
System.out.println(text.isEmpty()); // false
System.out.println(text.isBlank()); // false (Java 11+)
// Case conversion
System.out.println(text.toUpperCase()); // " HELLO, JAVA WORLD! "
System.out.println(text.toLowerCase()); // " hello, java world! "
System.out.println(text.trim()); // "Hello, Java World!" (removes whitespace)
System.out.println(text.strip()); // Same as trim but handles Unicode (Java 11+)
// Searching
System.out.println(text.contains("Java")); // true
System.out.println(text.indexOf("Java")); // 9
System.out.println(text.startsWith(" Hello")); // true
System.out.println(text.endsWith("! ")); // true
// Extracting
System.out.println(text.substring(9, 13)); // "Java"
System.out.println(text.charAt(2)); // 'H'
// Replacing
System.out.println(text.replace("Java", "PHP")); // " Hello, PHP World! "
System.out.println(text.replaceAll("\\s+", " "));// Regex: collapse whitespace
// Splitting
String csv = "red,green,blue,yellow";
String[] colors = csv.split(",");
// ["red", "green", "blue", "yellow"]
// Joining (Java 8+)
String joined = String.join(" | ", colors);
// "red | green | blue | yellow"
String Comparison
String s1 = "Hello";
String s2 = "hello";
String s3 = new String("Hello");
// Content comparison (ALWAYS use these for strings)
System.out.println(s1.equals(s3)); // true
System.out.println(s1.equalsIgnoreCase(s2)); // true
// Reference comparison (DO NOT use for content)
System.out.println(s1 == s3); // false (different objects)
// Lexicographic comparison (for sorting)
System.out.println("apple".compareTo("banana")); // negative (apple comes first)
System.out.println("banana".compareTo("apple")); // positive
// Null-safe comparison
String maybeNull = null;
System.out.println("Hello".equals(maybeNull)); // false (safe)
// System.out.println(maybeNull.equals("Hello")); // NullPointerException!
.equals() or .equalsIgnoreCase(), never with ==. Put the known non-null string on the left to avoid NullPointerException.StringBuilder (Mutable Strings)
// Problem: String concatenation in loops creates many temporary objects
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ","; // Creates 1000 new String objects! Slow.
}
// Solution: StringBuilder modifies the same buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(",");
}
String fast = sb.toString();
// Common StringBuilder methods
StringBuilder builder = new StringBuilder("Hello");
builder.append(" World"); // "Hello World"
builder.insert(5, ","); // "Hello, World"
builder.replace(0, 5, "Hi"); // "Hi, World"
builder.reverse(); // "dlroW ,iH"
builder.delete(0, 5); // " ,iH"
System.out.println(builder.toString());
String Formatting
String name = "Alice";
int age = 25;
double score = 95.5;
// String.format() — like printf
String msg = String.format("Name: %s, Age: %d, Score: %.1f%%", name, age, score);
System.out.println(msg); // Name: Alice, Age: 25, Score: 95.5%
// Formatted string (Java 15+)
String modern = "Name: %s, Age: %d".formatted(name, age);
// Common format specifiers:
// %s = string, %d = integer, %f = float, %.2f = 2 decimal places
// %n = newline, %% = literal percent sign
Key Takeaways
- Strings are immutable — every modification creates a new String object.
- Always use
.equals()for content comparison, never==. - Use
StringBuilderfor concatenation in loops — it is orders of magnitude faster. - Use
String.format()or text blocks (Java 13+) for complex string construction. - Key methods:
length(),contains(),substring(),split(),replace(),trim(). - Put the known non-null value on the left of
.equals()to avoid NullPointerException.
StringBuilder inside loops and methods that build strings incrementally. For simple one-time concatenation ("Hello " + name), the compiler optimises this automatically — no need for StringBuilder there.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.