This lesson is being piloted (Beta version)

Getting started with Java

Overview

Teaching: 30 min
Exercises: 30 min
Questions
  • What is Java?

  • How do I create my first Java program?

Objectives
  • Understand how Java and the JVM run.

  • Compile and run your first Java program

Pi j1.1 what-is-java from mcollison

Selecting your environment

Hello World is a common and basic first step into programming but this tutorial is about more than the code - it’s about your programming environment. Understanding your programming environment will enable you to be more efficient, understand your workflow and solve problems that you encounter during integration and deployment of your code. There are many choices for your Java development environment and lots of people have strong opinions on which options are best (some call it a war). We’re going to start with a text editor; I recommend starting with Notepad++ although I use Atom.

xkcd text editor cartoon

Once you get started programming, you will soon find that you are generating syntax errors in your code at a faster rate than you can keep up with while executing code from the command line. This is important at first so you can identify the source of your errors, however, at this point you may also want to try an IDE (integrated development environment). An IDE handles much of the packaging, integration and deployment phases of the build lifecycle which also means it can give you prompts about syntax errors in your code and you don’t have to run code from a command-line interface (CLI). A word of warning though, IDEs can cause as many problems as they solve. Once a project becomes sufficiently complex, an IDE can cause dependency conflicts and allow errors to quietly persist. Netbeans is my IDE of choice so if you want to get ahead that is what I’d recommend. 

Running Java in the command-line 

This workshop aims to give you some experience of using the command-line and a text editor for writing straightforward Java programs. If you have any difficulties or don’t understand what you are supposed to be doing or why you are doing it, please don’t hesitate to ask for help in the workshop.

To start, we’ll execute statements in the command-line interface  (CLI a.k.a. terminal) to help navigate this interface. Follow these steps: 

Windows: 

Get a command window by selecting “CMD” from the “All Programs” section of the Windows “Start” menu in the bottom left hand corner. A shortcut is to search for ‘CMD’ and you should find the command prompt. 

Top tip: Powershell is a similar command-line interface on all modern windows distributions with a slightly richer environment and better usability features.  

Mac: 

In applications you will Press cmd + space bar and search for ‘terminal’.  

Top tip: The mac terminal is basically the same commands as a linux command-line interface so if searching for answers online you can often apply answers intended for linux users. 

Linux: 

Open the terminal. If you’re on a linux machine and don’t regularly use the terminal - you’re probably using the wrong OS. 

The text before the prompt (C:\ or a drive name in windows) tells you the “drive” (or device) and the directory (folder) that you are in. The command-line is a way of interacting with the computer. It allows you to invoke programs by typing their names, and is the traditional way of interacting with computers. We are going to use it because it makes clear the distinction between the computer (running Windows), the Java tools (javac and java runtime environment), and your Java programs. 

A couple of useful commands for the console are: 

dir or ls - This shows you the files in the directory or folder that you’re currently in. You’re probably used to looking at these with Windows Explorer, but the same information is (less prettily) available with dir. 

cd Short for “change directory” allows you to change your current directory to another. If in your current directory you have a sub-directory named java, you can change to it with the command cd java. You could then see what files are in it with the command dir. The command cd by itself prints the current directory. 

Directories are arranged as “trees” as is obvious from file explorers. Thus each directory can have several sub-directories (children), but only one parent directory. You can change to the parent using cd .. 

At the command prompt, type:

java -version

You should see the Java version mapped to your environment path printed. If you have a version 1.8 (Java8) or higher you’re good to go otherwise if you see “java: command not found.” you’ll need to download and install a recent Java. 

To install the Java JDK follow the link below: 

[https://www.oracle.com/uk/java/technologies/javase-downloads.html]

Hello Java 

Fire up your text editor - start Notepad++ by selecting it from the main Windows menu. 2. You should an icon that looks like:

notepad++ icon

In order ensure that Notepad++ treats your file as a Java program, use the “Save As” menu to save the (empty) file as a java file (say HelloWorld.java). The .java extension is important, but you can choose whatever name you like; remember the naming conventions lesson - make the name as simple as possible, start iwth an upper case letter and use snake case. Make sure you know which folder you saved the program in. It’s probably best to make a new folder for your PiJ (Programming in Java) work. Once you’ve set the default program to Notepad++ it will then treat all your files in this session as Java; if you open a file with the .java extension, it will automatically be recognised as Java. 4. We’ll start by writing another very short program. Use the editor to write these three lines (but use your own name instead of ’Eric the Unready’): 


// An application to display the message
// "Hello World!" on the screen
public class HelloWorld{
  public static void main(String[] args){
    //Entry point
    //Statements here
    System.out.println("Hello World!");
  }
}

Notice that the editor colours the variables, strings and keywords differently to help you distinguish between them. Save your program to a file - well done you have created a Java class! Your text editor should look something like this: 

text editor view

In the command window, navigate to the directory where you saved the program and check that it’s there. (Recall the notes on cd and dir or ls.) Here’s an example where the file HelloWorld.java is saved and listed in the current directory; you can choose a different directory, of course. 

CLI first.java

As shown in the above picture, you will first need to compile the program by typing (at the command prompt (>) in the console):

javac HelloWorld.java

If this step is successful you should notice that a new file HelloWorld.class has appeared in your current directory. This file contains the java byte code to run your HelloWorld program. Finally, the next step is to use the Java Runtime environment to run your program with the command below:

java HelloWorld

Is the output what you expected?

Editing a Java module 

  1. Attempt to change the HelloWorld program to print “Hello Java workshop” and try compiling and running it again. Also check-in with others in the workshop before progressing on to the last individual task.

  2. Download and run the GreenBottles.java. Find the variable that controls the starting number and change the program so that it starts with 20 green bottles. Modify it again so that it starts with no bottles and counts up to 10 bottles in steps of 3; that is, 0 green bottles, 3 green bottles, 6 green bottles, 9 green bottles.

  3. Go back and modify your HelloWorld program to enable it to use command-line arguments. The code below briefly shows how this can be done. Speak to the workshop lead at this stage to work through how this can be done.


System.out.println( args[0] ) 
</pre>

java HelloWorld Matt
Hello Matt, it's nice to meet you
## Optional programming challenge - if you've programmed before! If you manage to complete all the tasks ahead of others either lend a hand to help debug any issues they're having or have a go at the coding bat warm-up exercises. [https://codingbat.com/java] That's the end of this practical sessison. Most others will be less wordy and more coding but if you have any questions, as always, just ask. Happy coding!

Key Points

  • Java is a general purpose, high-level, compiled, strongly typed, object oriented programming language