CS-WIKI101
Loading...
Searching...
No Matches
compiler

How to compile and run Java programs

Tested on

Operating System Architecture
macOS Sonoma 14.0 M1 chip
Ubuntu server 22.04 M1 chip

Table of contents

Single-file source-code programs

NOTE As a multi-file source-code program you can use Gradle to compile and run complex programs that consist of multiple source-code files. This method is quite advanced and is not recommended for beginners.

JAVAC: Java Compiler

  1. Create a file named HelloWorld.java and copy the following code into it:

    public class HelloWorld {
    public static void main(String[] args) {
    System.out.println("Hello, World!");
    }
    }
  2. Compile the program using the javac command:

    javac HelloWorld.java
  3. Run the program using the java command:

    java HelloWorld

    The program prints the following output:

    single-file-javac-helloworld-output

Multi-file source-code programs

JAVAC: Java Compiler

Project structure:

test/
└── src/
└── com/
└── myproject/
├── Main.java
└── Greet.java

you can create the project structure manually or use the following command to

mkdir -p src/com/myproject
  1. Main.java and Greet.java are located in the src/com/myproject directory.

    Main.java:

    public class Main {
    public static void main(String[] args) {
    Greet.sayHello();
    }
    }

    Greet.java:

    package com.myproject;
    public class Greet {
    public static void sayHello() {
    System.out.println("Hello, World!");
    }
    }
  2. Compile the program using the javac command:

    javac src/com/myproject/*.java
  3. Run the program using the java command:

    java -cp src com.myproject.Main

    The program prints the following output:

    multi-file-javac-helloworld-output

Gradle: Build Automation Tool

NOTE Gradle is quite advanced and is not recommended for beginners. You can use JAVAC: Java Compiler to compile and run simple programs.

For more information, see Gradle User Manual

Need assistance? Check out my discussion board or review the GitHub status page.

© 2023 AppleBoiy • Code of Conduct • [MIT License](LICENSE)

Back to Top