Your first Java program
Overview
Teaching: 0 min
Exercises: 0 minQuestions
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.
- 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.
- You can start a comment block with
- 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
.
- 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.
- The 5th line is empty. It is used purely for readability, the compiler will ignore any empty lines
- 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. - 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 thismain
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 thismain
method.public
keyword: The wordpublic
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 wordstatic
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 theShell
.
- Select the
Shell
tab- You should see the bash prompt:
~/01HelloWorld$
- Type
ls
and enter to get a listing of files in the directory.- You should see two files:
- Main.class
- Main.java
- Main.class is the compiled version of the program. To run it type the following at the command prompt:
java Main
What happens?
Summary
- Java code is organised in classes. A program consists of one or more classes.
- One of the classes of a program must have a method called
main(String[] args)
. The JRE needs themain
method to run a program.- An object is an instance of a class. When you instantiate a class a chunk of memory is allocated for that object.
- By convention classnames start with a capital.
- Classes are saved in a file with the same name as the class and with the extension
.java
.- 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.- 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 minQuestions
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 minQuestions
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:
byte:
stores whole numbers from -128 to 127short:
stores whole numbers from -32768 to 32767int:
stores whole numbers from -231 to 231-1.long
stores whole numbers from -263 to 263-1.float:
stores fractional numbers with 6 to 7 decimal digitsdouble:
stores fractional numbers with 15 decimal digitsboolean:
stores true or falsechar:
stores a single character from UNICODE
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:
- Note: By convention variable names start with lower-case.
- The first line is just a comment.
- Define the beginning of a class named Main.
- Another comment.
- Declaring the main method (the front door to the program).
- Yet another comment.
String
specifies the type of value that will be stored in the variable calledstringVariable
. The=
is an assignment operator. The variablestringVariable
will be assigned the value specified to the right of the=
, which in this case isPrint ten plus ten:
.int
specifies the type of value that will be stored inintegerValue
. The variableintegerValue
will be assigned the value specified to the right of the=
, which in this case is 10.- Another comment.
- On this line we declare yet another integer, called
total
, using theint
keyword but we don’t assign a value to the variable. - Print the content of the variable
stringVariable
to the console. - Convert the number 10 and the integer value stored in
integerValue
to strings and then concatenate them to the string value stored instringValue
. Print the final string to the console. - Convert the integer value stored in
integerValue
to a string and then concatenate that twice to the string value stored instringValue
. Print the final string to the console. - Add the integer value stored in
integerValue
to itself, convert the result to a string and then concatenate that to the string stored instringAviable
. Print the final string to the console. - Another comment
- … and yet another comment.
- The variable
total
is assigned the value of the calculationintegerValue * integerValue * 10
- Convert the integer value stored in
total
to a string and concatenate it to the stringPrint the value of total:
. Print the final string to the console. - Curly brace to close the
main
method. - Curly brace to close the class called
Main
.
Operators
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.
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 |
Challenge
Take the next few minutes and see if you can write some code to do the calculations below.
- Converting fahrenheit to celsius. The formula used for this is: ((fahrenheit - 32) * (5/9))
- Converting celsius to fahrenheit. The formula used for this is: ((celsius * 9/5) + 32)
- Converting celsius to kelvin: The formula used for this is: (celsius + 273.15)
- Converting fahrenheit to kelvin: Can you work this one out yourself by using what you have already done?
Steps:
- make four additional methods in Main; one for each of the calculations that a convert a value into another value. Go ahead and use the existing one as a skeleton (copy-paste) to be modified if you want.
Hints:
- your methods can
return
the converted value.- if methods with the
void
keyword terminates in a void, what might other variable types as method keywords enable the methods to do?- append
f
for float to 273.15 or java won’t compute.Suggestions:
- add more
System.out.println()
statements to explain the conversion by calling your methods with values of your choosing.
- make one method and the accompanying printed explanation until you have made all four calculations.
Solution
class Main { public static void main(String[] args) { System.out.println("Calculate to convert!"); System.out.println(50 + " degrees Fahrenheit is " + fahrenheitToCelcius(50) + " degrees Celcius"); System.out.println(20 + " degrees Celcius is " + celciusToFahrenheit(20) + " degrees Fahrenheit"); System.out.println(10 + " degrees Celcius is " + celciusToKelvin(10) + " degrees Kelvin"); System.out.println(500 + " degrees Fahrenheit is " + fahrenheitToKelvin(500) + " degrees Kelvin"); System.out.println(0 + " degrees Fahrenheit is " + fahrenheitToKelvin(0) + " degrees Kelvin"); } public static float fahrenheitToCelcius(float fahrenheit) { float celcius = (fahrenheit - 32) * 5 / 9; return celcius; } public static float celciusToFahrenheit(float celcius) { float fahrenheit = (celcius * 9 / 5) + 32; return fahrenheit; } public static float celciusToKelvin(float celcius) { float kelvin = celcius + 273.15f; return kelvin; } public static float fahrenheitToKelvin(float fahrenheit) { float celcius = fahrenheitToCelcius(fahrenheit); float kelvin = celciusToKelvin(celcius); return kelvin; } }
Press the green Run button.
Calculate to convert! 50 degrees Fahrenheit is 10.0 degrees Celcius 20 degrees Celcius is 68.0 degrees Fahrenheit 10 degrees Celcius is 283.15 degrees Kelvin 500 degrees Fahrenheit is 533.15 degrees Kelvin 0 degrees Fahrenheit is 255.37222 degrees Kelvin
Key Points
Creating Methods
Overview
Teaching: 0 min
Exercises: 0 minQuestions
What is a method?
Why create methods?
What do method keywords do?
What is the relationship between classes and methods?
Objectives
Create methods with different keywords and in different classes
Key Points
Making Choices
Overview
Teaching: 0 min
Exercises: 0 minQuestions
How can a program do different things based on data values?
Objectives
Write conditional statements using
if
,else
andelse if
.
Key Points
Getting Input
Overview
Teaching: 0 min
Exercises: 0 minQuestions
How can I enter information into my program via the keyboard?
Objectives
Get input from the keyboard using
System.in
andScanner
.Read the command line parameters.
Key Points
Repeating Actions with Loops
Overview
Teaching: 0 min
Exercises: 0 minQuestions
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