To build and compile Java code, you write .java source files, run the Java compiler (javac) to turn them into .class bytecode, then run the bytecode with the java launcher. The key condition is that the source must be saved in a file whose name matches the public class and that you compile from the correct directory or set the classpath properly. For anything beyond a single file, you'll want a build tool like Maven or Gradle to handle dependencies, packaging, and repeatable builds.
This guide walks through the whole path: setting up a JDK, compiling by hand, understanding packages and the classpath, packaging a JAR, and moving up to automated builds. Each step includes the failure modes you'll actually hit and a way to confirm it worked.
What "building" and "compiling" actually mean in Java
These two words get used loosely, so it helps to separate them. Compiling is one specific action: javac reads .java source and emits .class files containing JVM bytecode. Building is the umbrella term for everything needed to go from source to something runnable: compiling, resolving dependencies, copying resources, and packaging (usually into a JAR or WAR).
That distinction matters because beginners often expect javac alone to produce a runnable program. It doesn't. It produces class files, and running them is a separate step. Build tools exist because real projects repeat compile-resolve-package dozens of times a day and need it to be identical every time.
A quick note on the toolchain: you need a JDK (Java Development Kit), which includes the compiler, not just a JRE (runtime). If java -version works but javac -version reports "command not found," you've installed a runtime only. That's the single most common setup mistake, and it's worth checking before anything else.
Prerequisites: a JDK, a terminal, and a text editor
Before compiling, confirm three things.
1: A JDK is installed and on your PATH. Run javac -version and java -version. Both should print a version like 17.0.x or 21.0.x. The two should match; a mismatch between compiler and runtime versions causes confusing errors later. 2: You can open a terminal in your project folder. You'll be running commands relative to your source directory, so knowing where you are matters. 3: A plain text editor (or an IDE). An IDE is optional for compiling but makes larger projects far easier to navigate.
You don't need a build tool to start. The manual path below is the foundation; everything else automates it.
Step 1: Write a correctly named source file
Create a file called Hello.java. The name isn't arbitrary: the Java compiler requires a public top-level class to live in a file with exactly the same name, including capitalization.
Two rules to internalize here. First, Java is case-sensitive, so hello.java containing public class Hello fails. Second, the main method signature is fixed: public static void main(String[] args). A typo in that signature compiles fine but produces "Main method not found" at runtime.
Step 2: Compile with javac
From the directory containing the file, run:
Expect a new file, Hello.class, next to the source. If javac returns silently with no output, that's success—the compiler says nothing when it works. That quiet-on-success behavior is a classic source of doubt for newcomers, so check for the .class file rather than looking for a "done" message.
A simple success check: dir on Windows or ls on macOS/Linux should list Hello.class. Then, as a further check, run it (next step).
Step 3: Run the compiled class
Note there's no .class extension and no path separators—you give the class name, not the filename. If you pass java Hello.class, you'll get an error.
You should see:
That's the full loop: write, compile, run. Everything that follows scales this up.
Step 4: Organize code into packages
Real projects group classes into packages to avoid name collisions and to mirror directory structure. A package is declared at the top of the file and maps to a folder.
Create this structure:
src/com/example/Greeter.java:
src/com/example/Main.java:
Compile both files, keeping the package structure in the output:
The -d out flag tells javac to write class files into an out directory, creating the out/com/example/ tree automatically. This mirrors the package structure and is what makes the class files runnable by package name later.
Run it:
The -cp out (classpath) tells the JVM where to find classes, and com.example.Main is the fully qualified class name. Expect Hello, build!.
Why this matters: if you compile without -d, class files land next to your source files, and running with package names gets messy. Using -d into a dedicated output directory is the habit that scales.
Step 5: Understand the classpath and dependency errors
The classpath is the list of locations where the compiler and runtime look for classes. Most "obscure" Java build errors are classpath errors in disguise.
-cp vs. -classpath: they're the same thing. On Windows, separate multiple entries with ;, on macOS/Linux with :. Mixing these up across platforms is a frequent gotcha.
Symptom → cause:
cannot find symbol at compile time: you're referencing a class you didn't compile or a library not on javac's classpath. NoClassDefFoundError or ClassNotFoundException at runtime: the class compiled but isn't where the JVM is looking; your -cp is wrong or missing the compiled output. Main method not found: the main signature is off, or you named the wrong class.
Diagnostic move: print the classpath your tools actually see. For the runtime, java -XshowSettings:properties -version lists it among other settings. Compare that to where your class files and library JARs actually live. Start with reversible checks—adjust the -cp and re-run—before rewriting code.
If you're using external libraries like a JSON parser, you'll download its .jar and add it to both the compile and run classpaths:
Notice the classpath includes both the compiled output and the library. On Windows, swap : for ;.
Step 6: Package into a runnable JAR
When you want to ship one file, package the class files into a JAR (a ZIP with a manifest). The simplest approach:
This runs from the project root, taking everything in out and declaring com.example.Main as the entry point. Run it:
Expect Hello, build! again.
A caveat that trips people up: a JAR with a Main-Class in its manifest runs only if all its dependencies are bundled or resolvable. The java -jar command ignores a -cp flag for the JAR's own needs on some setups and relies on the manifest's Class-Path. Plain jar doesn't bundle dependencies, so a runnable fat JAR usually needs a build tool. If you get NoClassDefFoundError from a library when running java -jar, this is why.
You can inspect a JAR's manifest with jar --describe-module --file greet.jar (for modular JARs) or simply unzip and read META-INF/MANIFEST.MF.
Step 7: Move to a build tool (Maven or Gradle)
Manual javac is fine for learning and for tiny scripts. For anything with dependencies, tests, or a team, use Maven or Gradle. Both wrap the same compiler and JVM but add dependency resolution and lifecycle tasks.
Maven uses a pom.xml and convention-over-configuration. Typical commands:
target/ is Maven's output directory. A default mvn package produces a thin JAR; bundling dependencies requires a plugin like the Maven Shade plugin or Assembly plugin, configured in the POM.
Gradle uses build.gradle (Groovy or Kotlin DSL) and a gradlew wrapper that pins the Gradle version for everyone. Typical commands:
Gradle outputs to build/. The application plugin generates run scripts and a distributable archive.
Choosing between them: both are mature and popular. Maven's rigid lifecycle suits teams that want strict conventions; Gradle's flexibility and faster incremental builds appeal to larger or more customized setups. The trade-off is that Gradle's flexibility lets you build tangled configurations, while Maven's XML can feel verbose. I'd suggest Maven if you want predictability with minimal configuration, and Gradle if you expect to customize heavily. Neither choice is wrong for a typical backend service.
Step 8: Build from source with libraries using Maven
Here's a concrete Maven flow so the abstract steps land. A minimal pom.xml declares the Java version and a dependency:
Place source under src/main/java/com/example/. Run mvn package. Maven downloads declared dependencies from the central repository, compiles everything, runs tests under src/test/java, and writes target/greet-1.0.0.jar. Success check: the JAR exists and java -jar runs it (assuming dependencies are bundled or the app doesn't need them).
The maven.compiler.release property is important: it pins the bytecode target so that a newer JDK still produces classes runnable on the specified version. Without it, you may build on JDK 21 and accidentally require Java 21 at runtime.
Common build failures and how to fix them
Distinguish the symptom from the cause before changing anything.
"class file has wrong version" at runtime. You compiled with a newer JDK than the runtime. Fix: set --release (or the equivalent Maven/Gradle property) to the runtime's version, or run on a matching JRE.
Duplicate classes on the classpath. Two JARs contain the same class; the first wins and behavior is unpredictable. Maven's mvn dependency:tree reveals duplicates. Exclude one via .
Dependency version conflicts. Transitive dependencies pull different versions of a shared library. Build tools resolve to one version by their rules; if behavior breaks, pin the version explicitly.
Encoding errors. Source saved as UTF-8 but compiled with a different default encoding produces mojibake or errors. Set -encoding UTF-8 or the build tool's equivalent.
"package does not exist" despite adding the JAR. Often the JAR is on the compile classpath but not the runtime one, or vice versa. Check both.
Stop condition: if you're debugging classpath or dependency conflicts across a multi-module enterprise build with generated code, custom plugins, and private repositories, and standard isolation steps haven't resolved it, that's a point to bring in a build engineer or the team owning the build infrastructure. Continuing to poke at a complex shared build risks breaking everyone's pipeline.
Automation and reproducibility: CI and wrappers
The final maturity step is making builds repeatable anywhere. Two practices carry most of the weight.
Commit the wrapper. Maven's mvnw/mvnw.cmd and Gradle's gradlew pin the build tool version so a teammate or CI server doesn't need it preinstalled and everyone builds identically. Run ./mvnw package or ./gradlew build rather than relying on a global install.
Let CI build from a clean state. A continuous integration system should run the same compile-test-package sequence on a fresh checkout, catching "works on my machine" problems (missing files, undeclared dependencies, local-only settings). The build command is usually identical to what you run locally.
Verify success the same way every time: the artifact exists at a known path, tests pass, and the produced JAR runs with the expected entry point. Automate that check so a broken build fails loudly instead of shipping silently.
A worked example: from source tree to shipped JAR
Put the pieces together for a small project with one external dependency.
Source lives at src/main/java/com/example/Main.java and Greeter.java. The project needs a hypothetical lib-1.0.jar for, say, parsing configuration. With Maven, you declare the dependency in the POM, and the tool fetches it. The full sequence:
1: mvn clean package — wipes target/, compiles with the pinned release, runs tests, builds the JAR. 2: The Shade plugin bundles dependencies into target/greet-1.0.0.jar, so the manifest's Main-Class points at com.example.Main and no external classpath is needed. 3: java -jar target/greet-1.0.0.jar prints the expected output. 4: In CI, the same command runs on every push; a green check means the artifact is buildable by anyone.
Compare that to the manual route: you'd have to download lib-1.0.jar, remember to put it on both classpaths, hand-write a manifest or use jar --create --main-class, and re-do all of it whenever the dependency updates. The build tool's value is that this becomes a one-line command whose behavior is recorded in a file under version control.
Costs and limits, fairly stated: build tools add configuration surface and a learning curve, and dependency downloads require network access or a mirrored repository. They also hide the underlying javac/java mechanics, which is why learning the manual path first pays off when a build breaks in a way the tool doesn't explain.
Choosing your path
There's no single correct build setup; it depends on scope.
| Scope | Recommended approach | Why |
|---|---|---|
| One file, learning | javac then java | Zero setup; shows the mechanics |
| A few files, one package | javac -d out and java -cp | Still transparent; handles structure |
| Small app, no dependencies | jar --create --main-class | Ships a runnable JAR simply |
| Real project, dependencies, tests | Maven or Gradle | Reproducible, handles libraries and CI |
If you only ever write throwaway scripts, the manual route is genuinely sufficient. If the code will be shared, tested, or shipped, adopt a build tool early rather than migrating a tangle of manual commands later.
The practical rule I'd give: learn the manual javac/java loop until it's boring, then let Maven or Gradle own every project you intend to keep. The compiler is the same either way; the tool just makes the surrounding steps reproducible.
FAQ
Do I need an IDE to compile Java?
No. javac and java are command-line tools, and every IDE ultimately invokes them (or an equivalent compiler API). An IDE helps with navigation, refactoring, and debugging, but it's not required to build.
What's the difference between java Hello and java Hello.class?
java takes a class name, not a filename. java Hello runs the main in class Hello; java Hello.class treats .class as part of the name and fails to find the class. Add the extension only when the class name truly contains it, which is rare.
Why does my JAR fail with NoClassDefFoundError even though java -jar works on the compiled classes?
A plain jar doesn't bundle dependencies and java -jar relies on the manifest's Class-Path, so library classes aren't found at runtime. Bundle dependencies with a shaded/uber JAR (Maven Shade, Gradle Shadow) or supply a correct Class-Path entry.
Can I build a Java project without Maven or Gradle?
Yes. For small projects, javac, java, and jar handle everything. As dependencies and test suites grow, scripting your own build becomes harder to keep reproducible than adopting an established tool.