Java Online Compiler

Java online compiler · powered by OneCompiler
Open in new tab β†—

Quick start

Type or paste Java source code into the editor at the top of the page and click Run. The code is sent to OneCompiler's free cloud sandbox, compiled with javac, and executed by the JVM. Output (stdout, stderr, exit code) appears below the editor.

The first run takes a few seconds β€” that's JVM cold start. Subsequent runs on the same tab are near-instant. No account or download is required.

Ready-to-run Java templates

Copy any of these templates into the editor to see a specific Java feature in action. Click Try in compiler to copy the code and jump to the editor β€” then paste it with Ctrl+V (⌘+V on Mac).

1. Hello World

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

2. Reading input with Scanner (stdin)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("What's your name? ");
        String name = sc.nextLine();
        System.out.print("Your age? ");
        int age = sc.nextInt();
        System.out.println("Hello, " + name + "! Next year you'll be " + (age + 1) + ".");
    }
}

In the compiler above, type the stdin values in the "Stdin" panel before running β€” one value per line.

3. Command-line arguments

public class Main {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Pass arguments via the \"Command line arguments\" field");
            return;
        }
        int sum = 0;
        for (String arg : args) sum += Integer.parseInt(arg);
        System.out.println("Sum = " + sum);
    }
}

4. ArrayList and for-each

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> langs = new ArrayList<>();
        langs.add("Java");
        langs.add("Kotlin");
        langs.add("Scala");
        langs.add("Clojure");

        System.out.println("JVM languages:");
        for (int i = 0; i < langs.size(); i++) {
            System.out.println("  " + (i + 1) + ". " + langs.get(i));
        }
    }
}

5. HashMap lookup

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> capitals = new HashMap<>();
        capitals.put("France", 67_000_000);
        capitals.put("Germany", 84_000_000);
        capitals.put("Italy", 59_000_000);

        for (Map.Entry<String, Integer> e : capitals.entrySet()) {
            System.out.printf("%-10s β†’ %,d people%n", e.getKey(), e.getValue());
        }
    }
}

6. Streams β€” filter, map, reduce

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        int sumOfEvenSquares = nums.stream()
            .filter(n -> n % 2 == 0)
            .mapToInt(n -> n * n)
            .sum();
        System.out.println("Sum of even squares: " + sumOfEvenSquares);
    }
}

7. Record with validation (Java 16+)

public class Main {
    public record Point(int x, int y) {
        public Point {
            if (x < 0 || y < 0) throw new IllegalArgumentException("negative coords");
        }
        public double distanceToOrigin() { return Math.hypot(x, y); }
    }

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
        System.out.println("Distance: " + p.distanceToOrigin());
    }
}

8. Exception handling

public class Main {
    public static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            System.err.println("Caught: " + e.getMessage());
            return 0;
        } finally {
            System.out.println("divide(" + a + ", " + b + ") done");
        }
    }

    public static void main(String[] args) {
        System.out.println(divide(10, 2));
        System.out.println(divide(10, 0));
    }
}

9. Inheritance and polymorphism

public class Main {
    static abstract class Animal {
        abstract String sound();
        public String greet() { return "A " + getClass().getSimpleName() + " says " + sound(); }
    }
    static class Dog extends Animal { String sound() { return "Woof"; } }
    static class Cat extends Animal { String sound() { return "Meow"; } }
    static class Cow extends Animal { String sound() { return "Moo";  } }

    public static void main(String[] args) {
        Animal[] zoo = { new Dog(), new Cat(), new Cow() };
        for (Animal a : zoo) System.out.println(a.greet());
    }
}

10. Recursion β€” factorial with BigInteger

import java.math.BigInteger;

public class Main {
    static BigInteger factorial(int n) {
        if (n <= 1) return BigInteger.ONE;
        return BigInteger.valueOf(n).multiply(factorial(n - 1));
    }

    public static void main(String[] args) {
        for (int n = 1; n <= 25; n++) {
            System.out.printf("%2d! = %s%n", n, factorial(n));
        }
    }
}

Best free Java online compilers compared (2026)

We tested five popular free Java online compilers on the same criteria: Java version, stdin support, login requirements, execution limits, ads, and overall developer experience. Here's the breakdown.

Feature OneCompiler Programiz JDoodle Replit Local JDK
Java version17118 / 11 / 17 / 2117 / 21Any LTS
stdinβœ…βœ…βœ…βœ…βœ…
Command-line argsβœ…βŒβœ…βœ…βœ…
Multi-file projectβœ…βŒβœ… (paid)βœ…βœ…
Maven / Gradle depsβŒβŒβŒβœ…βœ…
File I/O❌❌❌ (sandboxed)Partialβœ…
Network access❌❌❌ (paid: βœ…)βœ…βœ…
Signup requiredOptionalNoOptionalYesNo
Shareable URLβœ…βŒβœ…βœ…N/A
Max execution time~10s~10s~10s (paid: more)~60sUnlimited
AdsLightLightModerateModerateNone
Iframe embeddableβœ…βŒβœ… (via widget JS)βœ… (paid)N/A
Best forQuick snippets, teachingBeginners learning JavaPaid API, multi-langFull projects, collabReal projects

OneCompiler (our default)

Clean UI, Java 17, shareable URLs, support for multiple files, and β€” crucially for this page β€” allows iframe embedding. Free tier is generous; no login needed unless you want to save snippets. Best overall balance for a free sandbox.

Programiz

Focused on learning. Extra-simple editor, auto-detects the class name, and no login required. Java 11 only. Does not allow iframe embedding (their page uses X-Frame-Options: SAMEORIGIN), which is why we open it in a new tab here.

JDoodle

The veteran. Supports 70+ languages, multiple Java versions (8, 11, 17, 21), and offers a paid API for programmatic execution. Free tier has ads and execution time limits. Their iframe embed works but requires their JS widget.

Replit

Full cloud IDE with Git, deployments, AI assistance, and real-time collaboration. Supports Maven dependencies and network access. Requires signup. The free tier is limited; serious projects are paid.

Local JDK (not an online tool, but the reference)

Everything above is a subset of what a local JDK offers. Unlimited execution, real file I/O, network, Maven / Gradle, any library. For anything beyond a single file, install a JDK.

How Java compilation works under the hood

When you click Run, four things happen on the compiler's server:

  1. Your source is saved as Main.java in a temporary directory.
  2. javac Main.java runs. If it fails, you see the compiler errors (red). The compiler parses your source, builds an AST, performs type-checking, and emits bytecode β€” a platform-neutral instruction set β€” into Main.class.
  3. java Main starts the JVM with Main.class on the classpath. The JVM loads the class, verifies the bytecode, and begins execution.
  4. Output β€” anything written to System.out or System.err is streamed back to your browser and displayed.

The JVM doesn't interpret bytecode naively β€” it uses a JIT (Just-In-Time) compiler to translate hot methods into native machine code at runtime. That's why Java programs are fast despite the bytecode layer. In a short online run, JIT doesn't have time to warm up; the first iteration of a hot loop is interpreted, subsequent ones compiled.

What javac actually produces

A .class file is binary. You can inspect it with javap:

javac Main.java
javap -c Main.class   # disassemble
javap -v Main.class   # verbose: constant pool + stackmap

Understanding bytecode is rarely necessary day-to-day, but it's fascinating and demystifies how the JVM reasons about your code.

How to compile Java locally (no online compiler)

For anything beyond a single file, a local JDK is faster, offline-capable, and unlimited. Install in under 5 minutes:

  1. Install a JDK. We recommend Eclipse Temurin 21 β€” free, open source, well-maintained. See our guide on downloading the Java JDK.
  2. Verify the install: open a terminal and run java -version and javac -version. Both should print 21.
  3. Write and run:
    mkdir hello && cd hello
    echo 'public class Hello { public static void main(String[] a) { System.out.println("Hi"); } }' > Hello.java
    javac Hello.java
    java Hello
  4. Single-file source mode (Java 11+): skip the javac step entirely.
    java Hello.java

For real projects, add Maven or Gradle to manage dependencies, and an IDE (IntelliJ IDEA Community or VS Code with the Java Extension Pack).

Common Java compile errors and how to fix them

Most first-time errors on any Java online compiler fall into one of these ten categories. Each section explains the cause and the fix.

class X is public, should be declared in a file named X.java

The online compiler saves your file as Main.java. If your public class is named something else (e.g. HelloWorld), javac complains. Two fixes: rename your class to Main, or drop the public modifier.

'class', 'interface', or 'enum' expected

You wrote code outside a class body. Every Java file must wrap its code in at least one top-level class or interface. Put your main method inside a class Main { ... }.

cannot find symbol

A method, class or variable name is not recognized. Usually: missing import, typo, or the symbol belongs to a dependency that's not on the classpath. See our detailed guide on this error.

incompatible types

You assigned an expression of one type to a variable of another. Java is strict about this: an int can auto-widen to a double, but not vice versa without an explicit cast. Check the error line; the compiler tells you exactly what it expected vs. what it got.

missing return statement

A non-void method ends without returning on some code path. Every branch must return a value. Add a return at the end, or change the return type to void.

reached end of file while parsing

Unmatched {. Count your opening and closing braces; it's almost always a forgotten one at the top or bottom of the class.

bad operand types for binary operator

You used an operator (+, -, <…) on types that don't support it. Common case: "hello" - 3 β€” you can concatenate strings with +, but you can't subtract. Convert explicitly.

variable X might not have been initialized

Local variables have no default value in Java β€” the compiler requires you to assign one before use. Unlike instance fields (which default to 0/null/false), local variables must be written before they're read.

error: <identifier> expected

Almost always a missing parenthesis, brace, or semicolon on the preceding line. Check the line number; go up one or two lines.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

This is a runtime error, not a compile error β€” the code compiled but your indices are out of bounds. Check that you're not accessing args[0] without passing command-line arguments, or iterating past array.length.

Limitations of online Java compilers

Free online compilers are designed for quick experiments, not production workloads. Their sandboxes impose hard limits you will hit the moment your code does anything serious:

  • Execution time capped β€” typically 10 to 30 seconds. Long loops or servers are killed.
  • Memory capped β€” usually 256 MB to 1 GB of heap. Allocating a large int[] or loading a 500 MB file will fail.
  • No file system access β€” new File(...) cannot read or write. Only stdin/stdout are available.
  • No network β€” outbound HTTP and socket calls are blocked. You can't call HttpClient or JDBC.
  • Limited dependencies β€” standard JDK only. No Maven, no external JARs.
  • No persistence β€” the sandbox is wiped between runs. Saving state across runs requires a cloud IDE.
  • Throttled CPU β€” benchmarks are meaningless on shared sandboxes.

When you need a local JDK

Online compilers answer the "can I see this snippet run?" question. For anything larger, install a JDK. You need a local setup if you're:

  • Building an actual application (command-line tool, web service, desktop GUI)
  • Using Maven or Gradle to pull in libraries
  • Running tests with JUnit, Mockito, etc.
  • Debugging with breakpoints and stepping through code
  • Working with files, databases, or network services
  • Collaborating via Git on a real project
  • Benchmarking performance or profiling memory
  • Learning enterprise Java β€” Spring, Jakarta EE, JPA

Our installing the JDK guide covers Windows, macOS and Linux in detail.

Who uses online Java compilers?

Online compilers are a tiny part of the Java toolchain, but they fit specific workflows perfectly:

  • Students β€” first programs without battling installation on a shared or locked-down machine.
  • Teachers β€” demonstrating a concept live in class, sharing a link to a working example.
  • Interviewers β€” conducting coding interviews with a neutral, consistent environment. Many platforms (HackerRank, Codility, LeetCode) use similar sandboxes under the hood.
  • Bloggers and content creators β€” reproducible snippets embedded in articles.
  • Professional developers quickly testing an isolated idea, a regex, a date format, or a standard-library method without polluting a real project.
  • Interview prep β€” LeetCode-style problems, Codewars katas, HackerRank challenges.
  • Open-source bug reports β€” attaching a minimal reproducer via a shareable URL.

Online compilers vs cloud IDEs

Online compilers (OneCompiler, Programiz, JDoodle) are single-page tools with a text area and a Run button. They're zero-friction but limited.

Cloud IDEs (Replit, Gitpod, GitHub Codespaces, IntelliJ IDEA Cloud) give you a full VS Code or IntelliJ-like experience in the browser β€” Git, Maven, terminals, multiple files, debugging, network access. They require signup, sometimes a paid plan, and a couple of minutes to spin up a workspace. Use them for anything you'd do in a normal IDE.

The rough rule: compiler for snippets, cloud IDE for projects, local IDE for everything serious.

A brief history of online Java compilers

The first wave of web-based code runners appeared in the early 2000s as CGI scripts shelling out to javac. They were slow, often broken, and mostly used for academic demos. Ideone launched in 2009 and was the first mainstream tool to get the formula right: a clean editor, immediate execution, and a URL for every snippet.

JDoodle (2013) expanded the approach to 70+ languages with a paid API. Programiz (~2014) targeted beginners with a simplified editor. Replit (2016) went beyond single-file runs and built a full cloud IDE. OneCompiler (~2019) focused on embedding, sharing, and a polished editor UX.

Today the niche is mature. The five major players are within a similar feature envelope for free tiers; differences matter more at scale (paid API, enterprise limits).

Frequently asked questions

Is this Java online compiler free?

Yes. The embedded compiler is free, with no signup required. Code runs in a third-party cloud sandbox. You can also open the full-screen editor in a new tab via the link above the iframe.

Which Java version does the online compiler use?

OneCompiler runs OpenJDK 17. For your local setup, install the latest LTS β€” currently Java 21.

Can I provide input (stdin) to my Java program?

Yes. The editor has a dedicated stdin panel below the code area. Type your input there, one value per line, before clicking Run. Your Scanner or BufferedReader reads from it normally.

Can I pass command-line arguments?

OneCompiler accepts them in a "Command line arguments" input below the editor. Fill it in before clicking Run and your main(String[] args) will receive them.

Can I read files from disk?

No. Online compilers block file system access for security. You can read from stdin only. For real file I/O, install a JDK locally.

Can I use Maven or Gradle dependencies?

Most online compilers ship only the standard JDK. For projects with external libraries, use a cloud IDE like Replit or GitHub Codespaces β€” or install a JDK locally.

Is my code private when I use an online compiler?

Code is sent to the provider's cloud for execution. Do not paste proprietary source or credentials. For confidential work, use a local JDK.

Why does it say "class is public, should be in a file named Main.java"?

The compiler saves your code as Main.java. Rename your public class to Main, or drop the public modifier.

How do I compile Java from the command line?

With a JDK installed: javac Main.java to compile, then java Main to execute. On Java 11+, run java Main.java directly (single-file source mode).

What's the difference between a compiler and a runtime?

The compiler (javac) translates .java source into .class bytecode. The runtime (java, the JVM) loads and executes that bytecode. Both ship together in a JDK.

Can I run multithreaded Java code online?

Yes, threads run normally. Execution time is capped though (usually 10–30 seconds), so infinite loops or long-running servers will be killed.

Why is my first run slow?

JVM cold start. Every new sandbox has to spin up a JVM before executing your code. Subsequent runs on the same editor tab are much faster.

Can I save my code?

OneCompiler gives you a shareable URL for every snippet. Click "Save" in the embedded editor and copy the generated link.

Is there a mobile version?

The embedded editor works on mobile but the experience is better on desktop. For phone-first coding, the apps from OneCompiler and similar providers are easier to use.

Does running Java online count as "coding"?

Yes, it runs real Java on a real JVM. The output is identical to running the same code on your machine, within the sandbox's limits. Online compilers are not toys β€” they're useful tools, as long as you know their limits.