Java Hello World
Hello World in Java
Hello World in Java
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.
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!
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. âŠď¸
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!
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.
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:
{
and }
, to enclose blocks of code. Weâll use these to enclose both the class body and method body.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.
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
.
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:
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.class
- this keyword says that we are declaring a new class.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.
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.
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.
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.
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:
public
- just like before, we are using the public
access modifier to allow any part of our program to access this method.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.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!)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.(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.
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:
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."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.;
- 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.
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.
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!
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:
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.
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:
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:
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:
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.
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
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!
Finally, we can now run our program! Once it is compiled, just type the following in the terminal to run it:
java HelloWorld
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.
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!
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.
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.
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.
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");
}
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:
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.
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:
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.
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.
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:
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.
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