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.
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
package 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
import java.time.LocalTime;An import
Lets the file write
LocalTimeinstead ofjava.time.LocalTime. Classes injava.lang, such asStringandSystem, never need importing. - 3
/** Greets people … */A Javadoc comment
Starts with
/**. Thejavadoctool turns these into HTML documentation, and editors show them on hover. - 4
public class Greeter {A public class
Because it's
public, the file must be calledGreeter.java, exactly, including the capital G. A file can hold other classes, but only one public top-level one. - 5
private final String name;A field
Data each
Greeterobject carries.privatehides it from other classes;finalmeans it's set once, in the constructor. - 6
public Greeter(String name) { … }A constructor
Has the class's name and no return type.
new Greeter("Ada")calls it. - 7
public String greet(LocalTime time)A method
Every parameter and return value has a declared type, checked by the compiler.
- 8
public static void main(String[] args)The entry point
Where the program starts.
staticmeans it runs without an object;argsholds the words typed after the class name on the command line. - 9
System.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.
# 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.jarjava Hello.java(Java 11, JEP 330) compiles the file in memory and runs the first class in it. No.classfile 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
.javafiles 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 insrc/test/java, download libraries and build the JAR. - Double-clicking a
.javafile doesn't run it: it opens in an editor. A.jarfile can run on double-click if a Java runtime is installed.
app/
├── Main.java class Main uses Helper
└── Helper.java class Helper
java app/Main.java # Java 22+: also finds and compiles Helper.javaRules
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.javais the wrong name forGreeter, even on Windows and macOS, whose file systems ignore case for most other purposes. - Packages map to folders.
package com.example.greet;belongs incom/example/greet/.javac -d outwritesout/com/example/greet/Greeter.class, and you run it by its full name,com.example.greet.Greeter. From Java 22,java Greeter.javachecks this too and stops withend of path to source file does not match its package nameif the folders are wrong. - One source file, several class files. Every class, including nested ones, gets its own
.classfile:Outer$Inner.classfor a class insideOuter. - Non-public classes have no naming rule. A class without
publiccan sit in a file of any name. The samples on this page use that, because a file calledsample-program.javacan't hold a public class: the hyphen makes it an invalid class name. - Two names are reserved for special files:
module-info.javadeclares a module, andpackage-info.javadocuments 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.
| Version | Released | Class file version | Notable for |
|---|---|---|---|
| Java 8 (LTS) | March 2014 | 52 | Lambdas and streams. Still found in older systems |
| Java 11 (LTS) | September 2018 | 55 | java Hello.java runs a source file directly |
| Java 17 (LTS) | September 2021 | 61 | Records, text blocks, switch expressions and sealed classes all available |
| Java 21 (LTS) | September 2023 | 65 | Virtual threads, pattern matching for switch, record patterns, sequenced collections |
| Java 22 | March 2024 | 66 | Running a program spread over several source files with java |
| Java 25 (LTS) | September 2025 | 69 | Compact 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: 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
| File | What it is | Readable? | How it runs |
|---|---|---|---|
.java | Source code | Yes, plain text | Compiled by javac, or run directly with java File.java |
.class | Bytecode for one class, starting with CA FE BA BE | No, binary; javap -c lists the bytecode | java ClassName on a JVM of the same or a newer version |
.jar | A ZIP of .class files and resources, with a manifest in META-INF/MANIFEST.MF | Opens with any ZIP tool | java -jar app.jar, or double-click |
.war | A web application packaged as a ZIP for a Java application server | Opens with any ZIP tool | Deployed to a server such as Tomcat |
.kt | Kotlin source, another JVM language | Yes, plain text | Compiled to .class files that can call Java code |
.jsp | A web page with embedded Java, from older web applications | Yes, plain text | Compiled 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 message | Usual cause | Fix |
|---|---|---|
| class X is public, should be declared in a file named X.java | The file name doesn't match the public class, often because of case or a download that renamed it | Rename the file to X.java, or remove public |
| cannot find symbol | A typo, wrong capitalisation, a missing import, or a class that isn't on the classpath | Check the spelling and imports; build with Maven or Gradle if it's a library |
| Could not find or load main class Hello.class | java was given a file name; it expects a class name | java Hello, or java Hello.java to run the source |
| UnsupportedClassVersionError: … class file version 69.0 | Compiled with a newer JDK than the one running it | Update 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 accept | Save as UTF-8 without BOM |
| unmappable character (0xE9) for encoding UTF-8 | An 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 command | No 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 int | A double assigned to an int without a cast | Cast 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
.classfile:javap -c ClassNamelists 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
.jaror.javaprogram 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.
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.
Comments 1 and 2: imports and the class
Five imports, then a
final classthat isn't public, with a note on why: a public class would need the file to be calledSampleProgram.java.Comments 3 to 5: an enum, a switch expression and a record
A
Categoryenum with a static method that uses an arrowswitchexpression, and anExpenserecord with a compact constructor that rejects negative amounts.Comments 6 and 8: exceptions
A checked
ParseExceptionthatparseLinemust declare withthrows, and an uncheckedNumberFormatExceptioncaught and turned into it.Comments 7 and 9: data and arithmetic
A text block holds five input lines, one of them invalid.
parseCentskeeps money in whole cents withMath.multiplyExact, which throws instead of overflowing silently.Comments 10 to 12: main, generics and streams
mainusesvarandList<Expense>, catches the bad line and prints it to standard error, then groups totals with a stream into aTreeMap. Output: €49.75 for Ada Example, €138.90 for Ben Example.What javac writes
Compiling produces four class files:
SampleProgram.classplusSampleProgram$Category.class,SampleProgram$Expense.classandSampleProgram$ParseException.classfor 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
switchwith record patterns andwhenguards, 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:
javacreports three errors, the public-class file-name rule, a lossydoubletointconversion 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.javaandsample-java21.javawithjavac -Xlint:all; both should compile without warnings.sample-compile-error.javashould fail with exactly 3 errors and write no class files. - Version checks: compile
sample-java21.javawithjavac --release 17. It fails, because pattern matching inswitchneeds Java 21; with--release 21it 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.javawith-Duser.language=nl; the areas print as6,00instead of6.00, becauseformatted()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
- Java Language Specification, chapter 7: packages and compilation units
- JEP 330: Launch Single-File Source-Code Programs
- JEP 458: Launch Multi-File Source-Code Programs
- InfoQ: JEP 512, compact source files finalised for JDK 25
- Oracle Java SE Support Roadmap
- JEP 400: UTF-8 by Default
Last reviewed 27 October 2026.