Chapter 7.J

Java Hello World

Hello World in Java

Subsections of Java Hello World

History of Java

Java Logo Java Logo 1

The Java programming language was originally developed by Sun Microsystems starting in the early 1990s as Oak, a new programming language designed to build upon the ideas of C++. Oak would be object-oriented and include a garbage collector, both things that were seen as weak points of the C++ language at that time. In addition, it would be designed to be portable across many different types of devices.

Eventually, the language was renamed to Java, and was originally used develop applications that could run on a website. These Java applets for the web were very popular in the late 1990s and early 2000s, but most of them have since been replaced by JavaScript code that can run directly in the web browser.

Java vs. JavaScript

While Java and JavaScript may share a common-sounding name, they are in fact completely unrelated languages. JavaScript was originally named Mocha and then LiveScript, but was rebranded to JavaScript in 1995. That move was widely regarded as a marketing ploy to take advantage of the fact that Java was the most popular new language at the time.

In fact, today JavaScript is just one of many implementations of a language standard known as ECMAScript. However, the name confusion still exists.

Since that time, Java has grown into its own fully-fledged programming language, and has indeed met its goal of being highly portable. Java today can run on most major computer operating systems through the use of the Java Runtime Environment (JRE) and Java Virtual Machine (JVM). In addition, the Android mobile operating system uses the Java programming language, and it has been used on many web servers and in consumer electronics.

For software developers, the Java Development Kit (JDK) provides easy access to all of the tools needed to develop programs using the Java language. Once a program is developed, the Java compiler converts the program to Java bytecode, which is similar to machine-code. That Java bytecode can then be run on any compatible platform using the JVM. This allows Java to achieve true portability. The only part of the system that must be specific to the computer’s hardware and operating system is the JVM, while Java bytecode can be used on any system with a compatible JVM installed.

Today, the OpenJDK project handles all development of the Java platform, and the language and all supporting code is free and open source.

If none of these features in the history of Java make any sense at this point, that’s OK! It’s difficult to describe the differences between programming languages without getting technical. However, that is a good thing for us, since nearly every programming language can be used to create the programs we’ll be writing in this course. The differences aren’t really important at this point!

Now that we’ve covered the basics, let’s get right down to it and create our first program in Java!

Resources


  1. File:Java_programming_language_logo.svg. (2018, May 26). Wikipedia. Retrieved 13:46, December 10, 2018 from https://en.wikipedia.org/w/index.php?title=File:Java_programming_language_logo.svg&oldid=872323259↩︎

Hello World

YouTube Video

Video Materials

According to tradition, the first computer program that we cover in any language is a simple program called “Hello World!” The entire goal of the program is to demonstrate what it takes to create our first program from scratch in the language and get to the point where we can print the message of our choice to the screen. While that sounds very simple, it is actually a pretty big first step toward learning how to write our own programs. Let’s get started!

Help!

If this is your first-time programming, it can be quite daunting to know where to get started. This guide will walk you through all the steps to create your first program. However, if you have any questions at all, don’t be afraid to seek help. It’s much easier to answer questions up front when they come up, instead of dealing with them down the road when you are truly lost.

Some Terminology

In any programming language, there is a bit of terminology that we should discuss before diving in. Here are a few terms we’ll want to be familiar with at this point:

  • keyword - in any programming language, a keyword is a word that has a special meaning. These words tell the program exactly what to do, and we cannot use these words as identifiers. Consult the Java Language Keywords list to determine which words are keywords in Java.
  • identifier - any class, method, or variable name is considered an identifier.
  • declaration - in a programming language, we use special lines to declare that something exists. In this example, we’ll see both a class declaration and a method declaration.
  • body - following a declaration, we typically find the body of the declared item. The body is enclosed by braces.
  • braces - in Java, we use braces or curly braces, denoted by { and }, to enclose blocks of code. We’ll use these to enclose both the class body and method body.
Declaration vs. Definition

Formally, a Declaration associates an identifier with a program language element.

public class Pet; 
// a declaration give the name only and
// tells the compiler that there will be a class called Pet
// Java will not support a class declaration this way

A Definition includes the complete information about the program element. So for a class, a definition includes its body.

public class Pet {
     String name = "rover";
     // a definition gives the content of the item; it is
     // like a declaration with all the info about the class
}

Some older languages (notably C) allowed things to be declared and used before they were defined. However, Java does not support this style of coding. As a result, Java documentation and developers tend to use “declaration” for both declaration and definition.

Open a File

To begin, we’ll write our code in a file name HelloWorld.java. If this lesson is being done in Codio or another learning environment, that file may already be open. If not, click on that file in the file tree to the far left to open it. Make sure that file is open for this example, since the file name must match in order for this process to work properly.

Also, we should make sure that the file is completely empty before moving on. If there is any text currently in that file, take the time to delete it now.

We can also do these same steps on a computer with the Java Development Kit installed. Simply create a new, blank text file named HelloWorld.java.

Create a Class

Java is an object-oriented programming language. We’ll discuss this more in detail in a later module, but for now we’ll just need to know that Java requires all of our code to be placed in a class. So, at the very top of our file, we’ll enter the following line:

public class HelloWorld

That line called a class declaration in Java. Let’s break that line down and discuss what each part means:

  1. public - this keyword is used to identify that the item after it should be publicly accessible to all other parts of the program. In a later module, we’ll talk about these keywords, called access modifiers, and the impact they have on our programs. For now, we’ll just use public whenever we need an access modifier, such as in a class declaration.
  2. class - this keyword says that we are declaring a new class.
  3. HelloWorld - this is an identifier that gives us the name of the class we are declaring. Java requires that the class name matches the filename that it is stored in, so we must store the HelloWorld class in a file named HelloWorld.java.

Every Java program must contain at least one class declaration. In fact, each Java file we create will contain at least on class declaration, so we’ll see this structure repeated very often.

Too Much Information?

Unfortunately, when learning to program in Java, there are a few things that we’ll just have to take for granted for now until we learn a bit more about how they actually work. Class declarations are a great example of this. For the next several modules, we’ll just have to include a class declaration at the top of each file without understanding everything about them. As long as we make sure the identifier matches the name of the file, it should work just fine. In fact, in most of the later examples in this book, we’ll have some sample code in each file that includes the class declaration.

We’re covering it in detail here just to make sure it is clear what is going on at first. It’s always better to have too much information than not enough.

Class Body

Once we’ve completed our class declaration, we need to move on to the class body. The class body is where all of the information about the class is stored. In Java, we use braces to enclose a block of code, such as a body. So, let’s modify our file to look like the following example by adding an opening brace { and a closing brace } with a few empty lines in between. Instead of copy-pasting it, try to type it in yourself and see what happens!

public class HelloWorld {
  
  
}

Did you notice that the text editor automatically added a closing brace right after you typed the opening brace? That’s the power of using a text editor that is tailored for programming. It should have also indented all of the lines between the two braces a bit, making it easier to read your code as we continue to fill it in. It may seem a bit jarring a first, but you’ll quickly get used to it. We’ll see it happen again later in this example.

Style Guide

To make your code easier to read, many textbooks and companies use a style guide that defines some of the formatting rules that you should follow in your source code. However, this is a point of contention, and many folks disagree over what is the best format. These formatting rules do not affect the actual code itself, only how easy it is to read.

For this book, most of the examples will be presented in a variant of the K&R Style used by most Java developers, which places the opening brace on the same line as the declaration, but the closing brace is placed on a line by itself and indented at the same level as the declaration. The code inside will be indented by four spaces.

Google provides a comprehensive style guide that is recommended reading if you’d like to learn more about how to format your source code.

Main Method

Inside of our class body, we must create a main method. A method is a piece of code that performs an action in our program. Methods are sometimes referred to as functions or subroutines as well, but we’ll use the term method. Each Java program have one class that contains at least one special method, called the main method, that tells the program where to start. So, let’s modify our file to the left to look like this example:

public class HelloWorld {
  
    public static void main(String[] args){
    
    
    }
  
}

We just added a method declaration and method body to our program! Let’s look at some of the keywords we used here:

  1. public - just like before, we are using the public access modifier to allow any part of our program to access this method.
  2. static - the static keyword is one of the more difficult to understand, and even some experienced programmers struggle with it. In this example, we must use static since this is the main method, which must always be a static method. This is because we aren’t using this method inside of an object, which we’ll cover in a much later module. For now, every method we create will use a static keyword.
  3. void - this describes what kind of data this method should output. Since this is the main method, it cannot output anything to another part of the program, so we use the special void keyword to denote the fact that it doesn’t output anything. (At least, it doesn’t output anything to the rest of the program, but it may display things on the screen!)
  4. main - this is another identifier that gives the name of the method. Since our program needs to have at least one main method, we need to use main as the name of this method.
  5. (String[] args) - following the method name is a section in parentheses that defines the inputs, or parameters, for the method. The main method must take in one parameter, an array of Strings. By convention, we use the identifier args as the name of that parameter. We’ll learn more about parameters, Strings, and arrays, in a later module. For now, we’ll just have to remember that the main method must have this exact set of parameters.

Lastly, we included a second set of braces to enclose the method body. Notice how everything in the class body is indented slightly, making it easy to see the structure of the code.

For now, we’ll just have to memorize the fact that the main method in Java is declared using public static void main(String[] args). As we move through this book, we’ll slowly learn more about each part of that line and what it does, and it will make much more sense.

Saying Hello

Finally, we can write our code. The actual code of our program goes inside the main method’s body, between the two braces. In the classic “Hello World!” example, we simply want to print the words “Hello World!” to the screen. So, let’s modify our program one last time to look like this example:

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

    }

}

As you typed in that information, you might have noticed that the editor also added a second set of quotation marks ", just like it did with the braces earlier. This is another example of a programmer-friendly text editor at work!

Let’s review what we just added to our program:

  1. System.out.println - this line tells us that we’d like to use a method called println in the System.out PrintStream object. Again, that means very little to us right now, but for now we’ll need to know to use this method to print a line of text to the screen. Following the name of the method is a set of parentheses that accepts input to the method, which is what we’d like to have printed to the screen.
  2. "Hello World" - by putting this in the parentheses after System.out.println, we are telling the println method in System.out to print Hello World to the screen. We have to enclose it in quotation marks " so that our program will treat it as a line of text and not more Java code. The values, or variables passed to a method are referred to as the method’s parameters.
  3. ; - each line of code in Java must end with a semicolon ;. This helps the compiler determine where one line of code ends and another begins. They really serve the same purpose as the period . in written English. However, periods are already used for other purposes in Java, so the semicolon became the standard symbol for the end of each line of code.

That’s it! That’s all it takes to write our first program in Java. On the next page, we’ll learn how to actually compile and run this program.

Subsections of Hello World

Compile and Run

YouTube Video

Video Materials

Note: the video's "Run" menu reference is obsolete.

Now that we’ve written our first Java program, we must compile and run the program to see the fruits of our labors. There are many different ways to do so. We’ll discuss each of them in detail here.

Codio vs. Other IDE

This textbook was written for the Codio learning environment, so many of the steps below will reference features in Codio. However, most integrated development environments (IDEs) also include features to compile and run your code, and you can always do so manually using commands in the terminal for your operating system. If you aren’t sure how to get it to work, ask for help!

Terminal

Codio includes a built-in Linux terminal, which allows us to perform actions directly on a command-line interface just like we would on an actual computer running Linux. We can access the Terminal in many ways:

  1. Selecting the Tools menu, then choosing the Terminal option
  2. Pressing SHIFT + ALT + T in any Codio window (you can customize this shortcut in your Codio user preferences)
  3. Pressing the Open Terminal icon in the file tree

Additionally, some pages may already open a terminal window for us in the left-hand pane, as this page so helpfully does. As we can see, we’re never very far away from a terminal.

New to Linux?

No worries! We’ll give you everything you need to know to compile and run your Java programs in this course.

If you’d like to learn a bit more about the Linux terminal and some of the basic commands, feel free to check out this great video on YouTube:

YouTube Video

Let’s go to the terminal window and navigate to our program. When we first open the Terminal window, it should show us a prompt that looks somewhat like this one:

Initial Terminal View Initial Terminal View

There is quite a bit of information there, but we’re interested in the last little bit of the last line, where it says ~/workspace. That is the current directory, or folder, our terminal is looking at, also known as our working directory. We can always find the full location of our working directory by typing the pwd command, short for “Print Working Directory,” in the terminal. Let’s try it now!

Enter this command in the terminal:

pwd

and we should see output similar to this:

pwd Command Output pwd Command Output

In that output, we’ll see that the full path to our working directory is /home/codio/workspace. This is the default location for all of our content in Codio, and its where everything shown in the file tree to the far left is stored. When working in Codio, we’ll always want to store our work in this directory.

Next, let’s use the ls command, short for “LiSt,” to see a list of all of the items in that directory:

~/workspace$ ls
java  README.md

We should see a short list of items appear in the terminal.

We can use the cd command, short for “Change Directory,” to change the working directory. To change to the java directory, type cd into the terminal window, followed by the name of that directory:

~/workspace$ cd java
~/workspace/java$

We are now in the java directory, as we can see by observing the ~/workspace/java on the current line in the terminal. Finally, we can do the ls command again to see the files in that directory:

~/workspace/java$ ls
HelloWorld.java

We should see our HelloWorld.java file! If it doesn’t appear, try using this command to get to the correct directory: cd /home/codio/workspace/java.

Once we’re at the point where we can see the HelloWorld.java file, we can move on to actually compiling and running the program.

Compiling in Terminal

To compile a Java program in the terminal, we’ll use the javac command, short for Java Compiler, followed by the name of the Java file we’d like to compile. So, in our case, we’ll do the following:

javac HelloWorld.java

If it works correctly, we shouldn’t get any additional output. The compiler will look through our Java file and create a new file containing the Java bytecode for our program, called HelloWorld.class. We can use the ls command to see it:

ls

javac Command Output javac Command Output

Problems?

If the javac command gives you any output, or doesn’t create a HelloWorld.class file, that most likely means that your code has an error in it. Go back to the previous page and double-check that the contents of HelloWorld.java exactly match what is shown at the bottom of the page. You can also read the error message output by javac to determine what might be going wrong in your file.

We’ll cover information about simple debugging steps on the next page as well. If you get stuck, now is a great time request help via your course’s help system. You aren’t in this alone!

Running in Terminal

Finally, we can now run our program! Once it is compiled, just type the following in the terminal to run it:

java HelloWorld

java Command Output java Command Output

That’s all there is to it! We’ve now successfully compiled and run our first Java program. Of course, we can run the program as many times as we want by repeating the previous java command. If we make changes to the HelloWorld.java file, we’ll need to recompile it using the previous javac command first. Then, if those changes instruct the computer to do something different, we should see those changes when we run the program after compiling it.

Try It!

See if you can change the HelloWorld.java file to print out a different message. Once you’ve changed it, use the javac and java commands to compile and run the updated program. Make sure you see the correct output!

Codio Assessments

Last, but not least, many of the Codio tutorials and projects in this program will include assessments that we must solve by writing code. Codio can then automatically run the program and check for specific things, such as the correct output, in order to give us a grade. For most of these questions, we’ll be able to make changes to our code as many times as we’d like to get the correct answer.

Subsections of Compile and Run

Debugging

Of course, when developing a computer program, there are always times when things don’t quite work the way we’d like them to. Let’s review a few of the common errors and how to solve them.

Compiler Issues

The Java Compiler is usually the source of most of our woes when first learning how to write programs in Java. The compiler expects the source code to be correctly formatted, or else it won’t be able to generate the Java bytecode for our program. Let’s modify our HelloWorld.java file to include some errors, just to see exactly what the error messages from the compiler are like.

Missing Braces

First, let’s replace everything in HelloWorld.java with the following code:

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

Before compiling that program, can you spot the error? Being able to find errors in code without using a compiler will definitely help you develop programs much faster. It is just like being able to spell words correctly without using a spell-checker. It makes everything go just a bit more smoothly.

In each of the examples in this section, take a minute and see if you can spot the error before running it through the compiler. The quiz in this module includes a few questions that require you to spot the error in a piece of code, so this is great practice for later!

Once we’ve updated that file, we can compile it using the using the terminal. When we do, we should see output similar to this:

Java Missing Closing Brace Java Missing Closing Brace

That error message gives us quite a bit of information. The first part, java/HelloWorld.java tells us which file the error is in, which is handy later on when we start working in programs that include multiple source code files. Following that, we see a 7 after the file name, which tells us that the error is on or around line 7. However, that doesn’t always mean that we’ll need to edit something at line 7 to fix the error; it just means that the Java Compiler realized there was an error when it reached line 7. Sometimes, we must make a change elsewhere in the file to resolve the issue.

After that, we’ll see the actual error message, which in this case is error: reached end of file while parsing. That may not seem very helpful at first, but it actually gives us an important clue.

If we look at the code above, we’ll notice that it is missing the second closing brace } at the end of the file. So, the compiler was expecting to see one more closing brace, but didn’t find it. So, to fix that, we’ll just need to add one more closing brace at the end of the file, and it should work just fine.

Missing Semicolon

Here’s another example we can try:

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

When we try to compile this file, we should get output similar to the following:

Java Missing Semicolon Java Missing Semicolon

In this example, the output is really helpful. It clearly shows us exactly where in our code we forgot to include a semicolon. By adding that symbol where indicated, we can solve the problem.

Runtime Issues

Of course, there are some problems that the compiler may not catch. These are known as runtime errors, since they happen at the time we run our programs. They can be especially tricky to deal with, but thankfully they are usually quite rare.

Incorrect Main Method

Let’s look at one more example:

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

This time, the program actually compiles! However, when we try to actually run the file, we’ll get an error similar to this one:

Java Incorrect Main Method Java Incorrect Main Method

This is because we accidentally forgot the square brackets [] in the main method declaration. It should be public static void main(String[] args), as the error message so helpfully tells us. So, it is important to remember that our programs may still have errors, even if the compiler doesn’t find any.

Break Stuff

Now that you’ve learned a bit about how to debug compiler errors, let’s see if you can figure out how to cause one! Modify HelloWorld.java in a way that causes the compiler to output the following error message:

error: class WrongClass is public, should be declared in a file named WrongClass.java

Subsections of Debugging