Compiling and running Java programs (javac, java)
Compiling and running Java programs
Section titled “Compiling and running Java programs”Java uses a two‑step process: compilation to bytecode, then interpretation/JIT execution.
The compiler: javac
Section titled “The compiler: javac”The Java compiler (javac) translates .java source files into .class bytecode files.
Basic usage:
javac MyProgram.javaIf the program has multiple classes, you can compile them all:
javac *.javaCommon options:
-d <directory>– specify where to place generated.classfiles.-classpath/-cp– specify where to find required libraries.
The launcher: java
Section titled “The launcher: java”The Java launcher (java) starts the JVM and executes the bytecode.
Basic usage:
java MyProgramYou pass the class name (without .class). The JVM looks for a public static void main(String[] args) method in that class.
To run a program that resides in a package:
java com.example.MyProgramYou can pass command‑line arguments:
java MyProgram arg1 arg2Inside the program, args contains ["arg1", "arg2"].
Classpath
Section titled “Classpath”The classpath tells javac and java where to find user‑defined classes and libraries. It can be set via the -cp option or the CLASSPATH environment variable.
Example:
javac -cp .:lib/* MyProgram.javajava -cp .:lib/* MyProgramJAR files
Section titled “JAR files”JAR (Java Archive) files bundle multiple classes and resources. You can run an executable JAR with:
java -jar myapp.jarThis requires the JAR’s manifest to specify the main class.