// Tutorial //

How To Write Your First Program in Java

Published on September 16, 2022
Default avatar
By Toli
Developer and author at DigitalOcean.
How To Write Your First Program in Java

The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

Introduction

Java is a mature and well-designed programming language with a wide range of uses, from being studied in class to running commercial applications of any size. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).

Java achieves high performance because it executes compiled (that is, machine-optimized) code. For developers, this means that you have to compile its source code before you can run it. If you’re used to languages such as PHP and Python, which allow source code to be executed directly, then compiling the code first will be a new step in the development process.

In this tutorial, you’ll create a “Hello, World!” program in Java. The “Hello, World!” program is a classic and time-honored tradition in computer programming. It’s a complete first program for beginners, and it’s a good way to make sure your environment is properly configured. By creating a “Hello, World” program, you’ll start learning Java’s basic syntax as well as the compilation and execution process of a Java program. Once you’re finished, you’ll be able to write and run basic Java code.

Prerequisites

For this tutorial, you will need:

  • Java (version 11 or above) installed on your machine. For Ubuntu and Debian, follow the steps for Option 1 in our tutorial, How To Install Java with Apt on Ubuntu 22.04. For other operating systems, including Mac and Windows, see the download options for Java installation.
  • A compiler provided by the Java Development Kit (JDK). To compile the source code, you’ll use the default Java compiler called javac. You can compile your source either on your local computer or on a remote server in the cloud. For Ubuntu, you can follow the JDK installation instructions in Option 1 from How To Install Java with Apt on Ubuntu 22.04. For other platforms, see Oracle’s JDK Installation Guide or the official instructions for installing OpnJDK version 11 or above.
    • (Optional) A Java Runtime Environment (JRE) that will execute the compiled code. The JRE is part of the JDK, so you don’t have to install it additionally if you have already installed the JDK. Otherwise, you can install the JRE separately. This can be useful if you intend to run your code on a remote server where you don’t want to compile code for security reasons. In this kind of server-oriented scenario, you can download and install the JRE via the native package manager. For Ubuntu and Debian, use sudo apt install openjdk-11-jre. For other distributions, use the respective package managers and search for the keyword jre and choose version 11 or above.
  • A terminal in which to execute commands. Java is well supported on all major operating systems, which means you can follow the instructions on your local computer and use a terminal to connect to a remote server. For guidance on connecting to remote servers, follow our Initial Server Setup Guide.
  • A text editor such as nano. To get started writing Java code, you can use any text editor. However, to code efficiently, consider using an integrated development environment (IDE), such as Eclipse IDE. IDEs are useful because they correct your syntax, autocomplete your code, and allow you to test the code directly, saving you the manual compilation step. However, IDEs are not always intuitive and may confuse you if you haven’t used them before. For your first Java program, it may be easier to use the text editor you are used to.

Writing and Executing the “Hello, World!” Program in Java

For many people, their first Java program is often also their last Java program. The problem is that even the simplest code seems too complex and you have to learn quite a few new things to fully understand it. To avoid this common pitfall, you’ll begin by writing the code, running it, and then seeing how it works.

To get started, create a new directory called hello-world in which to place the code for this tutorial. To create a project directory and change into it, run the following commands in a terminal:

  1. mkdir hello-world
  2. cd hello-world

Next, using nano or your favorite text editor, create a file called Hello.java. For nano, use the following command:

  1. nano Hello.java

Add the following code to your file. It is the bare minimum code for printing a “Hello, World!” message to the console.

hello-world/Hello.java
  1. public class Hello {
  2. public static void main(String[] args) {
  3. System.out.println("Hello, World!");
  4. }
  5. }

This program will print the message Hello, World! to the console. The file name (in this case, Hello with the extension .java) has to match the name of the public class in the source code, which is Hello. Matching the file name and public class name in the source code is a convention of Java. (This is helpful to remember because if you find some useful code, you’ll know how to name the Java source code file.)

Save and close your file. Using nano, press CTRL+X to exit, Y to save, and ENTER to confirm the filename and close the file.

In your terminal, run javac from the same directory where the Hello.java file is located so that the code is compiled:

  1. javac Hello.java

The source Java code has to be compiled using javac with the full file name.

Finally, execute the program with the java executable like this:

  1. java Hello

To execute the compiled code, you have to run java followed by the name of the class (which is Hello in this example). You cannot use any file name extension such as .java or .class when executing the code.

Your output will look like this:

Output
Hello, World!

Your program ran successfully! You created a basic Java program, compiled it, and executed it. Next, you’ll see how it all works.

Understanding the “Hello, World!” Program

If you’re used to writing code in Python or JavaScript, you’ll find that Java has some differences, even in a small program. Every Java program needs at least two things:

  • A class for your code.
  • A main method inside your class.

You need a class because Java is object-oriented, and all code must be a part of a class. Classes are functionally related code. Usually, they do not function on their own but instead serve as templates from which objects are created. An object is a specific instance of a class that can be used within your code. Objects have properties and are able to act when you trigger their methods.

In your program, the class is Hello:

hello-world/Hello.java
  1. public class Hello {
  2. public static void main(String[] args) {
  3. System.out.println("Hello, World!");
  4. }
  5. }

The first line of the code denotes the start of a class. Classes always start with class followed by their name. In this case, the name of the class is Hello, and it matches the name of the file with the .java extension. Then there is an opening curly bracket ({) and a closing curly bracket (}) at the end of the code snippet, inside which you put the code of the class.

The class has an access modifier (which methods also have). In this case, it is public, which means it is fully accessible.

It’s a best practice to use only one class per file, which makes the code easier to read. Still, there is no such official requirement, and you can have an unlimited number of classes inside one single file. There is one catch, though—only one of the classes inside a file can be public, and it should have the same case-sensitive name.

In addition to a class, your program also has a main method. The main method is the starting point of execution for a class—and for this tutorial, for the whole program. It has a very specific syntax: public static void main(String[] args):

hello-world/Hello.java
  1. public class Hello {
  2. public static void main(String[] args) {
  3. System.out.println("Hello, World!");
  4. }
  5. }

public is the access modifier and means that there are no restrictions on calling the method.

static is a special keyword denoting that the method (in this case) or property does not require a new object to be created explicitly in order for you to be able to call it. This has many uses; in particular, it resolves a possible “chicken and egg” situation in which, at some point, some code should be able to create the first object of your program without being part of an object itself.

void is the return type, and it means that nothing is being returned to the caller. In this case, you’ll be printing a message to the screen and thus directly consuming the result of the execution. Although void doesn’t return anything here, in other cases, methods often return a variety of information, such as alphanumeric characters, integers, or objects.

String[] args is the parameter or the input for the main method. A string of characters, or string, stores alphanumeric information. The square brackets ([]) indicate that it’s an array of strings and not only one string. The name of this array is args. In this case, main() doesn’t have any arguments, but if there were any, they’d be contained in this array.

If you miss any of the main method attributes, such as the fact that it is public, you may not get a syntax error, but it will not work as intended (as a starting point).

To print the text to the console, you use the method System.out.println():

hello-world/Hello.java
  1. public class Hello {
  2. public static void main(String[] args) {
  3. System.out.println("Hello, World!");
  4. }
  5. }

A method tells the computer to perform an action. We can tell it is a method because it uses parentheses: (). The method itself is println() and accepts one argument for the text to be printed. System.out precedes the method to specify that the method is part of the core Java (System) functionality for output (out).

In this case, you are using a method from the subpackage out, which is part of the parent package, System. To get a better idea of how classes are organized in Java, imagine that the class hierarchy is similar to that of a file system with parent folders and related dependent subfolders. In Java, these folders are referred to as packages. Related classes are put in one package or subpackage depending on how granular the hierarchy is.

The argument to System.out.println() is a string: "Hello, World!". We know it’s a string because a string is always surrounded by double quotes. In contrast to other languages, such as PHP, single quotes cannot be used for Java strings.

One peculiarity of Java syntax is that it requires a semicolon at the end of each statement, such as the one for printing the text: System.out.println("Hello, world!");.

Note: If you’re using an IDE or a text editor with Java syntax support, you don’t need to worry about missing semicolons because these programs automatically take care of this and other syntax quirks.

In this section, you examined your program line-by-line to understand how it works. In the next section, you’ll take a look at what happens when you compile and run the program.

Compiling and Running the “Hello, World!” Program

In this section, you’ll review what happens when you compile and run your Java program. To compile the code, you used javac from the JDK:

  1. javac Hello.java

javac will read the source code, check it for syntax errors, apply optimizations, and produce a byte code file called Hello.class. A Java .class file is the machine code that the JRE is able to interpret and run.

You can view the Hello.class file by running the ls command from the project directory.

  1. ls

This command lists the files in your current directory:

Output
Hello.class Hello.java

After the code is compiled, you run it with the java executable from the JRE:

  1. java Hello

The JRE runs only compiled code and is not able to execute code from a standard human-readable file in any way. Similarly, if you try to read a compiled .class file with a standard text editor, you won’t be able to. Though, with the help of tools such as the Java Decompiler, you are able to read compiled files, which can be useful when debugging programs for which you don’t have the source code.

With this command, you instruct the JRE executable java to process a class called Hello, which is found in the Hello.class file.

When the Hello, World! message prints to the console, you have confirmed the following:

  • You have a correctly working Java environment in which you are able to compile and execute code.
  • Java has successfully located the code for the Hello class, and it is able to access it.
  • The execution flow started from the main() method. There, the method System.out.println() has been invoked with the string argument Hello, World!. The welcome message has been printed on the screen.
  • Since there is no other code, the program successfully exited.

By invoking java, you start a type of virtual machine called a Java virtual machine (JVM). Check out our article, What is a Virtual Machine? for more general information on virtual machines.

The JVM is well-isolated with no dependencies on the external environment, libraries, or the hosting operating system as a whole. The JVM behaves very similarly, if not exactly the same, on different operating systems, which makes Java portable, predictable, and secure. This is in contrast to other languages such as PHP, where the PHP interpreter relies on many native libraries from the operating system.

Because Java runs its own virtual machine to achieve such isolation, that process consumes quite a few megabytes of memory. However, Java is optimized to manage resources efficiently. Even with the resource consumption involved in running its own virtual machine, Java has excellent performance for large, complex, and long-running programs.

In other words, there may be more easier or more efficient ways to program messages that print to the screen in other languages. But by using Java, you will be well-positioned to create complex programs that are compatible with various operating systems.

Conclusion

Congratulations! You have written your first Java program.

You can continue playing with the code in the Hello.java file and see what happens when you change the text or when you remove the semicolon and get an error. Just make sure to compile the code (javac Hello.java) every time you make changes to the Hello.java file.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up

Tutorial Series: How To Code in Java

Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).

About the authors
Default avatar
Toli

author

Developer and author at DigitalOcean.

Default avatar
Technical Editor

Still looking for an answer?

Was this helpful?
Leave a comment

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!