File types · Explainer

The Java source file (.java)

A JAVA file is a plain-text file of source code in the Java programming language, which the javac compiler turns into bytecode for the Java Virtual Machine. This guide explains what's inside one, how to compile and run it, the rules that tie file names to class names, and has free sample Java files to download for testing.

At a glance

Full name
Java source file
Extensions
.java
MIME type
None registered; text/x-java is common on Linux
Kind
Plain text (source code), compiled to .class bytecode before it runs
Encoding
UTF-8 by default since Java 18; older versions use the system's default unless you pass -encoding
Standard
The Java Language Specification, published by Oracle; OpenJDK is the reference implementation
First released
1996, by Sun Microsystems (part of Oracle since 2010)
Current LTS
Java 25 (September 2025); Java 21 and 17 are earlier LTS releases
Runs on
A Java Virtual Machine, on Windows, macOS, Linux and more; Android compiles Java too
Comments
// line, /* block */, /** Javadoc */
Magic number
None in source; compiled .class files start with CA FE BA BE

The basics

What is a JAVA file?

A .java file holds Java source code: classes with fields and methods, written as text. The Java compiler, javac, translates it into bytecode, stored in .class files. A Java Virtual Machine (JVM) then runs the bytecode on any operating system it's installed on, which is the idea behind Java's "write once, run anywhere".

Java runs a lot of business software: banking and insurance systems, web back ends built with Spring, big-data tools, Minecraft (Java Edition), and much of Android, where Java and Kotlin source are compiled for Android's own runtime. Students meet it early, because many courses teach programming in Java.

Three things worth knowing up front:

  • Java is not JavaScript. The two languages share part of a name and some syntax, nothing more. JavaScript files run in browsers; Java files are compiled for the JVM.
  • You need a JDK, not just a JRE. The Java Development Kit includes javac; a runtime alone can run programs but not compile them. Free builds of OpenJDK come from Oracle, Eclipse Temurin, Amazon Corretto, Microsoft and others.
  • The file name matters. A public class must live in a file with exactly its name, and packages map to folders. More on this below.

Anatomy

What's inside a Java file

A Java file holds one or more classes, and all code lives inside a class. The order is fixed: an optional package line, then imports, then the classes. Here is a small program in a package, part by part.

com/example/greet/Greeter.java
package com.example.greet;

import java.time.LocalTime;

/** Greets people according to the time of day. */
public class Greeter {
    private final String name;

    public Greeter(String name) {
        this.name = name;
    }

    public String greet(LocalTime time) {
        String part = time.getHour() < 12 ? "morning" : "afternoon";
        return "Good " + part + ", " + name + "!";
    }

    public static void main(String[] args) {
        String who = args.length > 0 ? args[0] : "Ada";
        Greeter greeter = new Greeter(who);
        System.out.println(greeter.greet(LocalTime.now()));
    }
}
  1. 1package com.example.greet;

    The package

    Names the namespace the class belongs to, and by convention the folder it sits in: com/example/greet/. Without a package line, the class is in the unnamed package, which is fine for small programs.

  2. 2import java.time.LocalTime;

    An import

    Lets the file write LocalTime instead of java.time.LocalTime. Classes in java.lang, such as String and System, never need importing.

  3. 3/** Greets people … */

    A Javadoc comment

    Starts with /**. The javadoc tool turns these into HTML documentation, and editors show them on hover.

  4. 4public class Greeter {

    A public class

    Because it's public, the file must be called Greeter.java, exactly, including the capital G. A file can hold other classes, but only one public top-level one.

  5. 5private final String name;

    A field

    Data each Greeter object carries. private hides it from other classes; final means it's set once, in the constructor.

  6. 6public Greeter(String name) { … }

    A constructor

    Has the class's name and no return type. new Greeter("Ada") calls it.

  7. 7public String greet(LocalTime time)

    A method

    Every parameter and return value has a declared type, checked by the compiler.

  8. 8public static void main(String[] args)

    The entry point

    Where the program starts. static means it runs without an object; args holds the words typed after the class name on the command line.

  9. 9System.out.println(…);

    Output

    Prints a line to the terminal. Every statement ends with a semicolon.

How to

How to compile and run a .java file

Install a JDK, then open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) in the file's folder. Check the install with javac -version.

Terminal
# Compile: the .java source becomes .class bytecode
javac Hello.java               # writes Hello.class
java Hello                     # run it: the class name, no extension

# With a package, compile into a folder tree and name the full class
javac -d out com/example/greet/Greeter.java
java -cp out com.example.greet.Greeter

# Skip the compile step (Java 11+): compiled in memory, nothing written
java Hello.java

# Package it as a JAR and run that
jar --create --file greet.jar --main-class com.example.greet.Greeter -C out .
java -jar greet.jar
  • java Hello.java (Java 11, JEP 330) compiles the file in memory and runs the first class in it. No .class file is written, and the file name doesn't have to match the class. Good for scripts, teaching and quick tests.
  • Several source files (Java 22, JEP 458). The same command now also compiles the other .java files the program uses, as long as each class sits in a file named after it, in folders that match the packages. Older versions only see the one file.
  • Projects use a build tool. Maven and Gradle compile everything under src/main/java, run the tests in src/test/java, download libraries and build the JAR.
  • Double-clicking a .java file doesn't run it: it opens in an editor. A .jar file can run on double-click if a Java runtime is installed.
Java 22+: a two-file program
app/
├── Main.java      class Main uses Helper
└── Helper.java    class Helper

java app/Main.java    # Java 22+: also finds and compiles Helper.java

Rules

The file-name rule, packages and folders

The Java Language Specification lets a compiler require that a public class sits in a file named after it, and javac does: public class Greeter must be in Greeter.java, or you get class Greeter is public, should be declared in a file named Greeter.java. The rule follows from it that a file holds at most one public top-level class.

  • Case matters. greeter.java is the wrong name for Greeter, even on Windows and macOS, whose file systems ignore case for most other purposes.
  • Packages map to folders. package com.example.greet; belongs in com/example/greet/. javac -d out writes out/com/example/greet/Greeter.class, and you run it by its full name, com.example.greet.Greeter. From Java 22, java Greeter.java checks this too and stops with end of path to source file does not match its package name if the folders are wrong.
  • One source file, several class files. Every class, including nested ones, gets its own .class file: Outer$Inner.class for a class inside Outer.
  • Non-public classes have no naming rule. A class without public can sit in a file of any name. The samples on this page use that, because a file called sample-program.java can't hold a public class: the hyphen makes it an invalid class name.
  • Two names are reserved for special files: module-info.java declares a module, and package-info.java documents a package.

Versions

Java versions that matter, and compact source files

A new Java feature release comes out every six months, in March and September, and Oracle makes one every two years a long-term support (LTS) release. Most companies run an LTS version.

VersionReleasedClass file versionNotable for
Java 8 (LTS)March 201452Lambdas and streams. Still found in older systems
Java 11 (LTS)September 201855java Hello.java runs a source file directly
Java 17 (LTS)September 202161Records, text blocks, switch expressions and sealed classes all available
Java 21 (LTS)September 202365Virtual threads, pattern matching for switch, record patterns, sequenced collections
Java 22March 202466Running a program spread over several source files with java
Java 25 (LTS)September 202569Compact source files and instance main methods

Java 25 made compact source files final (JEP 512). A file can hold methods and fields with no class around them; main no longer has to be public static or take args; the IO class prints and reads lines; and the common java.base classes, such as List, need no imports. The compiler wraps the file in a class named after the file, so the file name must be a valid class name: Hello.java works, while hello-world.java fails with bad file name.

Hello.java
// Hello.java: a compact source file (Java 25)
void main() {
    String name = IO.readln("Name? ");
    IO.println("Hello, " + name + "! " + List.of(1, 2, 3));
}

Compiling for an older Java

Code compiled by a newer JDK refuses to run on an older JVM, with UnsupportedClassVersionError … class file version 69.0, this version of the Java Runtime only recognizes class file versions up to 65.0 (Java 25 bytecode on Java 21). Compile with javac --release 21 to target the older version.

Related formats

.java vs .class vs .jar, and other Java files

FileWhat it isReadable?How it runs
.javaSource codeYes, plain textCompiled by javac, or run directly with java File.java
.classBytecode for one class, starting with CA FE BA BENo, binary; javap -c lists the bytecodejava ClassName on a JVM of the same or a newer version
.jarA ZIP of .class files and resources, with a manifest in META-INF/MANIFEST.MFOpens with any ZIP tooljava -jar app.jar, or double-click
.warA web application packaged as a ZIP for a Java application serverOpens with any ZIP toolDeployed to a server such as Tomcat
.ktKotlin source, another JVM languageYes, plain textCompiled to .class files that can call Java code
.jspA web page with embedded Java, from older web applicationsYes, plain textCompiled and run by the server

Build files sit next to the sources: pom.xml for Maven (XML), build.gradle or build.gradle.kts for Gradle. Settings often live in .properties or YAML files under src/main/resources.

Troubleshooting

The Java errors people hit most

Error messageUsual causeFix
class X is public, should be declared in a file named X.javaThe file name doesn't match the public class, often because of case or a download that renamed itRename the file to X.java, or remove public
cannot find symbolA typo, wrong capitalisation, a missing import, or a class that isn't on the classpathCheck the spelling and imports; build with Maven or Gradle if it's a library
Could not find or load main class Hello.classjava was given a file name; it expects a class namejava Hello, or java Hello.java to run the source
UnsupportedClassVersionError: … class file version 69.0Compiled with a newer JDK than the one running itUpdate the runtime, or compile with --release for the older version
illegal character: '\ufeff'The file was saved with a UTF-8 byte order mark, which javac doesn't acceptSave as UTF-8 without BOM
unmappable character (0xE9) for encoding UTF-8An old Windows-1252 file read as UTF-8 (the default from Java 18)Convert the file to UTF-8, or compile with -encoding windows-1252
'javac' is not recognized as an internal or external commandNo JDK installed, or its bin folder isn't on the PATH (Windows)Install a JDK and reopen the terminal; check with javac -version
incompatible types: possible lossy conversion from double to intA double assigned to an int without a castCast it, (int) value, or use the right type

How to

How to open and edit a .java file, and is it safe?

  • Read it: any text editor opens it: Notepad, TextEdit in plain-text mode, or a browser if it's online.
  • Edit it: IntelliJ IDEA, Eclipse and NetBeans are full Java IDEs; VS Code works with Microsoft's Extension Pack for Java. They compile as you type and underline errors.
  • Format it: IDEs format Java built in; google-java-format and Checkstyle are common in build pipelines.
  • See inside a .class file: javap -c ClassName lists the bytecode; IDEs can decompile it back into readable Java, which is why shipping bytecode doesn't keep code secret.

A .java file is text, and opening it in an editor runs nothing. The risks come later:

  • Running Java code gives it your permissions. As of JDK 24 the Security Manager is permanently disabled, so the JVM itself no longer sandboxes code. Treat an unknown .jar or .java program like any other program, or run it in a container or virtual machine.
  • Builds run code. Gradle build scripts are programs, and Maven runs plugins. Building a project you don't trust can run its code on your computer.
  • Dependencies are other people's code. A build pulls libraries from Maven Central or other repositories; check what you add.

Free downloads

Sample Java files to download

Free sample Java files for testing compilers, IDEs, CI pipelines, syntax highlighters and upload filters. Every sample except the deliberately broken one compiles with javac -Xlint:all -Werror and runs on Java 21 and Java 25, both compiled and with java file.java. The classes aren't public, so the hyphenated file names compile as they are.

sample-program.java · 5.6 KBDownloadOpen
Loading…

What's inside sample-program.java

The file is commented: open it in a text editor and each numbered comment marks one of these parts. Run it with java sample-program.java, or compile it with javac sample-program.java and run java SampleProgram.

  1. Comments 1 and 2: imports and the class

    Five imports, then a final class that isn't public, with a note on why: a public class would need the file to be called SampleProgram.java.

  2. Comments 3 to 5: an enum, a switch expression and a record

    A Category enum with a static method that uses an arrow switch expression, and an Expense record with a compact constructor that rejects negative amounts.

  3. Comments 6 and 8: exceptions

    A checked ParseException that parseLine must declare with throws, and an unchecked NumberFormatException caught and turned into it.

  4. Comments 7 and 9: data and arithmetic

    A text block holds five input lines, one of them invalid. parseCents keeps money in whole cents with Math.multiplyExact, which throws instead of overflowing silently.

  5. Comments 10 to 12: main, generics and streams

    main uses var and List<Expense>, catches the bad line and prints it to standard error, then groups totals with a stream into a TreeMap. Output: €49.75 for Ada Example, €138.90 for Ben Example.

  6. What javac writes

    Compiling produces four class files: SampleProgram.class plus SampleProgram$Category.class, SampleProgram$Expense.class and SampleProgram$ParseException.class for the nested types.

All sample Java files

  • Commented sample program

    sample-program.java · 5.6 KB (5,713 bytes)

    A complete program for Java 17 or later: an enum, a record, a switch expression, a text block, checked and unchecked exceptions, generics, streams and lambdas, with numbered comments explaining each part.

    • Checking a JDK, IDE or CI job compiles and runs Java
    • Teaching the parts of a Java program
  • Java 21 syntax

    sample-java21.java · 3.0 KB (3,066 bytes)

    A sealed interface with three records, a switch with record patterns and when guards, sequenced collections and 1,000 virtual threads. Compiles on Java 21 or later and fails on Java 17, so it shows which Java a tool really uses.

    • Checking parsers, linters and highlighters on current syntax
    • Testing which Java version a build server uses
  • UTF-8 text with CRLF line endings

    sample-unicode-crlf.java · 2.4 KB (2,463 bytes)

    Windows line endings and six sample strings (Latin, Greek, Japanese, Arabic, emoji), saved as UTF-8 without a BOM. Prints length() (UTF-16 units) next to the real character and byte counts, and shows that a text block's line endings become \n.

    • Testing encoding handling in editors, compilers and pipelines
    • Showing why `length()` miscounts emoji
  • Deliberately broken file (does not compile)

    sample-compile-error.java · 1.2 KB (1,228 bytes)

    Clearly labelled at the top: javac reports three errors, the public-class file-name rule, a lossy double to int conversion and a misspelt method, and the comments give the fix for each.

    • Checking how IDEs and CI jobs report compile errors
    • Teaching the most common javac messages

Ways to test with them

  • JDK and CI: compile sample-program.java and sample-java21.java with javac -Xlint:all; both should compile without warnings. sample-compile-error.java should fail with exactly 3 errors and write no class files.
  • Version checks: compile sample-java21.java with javac --release 17. It fails, because pattern matching in switch needs Java 21; with --release 21 it compiles.
  • Encoding: run sample-unicode-crlf.java; the six sample strings should come out readable. A ? instead of letters points at the terminal's encoding, not the file.
  • Locale: run sample-java21.java with -Duser.language=nl; the areas print as 6,00 instead of 6.00, because formatted() follows the locale.

Free to use for testing, teaching and demos, commercially or not, with no attribution needed. A link back to this page is always appreciated.

Put it online

Have a Java file? Give it a link.

Drop a .java file on 99helpers and it gets its own web address. Anyone who opens the link reads the code as plain text in their browser: it is never compiled or run, which makes it a simple way to share code for review, teaching or a bug report.

Questions

Java files, frequently asked

What is a .java file?

A Java source file: plain-text code in the Java programming language. The javac compiler turns it into .class bytecode, which a Java Virtual Machine runs.

How do I run a .java file?

Install a JDK, open a terminal in the file's folder and run java Hello.java (Java 11 or later). Or compile first with javac Hello.java and run java Hello, without the extension.

How do I open a .java file?

Any text editor opens it, since it's plain text. For writing Java, IntelliJ IDEA, Eclipse, NetBeans or VS Code with the Java extensions add completion and error checking.

Why must the file name match the class name?

javac requires a public class to sit in a file with exactly its name, so the compiler and the class loader can find classes by name. Classes that aren't public can sit in any file.

What's the difference between .java and .class files?

A .java file is human-readable source code. A .class file is the compiled bytecode for one class, which the JVM runs. Compiling one .java file can produce several .class files.

Which Java version should I use?

A current long-term support release: Java 25 (September 2025) for new projects, or Java 21. Code compiled for an older version runs on newer ones, not the other way round.

Is Java the same as JavaScript?

No. They are unrelated languages that share part of a name. Java is compiled for the Java Virtual Machine; JavaScript runs in web browsers and Node.js.

Is it safe to open a .java file?

Opening it in an editor is safe: it's text. Compiling and running it gives the code your user's permissions, so only run Java programs and builds you trust.

Related formats

Other file types explained

Keep going

Related

Sources

Last reviewed 27 October 2026.