You are on page 1of 139

Java for

Beginners University
Greenwich

Computing At
School

DASCO

Chris
Coetzee
Levels of Java coding
• 1: Syntax, laws, variables, output
• 2: Input, calculations, String manipulation
• 3: Selection (IF-ELSE)
• 4: Iteration/Loops (FOR/WHILE)
• 5: Complex algorithms
• 6: Arrays
• 7: Linked Lists
• 8: File management
• 9: Methods
• 9: Objects and classes (missing slides)
• 10: Graphical user interface (GUI) elements
(missing slides)
Syntax, laws, variables, output
3 Laws of Java

1. Every line ends with a ; unless the


next symbol is a {
2. Every { has a }
3. Classes start with capital letters,
methods and variables start with lower
case letters
Java’s structure
Java programs are called ‘classes’
They exist inside a container called a project
All classes have at least one method called main()

Project: CheeseCake

Class: CheeseCake

Method: main()

We write our ‘code’ here


Java class example
Class name

Main method
Variables vs. Value

• A variable is like a box


• What is inside the box can change or ‘vary’
• The ‘thing’ inside the box is the value
5 types of variables

double
int boolean
char

String
Why not have just 1 type?
• Only type big enough to cope with
sentences is Strings
• Strings are BIG compared with
booleans/ints
• To save space, we only use the box
type that is “just big enough” to contain
the value we want.
• Less waste = faster programs!
Strings: “cat” “DA1 2HW”

double
int boolean
char

String
int: 23 0 -98 39290 -321

double
int boolean
char

String
double: 1.2 -5.93 3.3333

double
int boolean
char

String
boolean: true / false

double
int boolean
char

String
char: ‘a’ ‘3’ ‘@’ ‘A’ ‘ ’

double
int boolean
char

String
What data type is each of
the following?
-9 double
4.5 int boolean
chicken char
false
% String
£ 2.90
The cat is hungry now.
192.168.1.190
Declare vs. Instantiate

int number; Declare

number = 3; Instantiate

int number = 3; All in one!


Strings

String name; Declare

name = “Joe”; Instantiate


e!
n on
li
Al
String name = “Joe”;
char

char letter; Declare

letter = ‘a’; Instantiate

char letter = ‘a’; All in one!


double

double price; Declare

price = 2.99; Instantiate


e!
on
l l in
A
double price = 2.99;
boolean

boolean fit; Declare

fit = true; Instantiate


e!
on
l l in
A
boolean fit = true;
Be careful!
true vs “true”
“a” vs ‘a’
“4” vs 4
“2.99” vs 2.99
+ vs ‘+’ vs “+”

Note! Strings cannot do calculations


What does this do?
int num;
num = 23;
System.out.println(23);
System.out.println(num);
System.out.println(“23”);

23
Output 23
23
Combining values and variables

int num1 = 5;
int num2 = 10;
System.out.println(num1+num2);
System.out.println(num1+” + ”+num2);

15
Output 5 + 10
What went wrong?!

String number = “2”;


int zombie = 4;
System.out.println(number+number);
System.out.println(zombie+zombie);

22
Output 8
Input, calculations, String
manipulation
5 types of variables

double
int boolean
char

String
Combining values and variables

int num1 = 5;
int num2 = 10;
System.out.println(num1+num2);
System.out.println(num1+” + ”+num2);

15
Output 5 + 10
Input
• From keyboard?
• From mouse?
• From microphone?
• From scanner?

Links to 2.1.2 (Hardware)


Four and ½ steps to keyboard input

• Import java.util.* BEFORE main()


• Declare a Scanner
• Declare a String variable to catch input
• Use the Scanner to assign input from
keyboard to variable

• Convert to int/char/double (if necessary)

(String) readLine(
import Scanner
variable )
Keyboard input
Important notes:
Input is best received as a String

We use:
String anything = kb.nextLine();

“Green cow”

anything
Converting String to int
To convert String to int, we use a
function called Integer.parseInt( );

Example:
String snumber = kb.nextLine();
int num = Integer.parseInt(snumber);

“123” 123
snumber num
Output
Converting String to double
To convert String to double, we use a
function called Double.parseDouble( );

Example:
String snumber = kb.nextLine();
double price = Double.parseDouble(snumber);

“2.95” 2.95
snumber price
Output
Calculations in Java
Operator Function Example Result
+ Add int i = 10 + 2; 12
- Subtract int j = i – 3; 9
/ Divide double k = j / 3; 3.00
* Multiply int product = i * j; 108
++ Add 1 i++; 13
-- Subtract 1 j--; 8
% Modulus int m = 12 % 5; 2
Good practice
Don’t do calculations and output in the same line:
Work out the answer first
THEN display the answer
What students struggle with
int x = 1;
int y = 3;
x = 3;
int total = x + y; Answer: 6

int h = 4;
h++; Answer: 5

int k = 7;
k = k + 2; Answer: 9
More about Strings
String device = “radio”;

r a d i o
0 1 2 3 4
To get a specific character from a String, we use the
.charAt( ) function

char letter = device.charAt(2);

“radio” ‘d’
device letter
String methods
There are many functions we can use to manipulate
Strings. They are called the ‘String methods’

Method Function Example


returns the char
String colour = “blue”;
.charAt(x) from a specified
index char letter = colour.charAt(0);

returns the String in String name = “bob”;


.toUpperCase() UPPER CASE bob = bob.toUpperCase();

returns the String in String pet = “DOG”;


.toLowerCase() lower case pet = pet.toLowerCase();
returns String
String s = “I love hats”;
.subString(x,y) portion between
two indexes String snip = s.substring(2,6);
returns how many
String h = “radar”;
.length() characters there
are in a String int size = h.length();
Selection (IF-ELSE)
Four and ½ steps to keyboard input

• Import java.util.* BEFORE main()


• Declare a Scanner
• Declare a String variable to catch input
• Use the Scanner to assign input from
keyboard to variable

• Convert to int/char/double (if necessary)

import Scanner (String) variable readLine()


Keyboard input
Calculations in Java
Operator Function Example Result
+ Add int i = 10 + 2; 12
- Subtract int j = i – 3; 9
/ Divide double k = j / 3; 3.00
* Multiply int product = i * j; 108
++ Add 1 i++; 13
-- Subtract 1 j--; 8
% Modulus int m = 12 % 5; 2
String methods
There are many functions we can use to manipulate
Strings. They are called the ‘String methods’

Method Function Example


returns the char
String colour = “blue”;
.charAt(x) from a specified
index char letter = colour.charAt(0);

returns the String in String name = “bob”;


.toUpperCase() UPPER CASE bob = bob.toUpperCase();

returns the String in String pet = “DOG”;


.toLowerCase() lower case pet = pet.toLowerCase();
returns String
String s = “I love hats”;
.subString(x,y) portion between
two indexes String snip = s.substring(2,6);
returns how many
String h = “radar”;
.length() characters there
are in a String int size = h.length();
IF (condition)
Used to change the flow of an algorithm,
dependent on a condition.
if(condition)

Condition is a logic check


something OPERATOR something
Example:

if(num == 3)
Logic operators in Java
Operator Function Example
== equals if(num==3)
(int, double, char, boolean)

.equals() equals
(String)
if(name.equals(“Chris”) )

> greater than if(num>20)


< less than if(num<15)
>= greater than or equal to if(age>=18)
<= less than or equal to if(age<=12)
!= not equal to if(married!=true)

Warning! = does not mean ==


IF example (int comparison)
IF example (String comparison)
What students struggle with

• = and ==
• .equals(“xx”) for Strings
• Putting a ; at the end of if( xx)
▪ if(num > 3); 🗶
▪ if(num > 3) ✔
IF/ELSE (2 outcomes)
IF/ELSE (int example)
Note conditions
if (condition) if (condition)
{ {
something something
} }
else else if (condition)
{ {
something else something else
} }
else
{
Only IF gets a third option
condition }
ELSE does not
AND/OR
• AND in Java: &&
• OR in Java: ||
• Used between conditions
▪ if(num>3&&<12) 🗶
▪ if(num>3)&&(num<12)✔
IF/ELSE (int example with AND)
Switch/Case (IF alternative)
Iteration/Loops (FOR/WHILE)
if(condition)

Condition is a logic check


something OPERATOR something
Example:

if(num == 3)
Logic operators in Java
Operator Function Example
== equals if(num==3)
(int, double, char, boolean)

.equals() equals
(String)
if(name.equals(“Chris”) )

> greater than if(num>20)


< less than if(num<15)
>= greater than or equal to if(age>=18)
<= less than or equal to if(age<=12)
!= not equal to if(married!=true)

Warning! = does not mean ==


AND/OR
• AND in Java: &&
• OR in Java: ||
• Used between conditions
▪ if(num>3&&<12) 🗶
▪ if(num>3)&&(num<12)✔
Types of iteration (loops)

•Iteration
•Fixed number of times
•FOR loop

•Unspecified number of times


•WHILE loop
Can you predict the output?
A logic condition
(like in IF) that has to
be true for the loop to
A simple variable continue.
(usually an int) that Something Operator
allows the loop to Something (usually
‘step through’ involving the counter
Normally called “i” variable)

for(counter; condition; change)


What should happen
to the counter
variable value at the
end of the loop
Usually i++ or i--
Typical example (FOR loop)
Create int called i Continue while i is At end of for loop,
Set i to 0 less than 3 increase i by 1

for(int i = 0; i<3; i++)


{
System.out.println(“X”);
}
X
Output X
X
Another example (FOR loop)
Create int called i Continue while i is At end of for loop,
Set i to 0 less than 5 increase i by 1

for(int i = 0; i<5; i++)


{
System.out.println(i);
}
0
1
Output 2
3
4
Predict the outcome (FOR loop)
What is the counter What is the What change
and starting value? condition? happens?

for(int j = 2; j<10; j=j+2)


{
System.out.println(j);
}
2
Output
?
4
6
8
Students struggle with…
EVERYTHING ABOUT LOOPS
Loops are an abstract construct. Lower
ability students will need a LOT of simple
practice.

Most common mistake:


for(int i = 0; i<5; i++);
FOR example

Can you
spot the
mistake?

Enter your favourite word >


Cheese
Here is Cheese 3 times!
Cheese
Output Cheese
Cheese
Cheese
That’s all folks!
FOR with .charAt(x)

s
p

?
e
c
Output t
r
u
m
Detour: random numbers
It can be very useful to make a random
number in program.
Java has a many ways to do this.
Most common way is Math.random()

Note: This is NOT an examinable bit, but


it does teach logical thinking which IS
examinable.
Making random numbers
Math.random() generates a random
double number between 0 and 1.
e.g. 0.34212… or 0.93813

To make random int numbers between


say 1 and 10 (both included), we need to
use a bit of maths.
Useful formula:
Min+(int)(Math.random()*((Max - Min) + 1))

Write down the minimum number and


maximum number you need, and use the
formula!

So let’s make numbers between 1 and 10:

1 +(int)(Math.random()*((10 - 1) + 1))
FOR with random ints (A)

17

Output
?
17
17
FOR with random ints (B)

19

Output
?
7
12
Example task (advanced)
Write a java program that will generate a
random letter of the alphabet 5 times.
Example output: g u l x e

?
A logic condition
(like in IF) that has to
be true for the loop to
A simple variable continue.
(usually an int) that Something Operator
allows the loop to Something (usually
‘step through’ involving the counter
Normally called “i” variable)

for(counter; condition; change)


What should happen
to the counter
variable value at the
end of the loop
Usually i++ or i--
Complex algorithms
What is the difference?
“Now count from one to
ten…”

Known number of
FOR
repetitions

Loops

Unknown number of
WHILE
repetitions

“Are we there yet?...”


A variable is created
and given a value so
that the loop will run.
Usually String, int or
A logic condition
boolean
(like in IF) that has to
be true for the loop to
continue.
Something Operator
Something (usually
condition variable involving the counter
variable)
while(condition)
change happens inside loop
There must be an
opportunity for the
condition variable to
change, sometimes
done in an IF block
Typical example (while loop)
Create int called i Continue while i is
Set i to 0 less than 3

int i = 0;
while (i < 3)
{
At end of for loop, System.out.println(“gum”);
increase i by 1 i++;
}
gum
Output gum
gum
Another example (while loop)
boolean done = false;
while (done == false)
Create boolean
{
called done.
Set to false System.out.println(“Are you done? Y/N ”)
String answer = kb.nextLine();
if (answer.equals(“Y”) )
Continue while {
done is false done = true;
}
System.out.println(“Goodbye!”);
If user enters Y, }
set done to true

Are you done? Y/N


Y
Output Goodbye!
Students struggle with…
FOR LOOPS – WHILE not so much
Some students will bizarely understand
while loops much easier than for loops.
They can use whichever on they prefer

Most common mistake:


while(done == false);
Practice time
✔ Generate two random numbers between 1 and 10.
✔ Calculate their sum (num1 + num2).
✔ Ask the user for their sum.
✔ If they get it right, the program congratulates them
and ends.
✔ If they get it wrong, the program repeats by
generating two more numbers and asking the user
again…

Make list of
Read problem Draw flowchart Code in Java
sub-tasks
Display
Sum:
num1 and
num1+ num2
num 2

Num2:
random number
between 1 and 10 Ask user
for total

Num1:
random number
between 1 and 10 False if total
= sum

Start True

Display
End Well
done!
Possible solution
boolean done = false;
while (done == false)
{
int num1 = 1 +(int)(Math.random()*((10 - 1) + 1));
int num2 = 1 +(int)(Math.random()*((10 - 1) + 1));
int sum = num1 + num2;
System.out.println(“What is ”+num1+” + “+num2+” ?”);
String answer = kb.nextLine();
int total = Integer.parseInt(answer);
if (total == sum)
{
done = true;
}
}
System.out.println(“Well done!”);
New topics /
we had less
practice before
Arrays/Linked Lists
Arrays vs Variables
Initialising an array
What could go wrong?
num [ 0 ] always OK
num [ 9 ] OK (given the above declaration)
num [ 10 ] illegal (no such cell from this declaration)
num [ -1 ] always NO! (illegal)
num [ 3.5 ] always NO! (illegal)
Array length
• When dealing with arrays, it is advantageous to
know the number of elements contained within the
array, or the array's "length". This length can be
obtained by using the array name followed by
.length. If an array named numbers contains 10
values, the code numbers.length will be 10.

** You must remember that the length of an array


is the number of elements in the array, which is one
more than the largest subscript.

http://mathbits.com/MathBits/Java/arrays/Declare.htm
Parallel arrays
Parallel array applications
Parallel arrays in Java
for(int index = 0; index < dogname.length; index++)
{
System.out.println(dogname[index]);
System.out.println(round1[index]);
System.out.println(round2[index]);
}
Searching an array using a flag
Sorting an array (Bubble Sort)
2D arrays
Declaring a 2D array in Java
int[ ][ ] arrNumbers = new int[6][5];

6 = number of rows (DOWN)


5 = number of columns (ACROSS)
Instantiating a 2D array
Example: Fill a 2D array with “X”

Nothing!
You only put
Output data in, not
printed it!
Common mistake: printing a 2D array

You can’t just print the array name,


You have to print every element in the
array separately!

Output
Correct way: printing a 2D array

Ou
tput
Common 2D array tasks
Linked Lists
Arrays vs Linked Lists

Array List
Fixed size Size can change

One or Two
Only linear
dimensions
Before you using a
Linked List…

Remember to import the utility libraries!

import java.util.*;
Creating a Linked List

Warning: don’t Remember


use double,
int, char or the () at
boolean the end!
Adding items to a linked list

Output
Removing items from a
linked list

Output
Useful LinkedList methods
Method What does it do
Adds xx onto the end of the
.add(xx)
linked list
Removes the element at
.remove(y)
position y
Returns how many elements
.size()
there are in the linked list
Returns what element xx is
.indexOf(xx) stored in; returns -1 if element
was not found
Beware getting the size!
.size() 🡪 Linked Lists
e.g. int k = zones.size(); //zones is a linked list

.length() 🡪 Strings
e.g. int m = name.length(); //name is a String

.length 🡪 arrays
e.g. int g = boxes.length; //boxes is an array
LinkedList example
What did the
programmer
forget to do…?
File management
Files
There are two types of files in
computing:
– Text files (that contain
ASCII/Unicode characters) – e.g.
TXT, CSV
– Random Access Files (that contain
binary objects) – e.g. JPG, MP3
Setting up the file connection

Steps to remember:

1. Import: java.io.*
2. Throw away any IOExceptions (throws
IOException) that could potentially occur in the
main method
Connecting to the file

Steps to remember:

1. First add a File Reader


2. Then add that File Reader to a Buffered Reader
Where do I store the text file?

Store the file in the


MAIN project folder
(not in BIN or in SRC)
How do I read from the file?

ALL INPUT IS ALWAYS STRING!


Useful strategy to know
Sometimes you might want to read in
data like this:
23, 45, 56, 93, 23, 35

Suggested strategy:
1. Read in the line in to a String
2. Split the String into an array
3. Convert the values into ints
In Java that would be:

Which reads as…


1. Read the first line from the file in to a String variable called line.
2. Split the line variable into an String array called tempstringarray
3. Create an integer array called intarr of the same size as
tempstringarray
4. Loop through for all the values in tempstringarray
5. Convert each value from a String to an int and store it in the new integer
array at the same index point.
Writing to a file

No buffer is used
this time.
You write directly
to the file.
In the end, always .close()
Example of adding numbers in a file
Methods
Methods
Methods are smaller chunks of code that
perform a specific function that you might
want to repeat in future

Method rules:
- Starts with a lower case letter
- Ends with a set of brackets: ( )
- Has to say what comes back
Types of methods
• Methods that return a value are called
return type methods.
• You have to specify what type of data
is being returned: int, String, char, etc.
• Methods that don’t return a value are
called void methods.
• Some people call void methods
procedures and return type methods
functions
Summary

•Void methods
•Don’t return a value
•Called procedures

•Return methods
•Returns a specified value
•Called functions
Methods are called from
within the ‘main method’
They are normally
written below the
main method
(but it really doesn’t
matter)
Void method examples
Return method examples
Void methods can be called
on their own line
Return methods should be called
into a receiving container
Common example
What does this
code segment
do?
How does it do it?
Method summary
Useful resource #1

http://mathbits.com/MathBits/Java/Methods/methods.htm
End of slides.

You might also like