Wednesday, May 31, 2017

First Java Program

With the Java JDK installed from the last post, we are finally ready to create our first Java application. The only other thing we'll need is a text editor, which comes preinstalled on every major operating system. Windows comes with Notepad, Macs come with TextEdit, and Linux comes with a variety of editors, such as Vim, Emacs, and Nano. While these editors are a great starting point, they have some limitations. Notepad, TextEdit, and Nano don't come with many features needed for everyday programming. Vim and Emacs have a fairly steep learning curve for new users. You may want to try out a programming text editor, such as Visual Studio Code, Sublime Text, or Atom. A programming text editor is specifically designed for writing software applications, and it comes with useful features such as syntax highlighting, line numbering, easy file navigation, etc. I may give a detailed comparison of the different programming text editors in a future post, but for now try installing them and viewing the online documentation if you're interested. These editors are also good when using other programming languages, such as JavaScript, so you will be able to learning a valuable skill.

Once you've chosen your editor, we're ready to begin writing our first Java program! First, create a new directory, which will contain all of our Java code. I called mine "Code" for simplicity. Next, create a "HelloWorld" directory inside of the one you just created. Hello World is the name of a simple program used when learning a new programming language. The goal is to simply print the words "Hello World" to the console. If you're interested, check out http://wiki.c2.com/?HelloWorldInManyProgrammingLanguages to see the HelloWorld program in other languages. Now, create a file called HelloWorld.java inside the HelloWorld directory. Java programs are just text documents with the extension .java at the end. The following diagram shows the directories and HelloWorld.java file that I created on my Mac:



I created a subfolder called "JavaSamplePrograms" to hold these tutorial programs. Don't worry about the HelloWorld.class file for now, we'll come to that in a minute. Once the HelloWorld.java file is created, open it in a text editor and copy the following code into there:

public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!");
        System.out.println("This is my first program!");
    }
}

This may look a bit overwhelming at first, but we'll take a deeper look at the program in a minute. And by the end of the next few posts, you'll have a good understanding of the basic concepts behind this program.

To run this program, open up a command line and navigate to the directory where you created the HelloWorld.java file. This can be accomplished by using a command such as "cd C:/Code/JavaSamplePrograms/HelloWorld" on a Windows machine. Now type "javac HelloWorld.java" and hit enter. If everything goes well, you should now see the HelloWorld.class file in the directory. This is the bytecode that our Java program got compiled into. If you get an error that the javac command wasn't found, that means the jdk wasn't installed properly. Check the previous post for details, or try searching for "javac command not found" online. If you get an error saying that something is wrong in the program, double check that everything was copied exactly as it appears above. Finally, we need to run the compiled HelloWorld.class file. To do this, type "java HelloWorld" and press enter. You should not enter "java HelloWorld.class", as the .class portion is implicit. If you do, you will get an error. After running the HelloWorld program, you should see the following output on the console:

Hello World!
This is my first program!

The following diagram shows how I created and ran the HelloWorld program on my computer. The output of the programming is outlined in red:



Congratulations! You have successfully compiled and ran your first java program. Although this seems like a lot of steps for a first program, there are tools to simplify creating Java applications. The main tool is called an Integrated Development Environment (IDE), which has a nice code editor, file explorer, console for running programs, etc. We'll take a detailed look at using an IDE and how it makes programming easier in the next post.

Now that you created your first program, let's take a brief look at how it works. This will be explained in detail over the course of the next few posts, so don't worry if things aren't really clear at this point. The first line:

public class HelloWorld

Says that we are creating a new Java class called HelloWorld. Java is an object oriented programming language, and the way we define these objects is by creating classes. We'll take a much deeper look at classes in a later section. For now, just know that nearly all Java files that you create will contain a class. The next line is an "{", also called an opening curly brace. This punctuation is used to start a block of code, which is a section of code that serves a single purpose. In this case, the "{" says that everything inside of it is part of the HelloWorld class. All "{" characters must have a matching "}" closing brace character that says where the block ends. In this case, the last line of the program closes out the block. It is an error to open a block using "{" but forgetting to close it using "}". IDEs help by automatically adding a closing brace every time an opening brace is entered.

The third line of the programming is the most overwhelming:

public static void main(String[] args)

Is used to add something known as a method. Methods are used inside of a class to do something, such as adding two numbers, displaying some text on the console, or predicting who will win the next Super Bowl. Any piece of functionality you can think of will usually go inside of a method. The method must also be given a name. In this case the name of the method is main. You should usually give the method a descriptive name, such as addTwoNumbers or predictSuperBowlOutcome, so it is clear to other programmers what the method does. The main method is special, as it tells the Java Runtime Environment (JRE) that this is the entry point of the application. In other words, when you run a Java program, it looks for a method named main and runs all of the code inside of that. Your program must include a main method, or else the JRE won't know how to start the program, and you'll get an error. There's a lot else going on in this line, but for now just know that the main method is what gets run when you start a Java program. In the first few posts, we'll write everything inside the main method, and later on we'll learn how to structure our code by adding our own custom classes and methods.

Line 4 is another opening brace, which says that everything inside of it belongs to the main method. Line 7 closes out the main method. Lines 5 and 6 are where all of the action takes place. They both do similar things, so let's take a look at line 5:

System.out.println("Hello World!");

Is used to display the text "Hello World!" without the quotes on the console. System.out.println is a method provided to us by the Java language to display text on the screen. Without that method, we'd have to understand how our operating system works and how to get it do display text on the console. That would be pretty difficult to do. This is one way object oriented programming makes our code easier to understand. We don't need to know all of the underlying details about how a method works. In this case, we know the what (print "Hello World!" to the console), but not the how (call the operating system and get it to display the letters H, e, l, l, o, etc). So for now, all you need to know is that in order to display some text on the console, you call System.out.println(), and give it the text to display inside of quotes.

With that, we have a high level understanding of how our first program works. Don't worry if a lot of it is still unclear at this point. Java programs have a lot of terminology that we need to understand before we really know what's going on. These concepts will become much clearer in the next posts. Also, there are tools that make it much easier to write and run Java programs. We'll take a look at one of these tools in the next post and see how it makes our job easier.

No comments:

Post a Comment