This lesson is still being designed and assembled (Pre-Alpha version)

An Introduction to Java Programming

Your first Java program

Overview

Teaching: 0 min
Exercises: 0 min
Questions
  • What does the simplest program look like in Java?

Objectives
  • Write the most basic program that can run in Java.

  • Identify the different parts of the program and explain their purpose.

  • Know what a class is.

  • Know why we need main(String[] args).

  • Know how to run a Java program (class).

Smallest possible program

We should probably start by defining what a computer program is. A program is a collection of instructions that can be executed by a computer to perform a task. So the smallest possible program would be the smallest number of instructions that we need to perform a task.

We mentioned on our introductory page that Java is a class based and object oriented language. You can think of a class as a “blue print”. If you are an architect and the computer is the builder, then the architect (the programmer) will provide the builder (the computer) with a blue print (the class) to build (instantiate) something (an object).

Let’s create a class called HelloWorld (the blue print). This class will be used to build a program that is going to print “Hello World” on the screen. The name of the file in which the class is saved HAS to be the same as the name of the class ending with the extention .java. Usually we would call this program HelloWorld, but because of the way repl.it works, we have to call it Main. So we have to create a file called Main.java. To the Java compiler it doesn’t matter what you call it but convention is to call it something meaningful so that someone else (or you when you come back to it tomorrow) can infer from the name what it will do.

Create a repl called 01.HelloWorld. Repl.it will create a file called Main.java for you with the following code already entered (without the comments):

1 /** 
2  * Define a class
3  **/
4 class Main {
5 
6   // The entry level to a Java program is a method called ```main```
7   // Don't forget the ```String[] args``` in the parenthesis. 
8   public static void main(String[] args) {
9     // The next line will print the characters between the quotes to the screen
10    System.out.println("Hello World");
11  }
12 }

Let’s look at the program line by line.

  1. The first three lines are comments.
    • You can start a comment block with /** and end it with **/.
    • Everything in between these markers will be considered to be comments.
    • The * at the beginning of the second line is purely for readability.
  2. Line 4 defines the name of the class.
    • By convention, classnames start with a capital letter.
    • The name of the file in which the class is saved must be the same as the class name and it has to end in .java.
  3. Curly braces are used to indicate the beginning and ending of a structure.
    • The left curly brace after the classname, Main, indicates the beginning of the class while the right curly brace on line 12 closes it.
  4. The 5th line is empty. It is used purely for readability, the compiler will ignore any empty lines
  5. Lines 6 and 7 are single line comments. If you start a line with //, the rest of the line will be ignored and considered to be a comment.
  6. It is important to understand line 8. However, trying to explain the meaning of each word in this line will be difficult at this point but it will become clearer as we go through the workshop.
    • main method: The main thing is to know that a Java program needs at least one class with this main method in it. It is like the front door to the program. When you ask the Java Runtime Environment (JRE) to run your program, it will look for this main method.
    • public keyword: The word public tells the JRE that the method is visible outside the class. The meaning of this will become clearer when we write several classes to work together. If it was called private, the method would only be visible to the code inside the class itself.
    • static keyword: We’ll leave the word static for later but it is important to know that it is needed for this specific method.
    • Command line parameters:You also need the String[] args in the curly brackets - it’s meaning will also become clear in the following episodes. As before, the curly braces are used to define the begin and end of a code block, which in this case is a method.

The code now has to be compiled before it can run. In repl.it, above the editor there is a button with the word Run and a small green arrow. Press the button to compile and run the program. In the console, next to the editor, repl.it displays the commands for compiling and running.

> javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -d . Main.java
> java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main
Hello world!
>

You could do all of this manually but usually your IDE, as repl.it is doing now, will take care of it. The first line compiles the program. The second line runs the program and the third line is the output of the program.

Exercise

You can add as many System.out.println statements as you want. Experiment a bit and print some text on the screen.

Solution

class Main {
  public static void main(String[] args) {
    System.out.println("I like to eat my peas with honey;");
    System.out.println("I've done it all my life.");
    System.out.println("It makes the peas taste funny,");
    System.out.println("But it keeps them on the knife.");
 }
}

Press the green Run button.

$ javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -d . Main.java
$ java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main
I eat my peas with honey;
I've done it all my life.
It makes the peas taste funny,
But it keeps them on the knife.

Challenge - Run the program again without compiling it again

The repl.it editor is divided into the left, middle and right panes. The right pane has two tabs, one for the Console and one for the Shell.

  1. Select the Shell tab
  2. You should see the bash prompt:
~/01HelloWorld$
  1. Type ls and enter to get a listing of files in the directory.
  2. You should see two files:
    • Main.class
    • Main.java
  3. Main.class is the compiled version of the program. To run it type the following at the command prompt:
java Main

What happens?

Summary

  1. Java code is organised in classes. A program consists of one or more classes.
  2. One of the classes of a program must have a method called main(String[] args). The JRE needs the main method to run a program.
  3. An object is an instance of a class. When you instantiate a class a chunk of memory is allocated for that object.
  4. By convention classnames start with a capital.
  5. Classes are saved in a file with the same name as the class and with the extension .java.
  6. When a class is compiled, the compiled code will be saved in a filename with the same name as the class but with a .class extension.
  7. To run a java program we type: java ClassName.

Key Points

  • What is a class?

  • What is the purpose of public static void main(String[] args)?

  • What is an object?

  • What does ‘instantiate’ mean?

  • What is the naming convention of classes?

  • What should the filename be in which a class is saved?

  • What will the filename be of a compiled class?

  • How do you run a compiled Java program?


Numbers

Overview

Teaching: 0 min
Exercises: 0 min
Questions
  • How can we print numbers on the screen?

  • When is a number just text and when is it an actual numeric value?

  • How do I do calculations on numbers?

Objectives
  • Distinguish between strings and numbers.

  • Do basic calculations on numbers.

  • Know what an operator is.

What would a programming language be without the ability to manipulate numbers? So let’s try a couple of thing to discover how Java works with numbers and characters.

Start by creating a new repl called 02.Numbers. As before, repl.it will create a file called Main.java for you with the “Hello World” code in it. Change the code to look as follows:

class Main {
  public static void main(String[] args) {
    System.out.println("Print the number ten: 10");
  }
}

When you run the program it should print the following on the screen:

Print the number ten: 10

Exercise

  • Insert the following statement after the third line System.out.println("Print the number ten: " + 10);
    class Main {
    public static void main(String[] args) {
      System.out.println("Print the number ten: 10");
      System.out.println("Print the number ten: " + 10);
    }
    }
    
  • Compile and run the program again.

Does the output of line 3 look different to the output of line 4? What is the difference between the two statements?

Solution

From the user’s point of view there is no difference but, to the compiler there is a difference. Characters that are enclosed in quotes are considered to be a string. In the first case the digits of the number 10 are considered to be characters. Java uses something called Unicode which is a standard for encoding text expressed in most of the world’s writing systems. Each character in Unicode has a unique number. In the second statement the number 10 is not in quotes and is therefore considered to be an integer value. However, the compiler has to convert the number to a string before it can concatenate it to the string in the quotes. The compiler does this automatically.

Let’s try something different. Change your program to look as follows and compile and run it again:

class Main {
  public static void main(String[] args) {
    System.out.println("Print ten plus ten: 10 + 10");
    System.out.println("Print ten plus ten: " + 10 + 10);
    System.out.println("Print ten plus ten: " + (10 + 10));
  }
}
Print ten plus ten: 10 + 10
Print ten plus ten: 1010
Print ten plus ten: 20

Discussion

Why do you think we are getting this output?

Key Points

  • What is a string?

  • What is concatenation?


Variables and Types

Overview

Teaching: 0 min
Exercises: 0 min
Questions
  • What is a variable?

  • What is a type?

Objectives
  • Use variables to store values and do calculations

In computer programming a variable is a symbolic name for a specific area in the computer’s memory where a value is stored. In Java we have to define a variable before we can use it and when we define it, we have to specify the type of information we will be storing in the variable.

In Java we have the following types available which we can use to define what information will be stored in a variable:

In addition to these types, Java provides special support for strings with the String type. Note the capitalisation of the String type. We’ll just mention the reason for the capitalisation but we won’t discuss it in more detail. String is a class whereas the other types we mentioned are known as primitives.

Each of these types use a different amount of memory.

Create a new repl and call it 03.Variables. Enter the following code and compile and run it:

1  // Define the class
2  class Main {
3   // Define the main method
4   public static void main(String[] args) {
5     // Define variables and initialise them with values;
6     String stringVariable = "Print ten plus ten: ";
7     int integerValue = 10;
8     // You can also define a variable without initialising it;
9     int total;
10    System.out.println(stringVariable);
11    System.out.println(stringVariable + integerValue + 10);
12    System.out.println(stringVariable + integerValue + integerValue);
13    System.out.println(stringVariable + (integerValue + integerValue));
14    // Do some multiplication and store the value in the variable total
15    // Storing a value in a variable is called assingment
16    total = integerValue * integerValue * 10;
17    System.out.println("Print the value of total: " + total);
18  }
19}

Print ten plus ten: 
Print ten plus ten: 1010
Print ten plus ten: 1010
Print ten plus ten: 20
Print the value of total: 1000

Let’s look at the program line by line:

  1. The first line is just a comment.
  2. Define the beginning of a class named Main.
  3. Another comment.
  4. Declaring the main method (the front door to the program).
  5. Yet another comment.
  6. String specifies the type of value that will be stored in the variable called stringVariable. The = is an assignment operator. The variable stringVariable will be assigned the value specified to the right of the =, which in this case is Print ten plus ten:.
  7. int specifies the type of value that will be stored in integerValue. The variable integerValue will be assigned the value specified to the right of the =, which in this case is 10.
  8. Another comment.
  9. On this line we declare yet another integer, called total, using the int keyword but we don’t assign a value to the variable.
  10. Print the content of the variable stringVariable to the console.
  11. Convert the number 10 and the integer value stored in integerValue to strings and then concatenate them to the string value stored in stringValue. Print the final string to the console.
  12. Convert the integer value stored in integerValue to a string and then concatenate that twice to the string value stored in stringValue. Print the final string to the console.
  13. Add the integer value stored in integerValue to itself, convert the result to a string and then concatenate that to the string stored in stringAviable. Print the final string to the console.
  14. Another comment
  15. … and yet another comment.
  16. The variable total is assigned the value of the calculation integerValue * integerValue * 10
  17. Convert the integer value stored in total to a string and concatenate it to the string Print the value of total:. Print the final string to the console.
  18. Curly brace to close the main method.
  19. Curly brace to close the class called Main.

Challenge

Before leaving you to experiment with what you have learnt so far we are going to mention a couple more things to make it more interesting.

  • Operators: Operators are characters that are used to perform actions on values.
  • Operators have precedence. That means that some operators have higher precedence than others. Operators with higher precedence are evaluated before operators with lower precedance. Operators on the same level of precedence are evaluated from left to right. Below is a table of operators. The subheadings in the table groups the operators with the same precedence together. The groups are listed according to the precedence order. The closer to the top of the table a group appears, the higher its precedence.

Take the next few minutes and see if you can write some code to do the suggested calculations below. Separate your code with white space and comments. In the next lessons we will then organise our code in a much more efficient way. Don’t just “hard code” values, but use variables and assignments.

  1. Converting fahrenheit to celsius. The formula used for this is: ((fahrenheit - 32) * (5/9))
  2. Converting celsius to fahrenheit. The formula used for this is: ((celsius * 9/5) + 32)
  3. Converting celsius to kelvin: The formula used for this is: (celsius + 273.15)
  4. Converting fahrenheit to kelvin: Can you work this one out yourself by using what you have already done?
Operator Description Example
Postfix    
++ (Increment) Increases the value of operand by 1. B++ gives 21
– (Decrement) Decreases the value of operand by 1. B– gives 19
Multiplicative    
* (Multiplication) Multiplies values on either side of the operator. A * B will give 200
/ (Division) Divides left-hand operand by right-hand operand. B / A will give 2
% (Modulus) Divides left-hand operand by right-hand operand and returns remainder. B % A will give 0
Additive    
+ (Addition) Adds values on either side of the operator. A + B will give 30
- (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10
Assignment    
= (Simple assignment operator) Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C

Key Points


Making Choices

Overview

Teaching: 0 min
Exercises: 0 min
Questions
  • How can a program do different things based on data values?

Objectives
  • Write conditional statements using if, else and else if.

Key Points


Getting Input

Overview

Teaching: 0 min
Exercises: 0 min
Questions
  • How can I enter information into my program via the keyboard?

Objectives
  • Get input from the keyboard using System.in and Scanner.

  • Read the command line parameters.

Key Points


Creating Methods

Overview

Teaching: 0 min
Exercises: 0 min
Questions
  • What is a method?

  • Why create methods?

Objectives
  • Create methods

  • Understand the difference between a void methods and a method with a return.

Key Points


Repeating Actions with Loops

Overview

Teaching: 0 min
Exercises: 0 min
Questions
  • How can I do the same operations on many values?

Objectives
  • Explain what a for loop does.

  • Explain the different parts of the for loop.

Key Points