Sub topic 3
Write and Save HelloWorld.java
Write the program
A Java source file is a plain text file containing Java instructions. Open a text editor, type the code below, and save it as HelloWorld.java. Use that exact spelling and capital letters. Check that the file is not named HelloWorld.java.txt.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}A class is a container for Java code. Its name, HelloWorld, must match the file name before .java.
A method is a named set of instructions. Java starts this program at the main method. The line inside it prints the greeting. You do not need to understand every word in the main line yet.
Compile and run
A terminal is a window where you type commands. Open one and move to the folder where you saved HelloWorld.java.
A compiler is a tool that translates source code into a form Java can run. The Java Development Kit (JDK) includes the compiler. Run:
javac HelloWorld.java
java HelloWorldThe first command creates HelloWorld.class. This file contains bytecode, a form of instructions for the Java runtime. The runtime is the software that runs Java programs. The second command starts the program and should print:
Hello, World!The compiler normally prints nothing when it succeeds. For the second command, use the class name without .java or .class.
Fix common problems
- If
javacorjavais not found, check your JDK installation and the steps for making its commands available. Close and reopen the terminal after changing those settings. - If
javaccannot find the source file, check that the terminal is in the right folder and that the file name is exactlyHelloWorld.java. - If you see a compilation error, compare your code with the example. Check capital letters, quotation marks, braces, and the semicolon.
- If Java cannot find
HelloWorld, check that compilation createdHelloWorld.classand that you are running the command from the same folder.
Try an IDE
An integrated development environment (IDE) is an app for writing and running code. It is optional. In an IDE, create a Java project, select your installed JDK, and create a HelloWorld class with the code above. Use the IDE’s run control to see the greeting.
Exercise
What command compiles the file, and what command runs the resulting class?
Show answer
Run javac HelloWorld.java to compile it, then java HelloWorld to run it.