Getting Started With Java

Java is one of the most popular programming languages in the world. Let’s see what Java programs look like, and learn how to write and run simple Java applications on a desktop or laptop computer.

Try It Online!

An old tradition holds that one’s first encounter with a new programming language should begin with writing a program to announce Hello, world. In Java, the program looks like this:

class Greeter {
    public static void main(String[] args) {
        System.out.println("Hello, world");
    }
}

You can run Java programs online at a variety of places. For now, just go to the Java runner at Tio.run and enter and run the program above into the “Code” box. You should see something like this:

tio-java.png

Exercise: To get experience with the runner, try introducing typos into the code and see what happens when you run the code. Next, try printing slightly different messages. See if emojis work in the code.

Download Java to Your Own Machine

Online runners are great for trying things out, but to build large systems, you will need to build programs on your own computer. To develop Java programs, you will need to download and install a Java Development Kit (JDK).

CLASSWORK
Download and install now, if you haven’t already. The actual installation process will vary from machine to machine, so do your best to follow whatever instructions you can find to complete the installation process. Don’t be afraid to ask for help.

Once a JDK is downloaded and installed, we can write programs and run them from the command line. First, let’s make sure your download went okay and that the main tools are installed. On the command line, enter these two commands:

These commands will show the version of Java installed on your box, something like this:

$ javac -version
javac 17
$ java -version
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)
$ jshell -version
jshell 17
Stay up to Date

You should have at least version 17 for these tools. If you have anything older, update!

Run Java on the Command Line

Now, make a new folder for writing our first programs. In this new folder, create a file called Greeter.java containing the Java program above. The class name Greeter has to be the same as the first part of the filename Greeter.java. (Those are the rules, people.) Once you have the file, you will first compile then run the program:

$ javac Greeter.java

$ java Greeter
Hello, world

You can run both commands on the same line like this:

$ javac Greeter.java && java Greeter
Hello, world

Recall that && means run the first command, and then, only if the first command succeeded, run the second.

What exactly is going on here? javac is the command to compile Java source code files. It reads .java files and produces .class files.

java is the command to run class files. Give this command the name of a class file (together with any command line arguments) and the command will run the program starting at the public static void main method.

Greeter.java
javac
Greeter.class
java
Program Running
Exercise: List the contents of your folder after running javac. Locate the Greeter.class file.
Do I really have to do both javac and java?

If your entire program fits in just one .java file, then no. For our program above, we could have just written

    java Greeter.java
However, most real life programs have multiple files, so that short cut does not work: you will have to javac each one of them. So you might as well get in the habit of running both commands.

Now of course your development environment will probably just have a button to just run the whole giant project; however, the command line will always be there, so get used to it too.

Let Your Editor Help You

It’s most helpful to use a modern editor like Code, in which you should install some good packages that can check and clean your code while you type (or whenever you save a file). Please install these packages; there is no pride in suffering through the discovery of typos through strange error messages in a console! Let your editor mark whatever problems it can, so you can fix trivial problems without leaving the editor. A good Java package can also give you type-ahead suggestions, which saves sooooooo much time.

CLASSWORK
The instructor and TAs will help you configure your environment during class. We will be using Visual Studio Code with: Extension Pack for Java and SonarLint.

Command Line Arguments

Let’s modify the program so that if a command line argument is present, we’ll assume it is a name to greet. If no argument is given, we’ll just say hello to the world. Command line arguments are passed to your program in the array argument to main:

class Greeter {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Hello, world");
        } else if (args.length == 1) {
            System.out.println("Hello, " + args[0]);
        } else {
            System.err.println("Program requires either zero or one argument");
        }
    }
}

Let’s try it out:

$ javac Greeter.java && java Greeter
Hello, world
$ javac Greeter.java && java Greeter Alice
Hello, Alice
$ javac Greeter.java && java Greeter Jane Doe
Program requires either zero or one argument
$ javac Greeter.java && java Greeter 'Jane Doe'
Hello, Jane Doe
Exercise: If you are new to Java, the effort of typing this program, saving it, and going through the motions of compiling and running is a good warmup. Give it a shot if you have time and feel the need for the warmup.

JShell

In addition to the javac and java commands, the JDK has a wonderful little tool called jshell, which lets you run little snippets of Java; it’s amazing for learning and experimenting. Even the most advanced Java programmers will “drop into the shell” to try out new things are see if their hunches are correct. We’ll work with this extensively in class, but for now, here’s a taste (don’t worry about understanding every line for now):

$ jshell
|  Welcome to JShell -- Version 17
|  For an introduction type: /help intro

jshell> 8 - 2 * 5
$1 ==> -2

jshell> "Hello".startsWith("Hell")
$2 ==> true

jshell> int triple(int x) {
   ...>     return x * 3;
   ...> }
|  created method triple(int)

jshell> triple(30)
$4 ==> 90

jshell> $4 * 2
$5 ==> 180

jshell> IntStream.range(1, 5).forEach(System.out::println)
1
2
3
4

jshell> /exit
|  Goodbye

Summary

We’ve covered:

  • Running Java programs at tio.run
  • Downloading a JDK
  • Writing and running Java programs on your own machine
  • Working with command line arguments
  • Executing Java code in JShell