Skip to main content

Command Palette

Search for a command to run...

Running Java Code from the Terminal and How to Do It

In the world of Java development, tools like IDEs often dominate the landscape, offering convenience and automation. Yet, understanding how to run Java code from the terminal remains an invaluable skill for any developer. It not only reinforces a...

Published
5 min read
Running Java Code from the Terminal and How to Do It
T

I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.

1. Why Should You Learn to Execute Java Code from the Terminal?

Understanding how to execute Java code from the terminal is more than just a legacy skill; it's a crucial capability with practical applications.

1.1. Mastering the Java Runtime Environment (JRE)

Running Java code via the terminal exposes you to the underlying mechanics of how Java compiles and runs programs. By manually invoking the compiler (javac) and the interpreter (java), you understand how Java bytecode is executed.

1.2. Essential for Headless Environments

In server-side or containerized environments, you might not have access to a GUI. Terminal-based Java execution ensures you can still compile and run your programs in these scenarios.

1.3. Lightweight and Efficient Workflow

For small programs or quick tests, using the terminal can be faster than booting up a heavy IDE. It also avoids unnecessary background processes, making your development lean and efficient.

2. Step-by-Step Guide to Running Java Code from the Terminal

To run Java programs from the terminal, follow these steps. Each step includes commands, code, and detailed explanations.

2.1. Setting Up Your Environment

Before anything, ensure that the Java Development Kit (JDK) is installed and correctly configured.

Install JDK:

Download and install the JDK from the Oracle website or use OpenJDK.

Verify the installation:

java -version
javac -version

Explanation: The java -version command checks if the Java Runtime Environment is available, while javac -version ensures the compiler is accessible.

Set Environment Variables:

Ensure the JAVA_HOME variable points to the JDK installation directory.

Add the bin directory to your system's PATH variable.

Example configuration for Linux:

export JAVA_HOME=/usr/lib/jvm/java-17-openjdk
export PATH=$JAVA_HOME/bin:$PATH

Explanation: These settings ensure you can invoke java and javac commands from anywhere in the terminal.

2.2. Writing a Java Program

Create a simple Java program. Save it as HelloWorld.java:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Explanation: This program consists of a single class with a main method that serves as the entry point for execution.

2.3. Compiling the Java Program

To compile the Java program, use the javac command:

javac HelloWorld.java

Explanation: The javac command compiles the source code into bytecode and generates a .class file (e.g., HelloWorld.class). This file contains the platform-independent bytecode executable by the JVM.

Common issues during compilation:

  • Error: File not found: Ensure the file name matches the class name.
  • Error: Unsupported major.minor version: Verify that the JDK version matches the version used for compiling.

2.4. Running the Compiled Java Program

Run the program using the java command:

java HelloWorld

Output:

Hello, World!

Explanation: The java command invokes the Java Virtual Machine (JVM) to execute the bytecode. Note that you don't include the .class extension when running the program.

3. Advanced Concepts and Applications

Once you understand the basics, you can explore more advanced use cases.

3.1. Running Programs with Command-Line Arguments

Modify the program to accept command-line arguments:

public class HelloWorld {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Hello, " + args[0] + "!");
} else {
System.out.println("Hello, World!");
}
}
}

Compile and run:

javac HelloWorld.java
java HelloWorld Alice

Output:

Hello, Alice!

Explanation: The args array captures command-line arguments passed during execution, making your program more dynamic.

Create a second class:

public class Greeting {
public static String getGreeting(String name) {
return "Hello, " + name + "!";
}
}

Update HelloWorld to use the Greeting class:

public class HelloWorld {
public static void main(String[] args) {
String name = args.length > 0 ? args[0] : "World";
System.out.println(Greeting.getGreeting(name));
}
}

Compile both classes:

javac HelloWorld.java Greeting.java

Run the program:

java HelloWorld Bob

Output:

Hello, Bob!

Explanation: Java allows multiple classes to interact, provided they are compiled and located in the same directory or a specified classpath.

3.3. Using Packages

Organize classes into packages for better structure:

Create directories:

mkdir -p com/example

Save HelloWorld.java and Greeting.java in com/example and add the package declaration:

package com.example;

public class HelloWorld {
public static void main(String[] args) {
String name = args.length > 0 ? args[0] : "World";
System.out.println(Greeting.getGreeting(name));
}
}

and

package com.example;

public class Greeting {
public static String getGreeting(String name) {
return "Hello, " + name + "!";
}
}

Compile:

javac com/example/*.java

Run:

java com.example.HelloWorld Alice

Explanation: Packages provide a namespace, preventing name conflicts and enabling modular programming.

3.4. Setting Classpaths

If your classes are distributed across directories, use the -cp option to set the classpath. For example:

java -cp /path/to/classes com.example.HelloWorld

Explanation: The classpath specifies where the JVM should look for classes during runtime.

4. Conclusion

Running Java code from the terminal offers unmatched insights into how Java operates, making it an essential skill for developers. Whether you're troubleshooting, working in headless environments, or simply seeking efficiency, these techniques form a cornerstone of Java mastery. If you have questions or want to share your experiences, leave a comment below—we’d love to hear from you!

Read more at : Running Java Code from the Terminal and How to Do It

More from this blog

T

tuanh.net

540 posts

Are you ready to elevate your Java, OOP, Spring, and DevOps skills? Look no further!