If you have programming experience in a development environment like Microsoft Visual Studio, you are likely familiar with built-in text editors, menus for compiling and launching programs, and debuggers. However, the JDK is quite different. All tasks are performed by typing commands in a terminal window. While this may seem inconvenient, it is a crucial skill to have.
When you first install Java, it’s important to troubleshoot your installation before setting up a development environment. Additionally, performing these basic steps manually gives you a deeper understanding of the processes a development environment carries out behind the scenes.
The command line provides a simple way to compile and launch Java programs without using an Integrated Development Environment (IDE). This section will walk you through the process of compiling and running a Java program using the command line.
Create a Java Source File
First, create a Java source file (with a .java extension) containing your program. For this example, create a file called HelloWorld.java
with the following content:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Code language: Java (java)
Open the Command Line
Open the command line interface on your computer:
- On Windows: Press Win + R, type cmd, and press Enter.
- On macOS: Press Cmd + Space, type terminal, and press Enter.
- On Linux: Press Ctrl + Alt + T or search for “terminal” in your applications menu.
Navigate to the Java Source File Directory
Using the command line, navigate to the directory containing your Java source file (HelloWorld.java). For example, if your file is in the “Documents” folder, you can navigate to it using the following commands:
- On Windows: cd C:\Users\YourUsername\Documents
- On macOS/Linux: cd /Users/YourUsername/Documents
Replace YourUsername with your actual username.
Compile the Java Source File
To compile the Java source file using the javac command, run:
javac HelloWorld.java
Code language: Java (java)
This command will create a new file called HelloWorld.class in the same directory, containing the compiled bytecode of your Java program.
Run the Compiled Java Program
To launch the compiled Java program, use the java command:
java HelloWorld
Code language: Java (java)
Remember not to include the .class extension when running the java command. The program will execute, and you should see the output “Hello, World!
” in the command line.
Important Points
Keep the following considerations in mind:
When manually typing the program, ensure the accurate use of uppercase and lowercase letters. Specifically, the class name should be “HelloWorld
” rather than “helloworld
” or “HELLOWORLD
.”
The compiler needs a file name (HelloWorld.java
), while running the program requires specifying a class name (HelloWorld
) without a .java or .class extension.
If you encounter messages like “Bad command or file name” or “javac: command not found,
” revisit your installation and carefully review the executable path setting.
If “javac
” indicates it cannot locate the HelloWorld.java file, verify its presence in the directory. On Linux, ensure the proper capitalization is used for HelloWorld.java
.
If you face a java.lang.NoClassDefFoundError
while starting your program, pay close attention to the class name in the error message:
- If the error refers to “helloWorld” (lowercase ‘h’), make sure to enter the ‘java HelloWorld’ command with an uppercase ‘H’. Remember, Java is case-sensitive.
- If the error points to “HelloWorld/java”, it means you mistakenly typed ‘java HelloWorld.java’. Correct the command by entering ‘java HelloWorld’.
If you run ‘java HelloWorld
‘ and the virtual machine fails to find the HelloWorld
class, it might be due to the CLASSPATH environment variable set on your system:
- Setting the CLASSPATH variable globally is not advised, but certain Windows software installers may configure it improperly.
- To fix this issue, follow the same procedure as for adjusting the PATH environment variable. However, this time, remove the CLASSPATH setting instead.
Image Viewer Example
The HelloWorld
program may not have been particularly thrilling. Now, let’s move on to a more engaging graphical application. This new program is a basic image file viewer designed to load and display an image. Just like before, you’ll compile and run the program using the command line.
Create a Java source file (with a .java extension) containing your image viewer program. Name the file ImageViewer.java
and add the following content:
// Import necessary Java AWT and Swing classes
import java.awt.*;
import javax.swing.*;
public class ImageViewer {
public static void main(String[] args) {
// Check if the command-line argument (image path) is provided
if (args.length != 1) {
System.out.println("Usage: java ImageViewer <image file>");
System.exit(1);
}
// Store the image path from the command-line argument
String imagePath = args[0];
// Create and display the GUI on the Event Dispatch Thread (EDT)
SwingUtilities.invokeLater(() -> {
// Create a new JFrame with the title "Image Viewer"
JFrame frame = new JFrame("Image Viewer");
// Set the default close operation for the JFrame to exit the application
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create an ImageIcon from the provided image path
ImageIcon imageIcon = new ImageIcon(imagePath);
// Create a JLabel to display the ImageIcon
JLabel label = new JLabel(imageIcon);
// Create a JScrollPane to allow scrolling if the image is larger than the window
JScrollPane scrollPane = new JScrollPane(label);
// Add the JScrollPane to the JFrame, centered in the BorderLayout
frame.add(scrollPane, BorderLayout.CENTER);
// Resize the JFrame to fit its content
frame.pack();
// Center the JFrame on the screen
frame.setLocationRelativeTo(null);
// Make the JFrame visible
frame.setVisible(true);
});
}
}
Code language: JavaScript (javascript)
This program takes one command-line argument – the path to the image file – and displays it in a simple Swing-based window.
Using the command line, navigate to the directory containing your Java source file (ImageViewer.java
). Then compile the file using the javac
command:
javac ImageViewer.java
Code language: CSS (css)
This command will create a new file called ImageViewer.class containing the compiled bytecode of your Java program.
To launch the compiled Java program, use the java command and provide the path to your image file:
java ImageViewer /path/to/your/image.jpg
Replace /path/to/your/image.jpg
with the actual path to the image file you want to view. The program will execute, and an image viewer window will appear displaying your chosen image. In my case I have an image named cup.jpg in the same folder where I created the ImageViewer.java file.
java ImageViewer cup.jpg
When I executed the program, the image viewer appeared and displayed the image I chose.
This above code demonstrates how to create a simple image viewer using the Java AWT and Swing libraries. It takes an image path as a command-line argument and displays the image in a JFrame
window with a JScrollPane
to enable scrolling if the image is larger than the window.