You are on page 1of 66

ICS4U - Java

1. Getting Started with JAVA:


You will have to install 2 programs:

Download and install the Java Development Kit

https://www.oracle.com/technetwork/java/javase/downloads/index.html

Download and install the COMMUNITY edition of JetBrains IntelliJ IDEA:

Windows: https://www.jetbrains.com/idea/download/#section=windows

MAC: https://www.jetbrains.com/idea/download/#section=mac

Make sure you click on the black button:

Starting a project and running a program:


See this website for more information:
https://www.jetbrains.com/help/idea/creating-and-running-your-first-java-application.html

 Open up IntelliJ and start a new project. Call it “project1”.


 Right click the mouse on src in the project window in the top left and select new and then Java
Class. Name the class Lesson1

 Now you will see this in your coding window on the right:

1
ICS4U - Java

Add the following two inside the class. Every new file you make will need to have a main function.

public class Lesson1 {

public static void main(String[] args) {


System.out.println("Hello, World!");
}
}

Right click inside your coding window and click run:

You should see the words Hello, World! In the output dialog box at the bottom of the screen.

Exercises: add these to your program:

a) output your name


b) output your three favorite foods

Shortcut: you can type “sout” and then hit the “tab” key to shortcut to System.out.println()

Try this a few times

*** to avoid typing the main method every time, similarly use “psvm” with tab to get the signature

2
ICS4U - Java

2. Terms in Java

*Copy and paste sample code here:


/*
Author: ICS4ug
Purpose: running a basic program in order to demonstrate
that we're set up
*/
public class HelloWorld {
public static void main(String[] args) {

System.out.println("Hello World");

}//End of main method


}//End of class

Define the following terms: For each term, link to an example in the code above

a. Keyword: Words belonging to a programming language which are used for various operations
(i.e. class, public, static, void)

b. Comments: Documentation within classes designed to clarify the purpose of certain portions of
code. Can be one line ‘//’ or can be /*…….*/ multiple lines.

c. White space: Any sequence of only space, tab, and newline characters. These characters affect
formatting/appearance of the code, but (unlike with Python) have no impact on how the code
runs.

d. Class: The basic building block of Java. For the purposes of this course, each Java file we
produce, represents a Class.

e. Method: Blocks of code that can carry out a specific task multiple times. A Class can be made up
of multiple methods.

Success Criteria: I can…


Create a java project, create a new class, and run that class
Define the terms: comment, white space, class and method

3
ICS4U - Java

3. Output in Java
For each of the following lines of code:

1. Predict the outcome of running the code

2. Enter the code into the programming environment

3. Write the results of actually running the code. If the code does not run, indicate “Syntax Error”
*after testing each line, comment it (//) so it no longer runs

Code to test Predicted result Actual Result


a.) System.out.println("Hello World");

b.) System.out.println(Hello World);

c.) System.out.println ("2+2");

d.) System.out.println (2+2);

e.) System.out.println (2+3*4);

f.) System.out.println (16/2);

g.) System.out.println (2/3);

h.) System.out.println (2.0/3);

i.) System.out.println(""make quotes show"");

j.) System.out.println("\"make quotes show\"");

k.) System.out.println("Hello World"); //This won't show up

l.) System.out.println(6%3);

m. System.out.println(7%3);
)
n.) System.out.println(8%3);

o.) System.out.println(9%3);

4
ICS4U - Java

Arithmetic operators in Java:

Operator Purpose Example


+ Addition 6+2 result 8
- Subtraction 6-2 result 4
/ Division 6/2 result 3
* Multiplication 6*2 result 12
% Modulus 3%3=0, 4%3=1, 5%3=2, 6%3=
(remainder)
() Brackets
Questions:

1. What’s the difference between a.) and b.)?

2. Why do c.) and d.) run differently?

3. Look at the results of e.). Are the rules of BEDMAS observed?

4. Why did g.) and h.) produce different results?

5. How do you get a quote (“) to show up in a print statement?

5
ICS4U - Java

4: Data Types and Declaring Variables


Recall the data types you learned last year in Python: (int, String, float, Boolean)

value Data type value Data type:


“hello” 3.14159
4 True

In Python, you don’t have to state in advance the variable type. Python will infer it from the value you
give it. In Java, you must tell it what the variable type will be (this is one way that Java has to do less
“figuring out” and therefore runs faster than Python, but it requires more coding).

Those data types have keywords in java: int, float, double, char, and String (capital S)

Compare how you declare them in Python vs Java:

Python Java
age = 18 int age = 18; // needs a ;
pi = 3.1415 float pi = 3.1415;
likesBurgers = True # upper case True Boolean likesBurgers = true; // lower case true

Make a new Java Class and call it “Lesson2Variables”. Type in this code (without comments) and run.

public class Lesson2Variables {

public static void main(String[] args) {

// tell Java what data type it is


int x = 5;
System.out.println("Your integer is " + x);

// a double is decimal value which takes up more memory


double z = 0.76;
System.out.println("Your double is " + z);

// a float is a decimal but takes up less memory


float y = 0.6f; // have to put an "f" to make it a float
// since the default is double
System.out.println("Your float is " + y);

// a char is a single symbol. You need single quotes


char c = 'a';
System.out.println("Your character is " + c);

// a String uses double quotes


String s = "sup";
System.out.println("Your string is " + s);
}
}

6
ICS4U - Java

Exercise:

a) Write a program that declares a variable for each of the main data types and outputs them to
the screen.

Naming Variables: variables in Java have to start with a lower case letter. They can have numbers after
the first letter, but no special symbols anywhere. Variables with multiple words can have an underscore
between then, first_name, or have every new word start with a capital, firstName.

Acceptable: No good:

int num1 int 1num

String full_name String %name

String fullName Boolean 1forest1

5: Basic Math
You can perform the same operations as Python (+, -, *, /). Type in and run the following:
public class tryingmath {
public static void main(String[] args) {
double x = 5;
double y = 7;
double z = x/y;
System.out.println("Quotient: "+ z);
z = x*y;
System.out.println("Product: "+ z);
z = Math.pow(x,y);
System.out.println("Power: "+ z);
}
}

You can’t use ** as an exponent like you can in Python (e.g. 5**2). But you can use the function:
z = Math.pow(x,y);

7
ICS4U - Java

Exercises:

1) Write a program that declares two double variables. You can pick any numbers for them
between 10 and 20. The program should:

Add them, subtract, multiply, divide, raise one to the power of the other and vice versa. It
should store the results in four new variables. Output them to the screen in a nice-looking
way.

2) Write a program that stores the radius of a circle in an appropriate variable and give it some
value, for example, double radius = 5.5.
a. Calculate the circumference (and store it in a variable called “circumference”). You
can make another variable to help:

b. Calculate and store the area of the circle in another variable.


c. Output the circumference and area in a nice way like this:

3) Similar to question (2), write a program that calculates the perimeter and area of a
rectangle. You can start with variables length and width and give them values. Output the
perimeter and area in a similar way.

4) Write a program that solves the Pythagorean theorem. Start with two doubles, called a and
b. Give them values. Calculate the hypotenuse, store it in double c, and output it in a nice
way (see below). You can use Math.sqrt() method to do this.

5) Write a program that calculates and outputs the surface area and volume of a cone, give
the height and radius (these values can be hard coded into variables like you did in previous
questions). You may have to look up the formulas.

8
ICS4U - Java

Data Casting

Block comment out your previous programs. Now add these lines to your main method, and see the
new output:
int a = 3;
int b = 4;
double c = a/b;
System.out.println(a + " / " + b + " = " + c);

You’ll notice it gives you an answer of 0.0 instead of 0.75. When you divide integers, the result is an
integer. You can store it in a double data type but it has already lost its decimals. To avoid this, change
the line to:

double c = (double)a/(double)b;

This is called “casting” the variable’s value to be a type double (casting = changing the data type). You
can do this between numerical values, but not between numbers and Strings / chars.

If you are casting values directly, not variables that store values, you can add a “d” after the number to
make it a double, or “f” to make it a float, for example, try these:

Casting examples: add each to your program and run them:


float f = 3/4; // integer division - f will be 0.0
System.out.println("f: " + f);

float g = 3f/4f; // float division - g will be 0.75


System.out.println("g: " + g);

int i = (int)(3f/4f); // does float division, but then casts as an integer


System.out.println("i: " + i);

Casting Exercises:

1) Declare two variables as integers and give them integer values. Divide them while casting them
as doubles, and store the result in a new double. Output the result.

2) Declare two variables as doubles and give them decimal values. Divide them and cast the result
as an integer. Output the result.

9
ICS4U - Java

Other Data Types:

Java has a few other primitive data types (primitive = basic and easy to handle). String is not actually a
primitive data type. It is a class (more on that later).

Data Type Can hold… Size in # of Bytes Range


byte Integers 1 (28) -128 to 127
short Integers 2 (216) -32768 to 32767
int Integers 4 (232) -2.15x109 to 2.15x109
long Integers 8 (264) -1.84x1019 to 1.84x1019
float Real numbers 4 (6/7 decimals)
double Real numbers 8 (15/16 decimals)
char Characters 2
Boolean true/false 1 bit

You can save memory by using a byte data type if you only need to store small numbers that go up to 2 8
= 128.

If you need to store an integer value greater than 2 32 = 4.295 x 109 (4.2 billion), you would need to use a
long data type.

Variables in Java actually store a memory address in RAM. At that memory address is the value the
variable is holding. When you run this line: int x = 3;

Java creates a location in RAM (a memory address) that is 4 bytes in size to hold the number you are
placing there.

Success Criteria: I can…


Declare variables of different types and output them to screen
Define the terms: comment, white space, class and method
Differentiate the primitive data types (byte, short, long, int, boolean, float, double)
Perform basic math functions on variables
Cast variables between different data types

10
ICS4U - Java

6: Getting User Input from the Keyboard


Scanner Class: Java is built around using different classes. A class can be an entire program, a more
complex data type, or a structure to organize different methods. The scanner class is a collection of
methods that allow us to read input from the keyboard.

Good extra resource on this topic: http://www.csc.villanova.edu/~map/1051/s14/02input.pdf

Make a new class called “gettinginput”. Type in the following code.


import java.util.Scanner;

public class gettinginput {

public static void main(String[] args) {

// creates a new Scanner object which can take in keyboard input


Scanner scan = new Scanner(System.in);

// first output the question prompt:


System.out.println("Enter your name: ");

String name = scan.nextLine();


// user's input gets stored in the variable "name".

// output their name


System.out.println("Hello, " + name);

// now let's take in an integer


System.out.println("Enter an integer: ");
int num1 = scan.nextInt();
System.out.println("your integer is " + num1);

// or a double...
double num2 = scan.nextDouble();
System.out.println(num2 + " squared is " + num2*num2);
}
}

Use different functions to take in different data types (nextLine for Strings, nextInt, nextFloat,
nextDouble, etc.)
*** whenever you take in a new data type with scanner, it must be reset:
scan = new Scanner(System.in);

11
ICS4U - Java

Exercises:

a) Write a program that asks for a person’s favorite food (String) and outputs it back to them
b) Write a program that asks for two numbers (int). It should multiply them together and print the
result
c) Add to (b) by making the program calculate the first number to the power of the second like we
did in program 3, and output the result (doubles)
d) Write a program that asks the user for the radius of a sphere, and outputs surface area and
volume.
e) Create a Pythagorean theorem program that asks for sides A and B, then calculates and outputs
the hypotenuse.

12
ICS4U - Java

7: More on Data Casting


Explicit Casting:

We have already done examples of data casting, for example:


int x = 3;
int y = 4;
float z = (float)x/(float)y;
System.out.println(z);

This is called explicit casting (you are stating out in the open the data type you want). This is usually
done to get an answer with more precision than the original data types being used.

Implicit Casting:

Sometimes you don’t need to be explicit. For example, you *can* do this:
byte a = 15;
int b = a;

But you *can’t* do this:


int a = 15;
byte b = a;

Exercise: between byte, short, int and long, test which pairs of data types can be implicitly casted and
which can’t. After experimenting, come up with a rule.

Numbers to Strings:

You can’t cast numerical values to symbolic ones (e.g. int to String). There are built-in functions that do
this. Try these:
// integer to string
int a = 15;
String s = Integer.toString(a);
System.out.println("your integer is " + s);

// float/double to string
float pi = 3.14f;
String sp = Float.toString(pi);

There’s also a really easy way to do it, just by adding “” symbols before the numeric variable:
int n = 3;
String s = ""+n;

13
ICS4U - Java

Strings to numbers:

Converting strings of numbers into numerical data types is called parsing. The functions have that word
in them:
// String to float
String pi = "3.1415";
float float_pi = Float.parseFloat(pi);

// String to int
String s = "5";
int int_s = Integer.parseInt(s);

Exercises:

a) Why doesn’t this code work?

String pi = "3.1415";
int int_pi = Integer.parseInt(pi);

b) Write a program that uses scanner to input two integers from the user. Cast both integers to
Strings, combine them, and output the result. Sample output:

c) Write a program that scans in two strings from the user (in integer format). Cast both strings to
integers, add them, and output the result.

Success Criteria: I can…


Use the scanner class to get input from the user in the form of a String, int, double, etc.
Case numerical values to strings and vice versa

14
ICS4U - Java

8: The String Class


A String is a series of one or more characters.

// strings can be concatenated


String s1 = "race";
String s2 = "car";
String s3 = s1 + s2;
String s4 = s3 + "s are awesome";
System.out.println(s4);
// get the length of a string
int s4_length = s4.length();
System.out.println(s4 + " is " + s4_length + " letters long.");

In Java String is not a Primitive Data Type. It is an entire class with many functions/methods. .length() is
a very useful method.

Here are some String class methods: try each of these in order to see the output
String s1 = "hello world";
// .length() - getting the length of a string and returns int
System.out.println(s1 + " is " + s1.length() + " characters long");

// .charAt(char c) - returns the character at that location


System.out.println(s1 + " starts with " + s1.charAt(0));
System.out.println(s1 + " ends with " + s1.charAt(s1.length()-1));

// .startsWith(char c) - returns true or false if it starts with that char


System.out.println(s1 + " starts with 'x'? " + s1.startsWith("x"));
System.out.println(s1 + " starts with 'h'? " + s1.startsWith("h"));

// .equals(String s) - true or false if it equals the given string


System.out.println(s1 + " is the same as 'banana'? " + s1.equals("banana"));
System.out.println(s1 + " is the same as 'hello world'? " + s1.equals("hello world"));

// .equalsIgnoreCase(String s) - more useful version of the above that ignores case


System.out.println(s1 + "is the same as 'Hello World'? " + s1.equals("Hello World"));
System.out.println(s1 + "is the same as 'Hello World' ignoring case? " +
s1.equalsIgnoreCase("Hello World"));

// .indexOf(char c) - returns the location index of the first time that char appears
System.out.println("x occurs at location: " + s1.indexOf("x")); // -1 not in the string
System.out.println("l occurs at location: " + s1.indexOf("l"));

// .replace(char c1, char c2) - replaces c1 with c2


System.out.println("replace 'l' with 'x': " + s1.replace("l","x"));

// .substring(int n1, int n2) - gets the substring between n1 (includes) and n2 (doesnt
include)
System.out.println("first 4 letters: " + s1.substring(0, 4));
System.out.println("last 4 letters: " + s1.substring(s1.length()-4, s1.length()));

// .toLowerCase() - puts it in lower case


System.out.println("lower case: " + s1.toLowerCase());
System.out.println("upper case: " + s1.toUpperCase());

15
ICS4U - Java

Exercises:

1) Write a program that asks the user to input a string of 2 words with first letters capitalized. For
example: “Hello World!”

a. State the length of the string


b. Output the third character of the string
c. Output the first letter and last letter
d. Output the string without the first and last letters
e. Output the first 3 letters
f. Output the last 3 letters
g. Output the string in lower case
h. Output the string in upper case
i. Ask the user to pick a letter in the string and output the location of that letter
j. Find and output the location of the space “ “ between the words (store it in a new int
variable)
k. Using the answer to the previous part, store the first word in a new String variable, and
the second word in a separate String variable. Output both words.
l. Replaces all vowels in the string with a “*”. You will have to search for each vowel.

2) Perimeter of a rectangle: ask the user for the length and width of a rectangle separate by a
space, for example: “5.6 8.62”. Separate their input into two strings stored in new variables.
Parse the Strings into double in two new variables. Calculate and output the area and perimeter
of the rectangle.

3) Pythagorean theorem: ask the user for sides A and B separated by a space. Parse them to
doubles, then calculate and output the hypotenuse.

4) Ask the user the input a 9 digit integer and take it as a String, for example “111222333”.
a. Save the first 3, middle 3, and last 3 numbers in new Strings.
b. Combine and output the first 3 and last 3, e.g. “111333”
c. Parse all three Strings into integer. Add them all together and output the sum.

Success Criteria: I can…


Use the String class and perform basic String operations like lowercase, substring, etc.
Parse values into strings and vice versa

16
ICS4U - Java

9: The Math Class


The ‘Math’ class is one of many classes available from the Java Library. It has a variety of useful methods
that can be used to carry out math-related tasks.

Method Syntax Description Return Type


Math.abs(int n) Absolute value(n or n*(-1) whichever is greater double or int
Math.acos(double d) Arc cosine of d double
Math.asin(double d) Arc sine of d double
Math.atan(double d) Arc tangent of d double
Math.ceil(double d) Smallest integer >= d int
Math.cos(double d) Cosine of d double
Math.exp(double d) ed where e=2.718… double
Math.floor(double d) Largest integer <= d int
Math.log(double d) Natural logarithm of d double
Math.pow(double a, double ab double
b)
Math.random() Generates a random number >= 0.0 and < 1.0 double
Math.round(double d) Rounds d to the nearest long value long
Math.sin(double d) Sine of d double
Math.sqrt(double d) Square root of d double
Math.tan(double d) Tangent of d double
Math.toDegrees(double d) Converts d (in radians) to degrees double
Math.toRadians(double d) Converts d (in degrees) to radians double
Math.min(double a,double b) returns the lower of the two values double or int

Sample code for generating a random numbers: try these and any variations in a new class file.

public class tryingmath {

public static void main(String[] args) {

// between 0 and 1
double num1 = Math.random();
System.out.println("a number between 0 and 1 is: " + num1);
System.out.println("formatted to 2 decimals: " + String.format("%.2f", num1));

// 0 - 10
double num2 = Math.random()*10;
System.out.println("0 - 10, 3 decimals: " + String.format("%.3f", num2));

// 1 - 6
double num3 = 1 + Math.random()*5; // 1-6
System.out.println("a number between 1 and 6 is: " + num3);

// 1 - 6 rounded to an integer (e.g. die roll)


int dieRoll = (int)(1+Math.random()*5);
System.out.println("a random die roll: " + dieRoll);

// evenly weighted die roll


int roll_even;
roll_even = (int)(Math.round(0.5 + Math.random() * 6));

17
ICS4U - Java

}
}
Exercises:

1) Write a program that asks the user to input decimal number, using scan.nextDouble(). Then
output:
a. the original number, and the number formatted to 4 decimal places
b. the cube of the number
c. a random number between 0.0 and the number
d. rounds the number to the nearest integer

2) Use Java to calculate the value of these expressions:

a. Math.abs(-4 + Math.sqrt(Math.max(2,3) * Math.ceil(2.8)));

√( ) ( )
4
3 3 2
b. + - cube root, same as an exponent of 1.0/3.0 – using Math.pow()
4 5

3) Ask the user to input 2 numbers. The program should take the lower number (using Math.min)
and output the absolute value of that number plus 10. For example, if the user inputs 3 and -5,
the program will output abs(-5 + 10) = 5.

4) Starting with these variables:

double x = 2.5;
double y = -1.5;
int m = 18;
int n = 4;
String s = "Hello";
String t = "World";

Determine what the output would be for the following without coding it:

line output
1 System.out.println(x + n*y - (x + n)*y);

2 System.out.println(m/n + m%n);

3 System.out.println(5*x - n/5);

4 System.out.println(Math.sqrt(Math.sqrt(n)));

5 System.out.println( (int)Math.round(x));

6 System.out.println((int)Math.round(x) + (int)Math.round(y));

7 System.out.println(s + t);

8 System.out.println(s + n);

9 System.out.println(1-(1-(1-(1-(1-n)))));

18
ICS4U - Java

10 System.out.println(s.substring(1,3));

11 System.out.println(s.length() + t.length());

Success Criteria: I can…


Use the math class to perform other math operations on variables
Generate random numbers between any two values

10: Boolean Operators:


IF statements in Java are almost identical to IF statements in Python. You can use the following
comparisons:

Equals Not equals greater less …or equal


== != > < >= <=

Like Python, Java comparisons can either be true or false. Give the Boolean value for the following:

expression outpu expression output


t
2 == 6/3 5 != 5
“hello” == “Hello” 4 <= 8/2
“hello” != “Hello” 10 > 20
10 == 20/4 ‘a’ < ‘c’
Math.pow(2, 2) == 4 ‘c’ < ‘a’

AND and OR – Python vs Java

operator Python Java


and and && (shift-7)
or or || (shift \)

Boolean truth tables:

Say that a and b are Boolean expressions that can be true or false.

AND – both must be true OR – only one needs to be true XOR – only one can be true

a b c = a && b a b c = a || b a b c = a^b
false false false false false false false false false
true false False true false true true false true
false true false false true true false true true
true true true true true true true true false
Exercises:
1) Complete the truth table:

19
ICS4U - Java

b c b&&c b||c b^c !b b==c b!=c


false false
true false
false true
true true
2) Evaluate the following expressions mentally, then test them in Java:

Code Output: true or false


Boolean b1 = 5 < 10;
System.out.println(b1);
Boolean b2 = 5 == 10;
System.out.println(b2);
Boolean b3 = (5 < 10 || 5 == 10);
System.out.println(b3);
Boolean b4 = (5 < 10 && 5 == 10);
System.out.println(b4);
Boolean b5 = (true || false && 5 < 3 + 3);
System.out.println(b5);
int x = 0;
System.out.println(x==0 || x-5 > -2);

3) Try each of these examples in Java. One will compile, but the others will not.

// example A
int x = 0;
System.out.println(50/x);

// example B
int x = 0;
System.out.println(x==0 || 50/x>2);

// example C
int x = 0;
System.out.println(x==0 && 50/x>2);

a. Why does A crash?


b. Why does B compile?
c. Why does C crash?

Success Criteria: I can…


Evaluate Boolean expressions in Java
Use Boolean comparatives between variables and values
Use brackets to evaluate more complex Boolean expressions

20
ICS4U - Java

11: Conditionals / IF Statements


If statements in Java are almost identical to Python.

Python:
grade = 75
if grade >= 80:
print("you made the honour roll!")
elif grade >= 50:
print("you passed")
else:
print("you failed")

Java:
double grade = 75;
if (grade >= 80){ // Boolean expressions go in brackets ()
System.out.println("you made the honour roll!");
} else if (grade >= 50){
System.out.println("you passed");
} else {
System.out.println("you failed");
}

Exercises:

1) Write a program that asks the user to input a number. It should output a different statement
depending on the number of digits of the number:

digits Output
1 “less than 10”
2 “double digits!”
3 “hundreds”
4 “thousands”
>4 “that’s just big!”

2) This program generates a random “grade” between 40 and 100. It should output the
appropriate letter grade for the mark (e.g. > 90 is A+, > 80 is A, > 70 is B, etc.)

3) Ask a user for the length and width of a rectangle. It should calculate the perimeter and output
it. If the perimeter is greater than 100, output, “too large”, if it is less than 50, output “too
small”. If it is between 50 and 100, output “good choice”.

21
ICS4U - Java

Switch Statement: this is a shorthand that lets you do multiple if statements to compare a variable to
multiple set values. It only works for the == operator. You can’t do it for > or <.
String food = "grapes";
switch (food) {
case "orange":
System.out.println("bad for your teeth!");
break;
case "apples":
System.out.println("keeps the doctor away");
break;
case "grapes":
System.out.println("yum!");
break;
default: // any other options
System.out.println("that food is not in the list");
}
You can give multiple values the same outcome:
String food = "plum";
switch (food) {
case "plum":
case "apple":
case "orange":
System.out.println("this will print for the 3 above fruits");
break;
}
You can also write it with arrows, and not have to include the terms case or break;
String day = "M";
switch (day) {
case "M", "T", "W", "R", "F" -> System.out.println("weekday");
case "Sa", "Su" -> System.out.println("weekend");
default -> System.out.println("that is not a day");
}

Find more information: Switch Expressions (oracle.com)

Exercises:

1) Use a switch: write a program that asks the user for a letter grade, e.g. “A”, “b”, etc. It should be
able to handle upper or lower case (you can use a string operation). Output the grade range for
that letter. For example, if they enter “C”, output”

60 – 60 %

22
ICS4U - Java

2) Use a switch: write a dice rolling / craps program. It should roll two random dice (integers
between 1 and 6). Output:
“winner!” if they add up to 7 or 11
“not bad!” if they add up to 6
“snake eyes!” if they add up to 2

3) Modify your die rolling game. Don’t use a switch, just use if statements with && and ||
a. 7 or 11: “winner!”
b. 6: “not bad!”
c. 2: “snake eyes!”
d. If you roll the same number on each: “doubles!”
e. If both rolls are 1-3: “under 4s!”
f. If both rolls are 4-6: “over 3s!”
g. If one roll is 1-3 and the other is 4-6: “over under!” (note: there are two ways this can
happen. Have them both in a single if statement with and and ors)
h. If both rolls are even: “evens!” (use modulus, example below)
int x = 4;
if (x % 2 == 0){
System.out.println("even!");
}

i. If both rolls are odd: “odds!”

j. If one roll is even and the other is odd: “even/odds!” (two ways for this to happen as
well)

4) For each situation below, code an appropriate solution using either (a) if, (b) if else (c) if else-if
or (d) if else-if else
a) Use a person’s age (int age) to determine whether they are eligible to vote – if they are 18 or
over. Output a message “you are eligible” or “you are not eligible”
b) Use a person’s age and whether they have job experience (yes or no) to see if they are suitable
for a job. In order to be suitable they should be over 16 and have experience. If they are
suitable, output “suitable”, otherwise output a message for reasons why they are not, e.g. “not
16” or “no job experience” or “not 16 and no job experience”
c) Generate a random number and ask the user to enter a number.
a. If the user input is lower, indicate whether it is less than half, half, or more than half the
random number
b. If the user input is equal, output “equal”
c. Otherwise output “greater”

Success Criteria: I can…


Use if statements with &&, || and Boolean comparisons between variables and values
Use a switch statement

23
ICS4U - Java

24
ICS4U - Java

12: Programming Conventions


Programs are conventionally set up in a specific way. It’s standard in the programming industry and
helps other programmers read and edit your code.
/*
Program: demonstrating program conventions
Author: Matt Craig
Date created: 8/19/2021
Last modified: 8/19/2021
*/

// inner classes if you have them


class InnerClass{

// public class last


public class conventions {

// variables / class instances with camelCase or underscore_case


String first_name = "";
int testAverage = 0;
InnerClass IC = new InnerClass();

// METHODS

// main
public void main(String[] args){
// main program goes here
}

// other methods if you have


private void method(){
}
}

Exercise: add these programming conventions to your previous die-rolling program, and use it in all
future programs.

Success Criteria: I can…


Apply programming conventions to make my program fit industry standards
Write comments where appropriate include program headers

25
ICS4U - Java

13: WHILE loops


With a counter variable
Here’s a sample syntax for a while loop that outputs all multiples of 5 from 0 to 100:
public class whileloops {
public void main(String[] args) {
int i = 0;
// printing multiples of 5 from 0 to 100
while(i < 100) {
System.out.println(i);
i += 5;
}
}
}

Exercises:

a) Make a program that asks the user to input a min and max number. Your program should output
all the integers between those two numbers
b) Change (a) to output every other number (by adding 2 each time)
c) Output all multiples of 5, but in reverse, so it will count down from 100.

With a Boolean
This while loop uses a Boolean to keep looping until the user is ready to quit:
import java.util.Scanner;

public class whileloops {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

boolean keepLooping = true;


while (keepLooping){
System.out.println("Do you want to keep looping? y/n ");
String choice = scan.next();
if (choice.equals("y")){
System.out.println("Looping again");
} else if (choice.equals("n")){
System.out.println("Quitting");
keepLooping = false;
} else {
System.out.println("invalid choice");
}
}
}
}

26
ICS4U - Java

Exercises:

a) Make a program that takes a double as input from the user. Then a while loop should ask them
to enter “1”, “2” or “3”.
1: the loop doubles the number and outputs the result
2: the loop halves the number and outputs the result
3: the loop exits

b) Make a program that asks a user for a positive integer (-1 to quit). After the number is received,
the program must display how many numbers have been received (what “round” it is, basically)
and output the total sum of the numbers so far. The program will exit when any negative integer
is input.

c) Write a program that has users input positive integers. Every time an integer is input that is
evenly divisible by the previous input integer, the program should output a message like:

8 is divisible by the previous number, 4

Quit the program when a negative number is input.

d) Make a “war” game inside a while loop. Every loop, a random number between 1 and 10 is
generated for the user and computer. Whoever has the higher card gets a point (if it’s a tie no
one gets a point). You can keep playing while the user hits enter, and exit when they input “q”
to quit. Give it appropriate output messages for each hand, for example:

User got 6 and computer got 4.


User wins this round!
The score is, user: 3, computer: 1
Hit enter to play another round or (q) to quit

Success Criteria: I can…


Write while loops to repeat blocks of code
Control while loops with counter variables or booleans
Use the break; command to break out of loops

27
ICS4U - Java

Getting out of Loops

If you program your while loop correctly, you should always be able to exit the loop. There is a way to
force break out of a loop using a break. Here’s an example that uses a break and no Boolean variable.
import java.util.Scanner;

public class whileloops {


public void main(String[] args) {
Scanner scan = new Scanner(System.in);

while (true){ // always do the loop


System.out.println("Do you want to keep looping? y/n ");
String choice = scan.next();
if (choice.equals("y")){
System.out.println("Looping again");
} else if (choice.equals("n")){
break; // breaks out of the current loop
}
}

}
}

Exercises:

a) Rewrite program (a) from above using while (true) and a break
b) Rewrite program (b) from above using while (true) and a break

*** There are some cases where a break is necessary, but generally speaking, I would prefer you to use
other methods as it’s a bit lazy.

28
ICS4U - Java

14: FOR loops


For loops are used when you want to do something a definite amount of times.
public class newProgram {
// your main function - this is where the program will start running
public static void main(String[] args) {

// i is the counter, start at 0, end at 9, add one each time


for (int i = 0; i<10; i += 1){
System.out.println(i + " squared is " + i*i);
}
System.out.println();
System.out.println();
// or go down from 9 to 0 by twos:
for (int i = 9; i >= 0; i -= 2){
System.out.println(i + " squared is " + i*i);
}

}
}

*** you can also use floats or doubles as your counters in for loops. It’s less
common, though.

Exercises:

a) Make a program that asks the user to input a min and max number. Your program should output
all the integers between those two numbers

b) Change (a) to output every other number (by adding 2 each time)

c) Output all multiples of 5 from 100 down to 5 in reverse order: 100, 95, 90…

d) Write a program that asks the user for an integer. It should output all the factors (integer
divisors) of that number. At the end it should output the total number of divisors. Use modulus.

e) Make a program that “deals” a user hand – it uses a for loop to generate 5 random numbers
from 1-10. It should add them up to a total. Do the same for the computer hand (you can do this
in the same FOR loop). Whoever has the higher hand wins – output a message comparing the
scores and declaring the winner after the loop

f) Add to (e) put the whole thing inside a while loop with Boolean condition so the user can keep
hitting enter to play another round, or “q” to quit.

g) The Fibonacci sequence is a sequence where each term is the sum of the previous two terms:
1, 1, 2, 3, 5, 8, 13, 21, …
Write a program that outputs the Fibonacci sequence. It should ask the user how many terms to
output. For example if the user enters “10” it outputs the first 10 terms.

Success Criteria: I can…


Write for loops using increasing or decreasing values

29
ICS4U - Java

15: Problem Solving with For Loops


When solving problems in computer science, the first step is to ensure the solution is correct. The next
goal is to arrive at the most efficient solution. Efficient solutions are faster and use the least amount of
memory (faster is more important).

Here are some problems to try. How efficient is your solution?

In each problem: the user enters a string, which I will call userWord, consisting of lower case letters
only. You can use to help:
userWord.toLowerCase());

Consider the number (ASCII) values of characters: “a” = 97, “b” = 98, “c” = 99, …, “z” = 122
You can get the letter value by casting as an integer:

int letterVal = 'c';


System.out.println(letterVal);

You can parse a string to a char with:

char newChar = userWord.charAt(i);

Exercises:

 Output all the letters of the word and their values (I will help with this one)

a) Find the largest (highest) letter of userWord


b) Find the smallest letter
c) Find the largest difference between two adjacent letters. For example, if the word is
abcdg – then the largest difference occurs between the d and g (3 letters).
d) Find the longest increasing subsequence of userWord.
e) Sort a word from highest to lowest letter (tricky)

Sample output:

30
ICS4U - Java

16: Arrays
Arrays are like lists in Python but you initialize/declare them entirely different. In Python, we used lists
and appended to them, for example:

Creating a list of 10 items in Python (ten zeroes):


scores = []
for i in range(0, 10):
scores.append(0)

Creating an arrays in Java:

Method 1: give them values right away


int x[] = new int[] {1, 2, 3, 4, 5}; // 5 integers, values in {}
String words[] = new String[] {"hello", "goodbye", "shalom"}; // 3 strings
double dubs[] = new double[] {1.5, 3.6}; // 2 doubles

Method 2: start them empty and give them values later (more common)
int x[] = new int[10];
String words[] = new String[10];
double dubs[] = new double[10];

*** these three arrays are EMPTY. You can’t access their values. You have created space in memory to
hold those data types.
import java.util.Scanner;

class Scratch {

public static void main(String[] args){


Scanner scan = new Scanner(System.in);

// declare empty array of 5 integers


int x[] = new int[5];

// give it a value directly


x[0] = 15;

// input a value to it
System.out.println("Enter second number: ");
x[1] = scan.nextInt();

// use a for loop to populate the array with random 1-10


for (int i = 0; i<x.length; i++){
x[i] = (int)(1+Math.random()*9);
}
// print the array
System.out.println("Your array is: ");
for (int i = 0; i<x.length; i++){
// .print (as opposed to .println) does not go to the next line
System.out.print(x[i] + " ");
}

31
ICS4U - Java

}
}

Exercises:

a) Declare an integer array of 5 numbers (you can just make up numbers to put in). Use a for loop
to output them.
b) Declare a string array of five of your favorite foods. Use a for loop to output them in a nice way.
c) Declare an empty double array of 5 values. Use a for loop to store random values between 3 and
7 in each. Also output them.
d) Declare an empty array of 10 integers. Use a for loop to store and output the perfect squares of
1-10 in them.
e) Declare an empty array of 10 integers. Use a for loop to store successive multiples of 2. (e.g. 0,
2, 4, 6, etc.)
f) Repeat (e) but the user can input the size of the array and the multiple.
g) Add to program (f): use a for loop to add up all the numbers in the array and then output the
sum

Assessments:

a) Create a program that uses a loop for the user to keep inputting test scores. Put those scores
into an array. Since you don’t know how big it will, create a 10 integer array and populate it with
zeroes to start. When the user enters a negative value, the loop exits. Calculate the average of
the scores in the list and output them.

b) Speed dial:
a. Make a list of ten 7-digit phone numbers. Use a for loop to randomly generate the
numbers e.g. nums[i] = (int)(Math.random()*9999999);
b. Make a second list of 10 names (Strings). You can simply make up names.
c. In a while loop, ask the user for a number, 0-9, and outputs the name and phone
number of that item in the list. Otherwise, you can use -1 to quit.

c) Modify program (a). The user should be prompted to modify a value, for example:

32
ICS4U - Java

d) Write a program that simulates rolling 2 dice 100 times. It should count how many times each
roll occurs and store those totals in a list, which you can output at the end.

Success Criteria: I can…


Create arrays of different data types
Use for loops to go through arrays (e.g. add all the elements, compare elements)
Take user input into an array for analysis

33
ICS4U - Java

17: ArrayLists
Arrays are limited in functionality because you need to predetermine the size when you first declare
them. Their size is not dynamic (this has never caused Mr. Craig any problems in his program – you just
have to be aware of the maximum size they can get and set that as their start size).

ArrayLists are dynamic, which means they can be resized, and they function just like lists in python, with
functions similar to append() and remove().

This code shows how you can create an ArrayList, add to it with .add() and retrieve from it with .get()
//The type of data held by the ArrayList should be typed in the <>
ArrayList<String> stringsList= new ArrayList<>();

//Data can be added to the end of the list with .add()


stringsList.add("Hello");
stringsList.add("World");
stringsList.add("!!!");

for(int i=0;i<stringsList.size();i++){
//Data from location i in the list can be retrieved with .get(i)
System.out.println(stringsList.get(i));
}

Things to note:
1) You will need to import: import java.util.ArrayList;

2) ArrayLists don’t hold primitive data types (boolean, int, char, double). They instead use whats
called a “wrapper class” which lets you treat primitive data types as objects. This allows you to
easily use built in methods for them in your programs (more on this later). For now, just know
that the wrapper class just uses a capital first letter and full word:
int  Integer
boolean  Boolean
char  Character
double  Double

3) The .add() function acts like the .append() function in Python.


4) You can’t access the data by simply referencing the index in square brackets (e.g. words[2]). You
need to use words.get(2).
5) Since its not technically an array, you can’t use .length. You have to use words.size()

You will find the following methods most useful:


.add(value) Adds the value at the end of the list
.get(int index) Gets the value at that index
.set(int index, value) Replaces the value at that index with a new value
.remove(int index) Removes the object at that index
.size() Returns the size of the list

For a full list of methods, consult this website:


ArrayList (Java Platform SE 8 ) (oracle.com)

34
ICS4U - Java

Exercises:

a) Make an ArrayList that stores all integers <Integer>


from 10 to 20. Use a NEW for loop, that goes from 0 to
list.size(), to output them all on one line.
b) Modify (a) – use a for loop to replace all EVEN values
with the number 0. Use modulus to check if the value is
even. Output the new list.
c) Modify (b) – use another loop to remove all ODD
values. Output the new list.
d) Match the output on the right

e) Make an ArrayList program that stores favorite foods of the user as


Strings. They can keep entering favorite foods until they enter (“q”).
Match the output on the right.

f) Redo the test average program with an ArrayList to store each score. The user inputs test scores
until they enter (“q” or -1) and then it outputs the average.

Success Criteria: I can…


Explain how arraylists are dynamic and in some cases more useful than arrays
Use for loops to go through arraylists
Create programs that use arraylists for user input

35
ICS4U - Java

18: Big-O Notation: Code Efficiency


With a partner consider these examples:

1) Addition: you have to add two numbers by hand (old school way). Let’s say a single digit addition
like 3 + 4 = 7 counts as “one addition”. How many additions are required for the following?

One digit numbers Two digit numbers Three digit numbers


2 + 3? _____ 22 + 33? _____ 222 + 333? _____

Ten digit numbers? _____ one hundred digit numbers? _____

n-digit numbers? ______

2) Multiplication: Complete the multiplication tables:

1x1= 1x2=
2x1= 2x2=

1x1= 1x2= 1x3=


2x1= 2x2= 2x3=
3x1= 3x2= 3x3=

How many calculations did you do to complete:

The 2 x 2 table? _____

The 3 x 3 table? _____

What if that table was n x n ? _____

3) A computer program generates a random number between 1 – 100. You have to guess and the
program will say “higher” or “lower” until you guess the number.

a) Suggest the least efficient algorithm you can think of to accomplish this.
a. How many guesses could it take in the worst case scenario?
b. If you double the max number 1 – 200, how many guesses could it take in the worst
case scenario?

b) Suggest a more efficient algorithm to accomplish this.


a. How many guesses could it take in the worst case scenario?
b. What if you double the max number?

36
ICS4U - Java

Big-O Notation Explained with Examples (developerinsider.co)

The most important part of a computer program is that it works. The second most important
consideration is how efficient the code runs and Big-O notation is a way of describing the relative
complexity / computational use of your programs. Better algorithms will still run quickly when the data
sets become very large. Bad algorithms will hit a computational wall when data sets become very large.

Examples:

O(1): constant

Regardless of how big your data set is, the computational cost is constant.

Example:

 Print the 5th item of an array:


System.out.println("the fifth item is " + x[4]);

Explanation: the size of array x[] has no impact on how long this takes. x[] could be 10
items or 1, 000, 000 items long. It still takes the same amount of time to print the 5 th
item.

O(n): linear

The cost increases linearly with your data set size (e.g. if the data set is twice the size, the
algorithm takes twice as long.

Examples:

 The first addition example on the last page is O(n). If you had n digit numbers, it takes n
additions of individual digits.

 Add all the elements in an array:

a) Five item list:


int x[] = new int[] {0, 1, 2, 3, 4};
int sum = 0;
for (int i = 0; i<x.length; i++){
sum += x[i];
}
b) Ten item list:
int x[] = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int sum = 0;
for (int i = 0; i<x.length; i++){
sum += x[i];
}

Since list (b) is twice as long, the for loop must iterate twice as many times. If the array
is n items long, the loop will iterate n times. This is O(n)

37
ICS4U - Java

O(n2): quadratic

As the data set grows, the cost increases as the square of the growth.

Example:

1) Everyday Multiplication:
2x3  1 operation (2 x 3)
21 x 31  4 operations (1 x 2, 1 x 2, 3 x 2, 3 x 1)
211 x 311  9 operations

2) Example 2 from the first page: nested for loops: outputting a multiplication tables:

int numberOfCalcs = 0;
for (int i = 1; i <= 10; i++){
for (int j = 1; j <= 10; j++){
System.out.println(i + " x " + j + " = " + i*j);
numberOfCalcs ++;
}
}

This code outputs every multiplication from 1 x 1 to 10 x 10. Integer i first takes a value of 1, and
j takes values 1 through 10. Then i takes value 2 and the process repeats. There are clearly 10 x
10 (102) calculations here. The variable numberOfCalcs will be 100. If we increase i and j to a
maximum of 20, then there will be 20 2 = 400 calculations.

A nested for loop (a for loop in a for loop) is O(n 2). Likewise, if you had a third nested for loop, it
would be O(n3)

Other Important Big-O Complexities:

O(log n): logarithmic.

Example:

 The third example on the first page: higher/lower number guessing game. Every
computation divides the data in half.

O(constantn) / O(2n): exponential.

Algorithms that use recursion can be exponential. We will study this later in the course.

38
ICS4U - Java

This graph helps you visualize Big O notation for algorithms. You can see that O(n 2) the computation
time increases much more drastically for larger data sets.

39
ICS4U - Java

So how do we find the Big O of a computer program?

Rule: You focus on the most complex part of the program and assume the worst case scenario.

Example: looking up a name in the phone book to get the phone number. You can do this in many ways:

1) Start from page 1 and keep flipping pages until you get there.

Best case: it’s on the first page O(1)


Worst case: it’s on the last page O(n)
Expected case: it’s near the middle O(n/2)
We would say this algorithm is O(n) in the possible case that the name is zena zebra.

2) Keep bisecting the telephone book. First cut it in half at a-h / h-z. Then cut those halves in half,
etc.

Best case: it’s on the first page O(1)

Worst case: keep dividing by 2 and its on the very last page O(log n)

Final answer: O(log n)

General Rules:

- A single computation:

- A for loop that runs a set number of times regardless of data set size (e.g. always doing
something 3 times):

- A for loop that runs n times, for example, goes through an array of length n:

- A for loop that runs n times followed by another for loop that runs n times:

- A for loop that runs n times inside another for loop that runs n times:

- A for loop that runs n times inside another for loop that runs m times:

- A process that splits the data you need to look at in half every iteration:

40
ICS4U - Java

Practice: With a partner determine the Big O complexity of the following blocks of code:

Example: Big O Complexity:


// 1) a calculation
double x = Math.pow(3, 2);

// 2) three cheers for Mr. Craig!


for (int i = 0; i<3; i++){
System.out.println("hip, hip... Hooray!");
}

// 3) squaring the items in a list


int y[] = new int[] {5, 6, 7, 8, 9};
for (int i = 0; i<y.length; i++){
System.out.println(y[i]*y[i]);
}

// 4) nested for loops of size N and M


for (int i = 0; i < dataSetN; i++){
for (int j = 0; j < dataSetM; j++){
// do something
}
}

// 5) nested for loops of size N and N


for (int i = 0; i < dataSetN; i++){
for (int j = 0; j < dataSetN; j++){
// do something
}
}

// 6) nested for loops of size N and 3


for (int i = 0; i < dataSetN; i++){
for (int j = 0; j > 3; j++){ // always 3
// do something
}
}

// 7) populating a 3-dimensional array with zeroes


int nums[][][] = new int[dataSetN][dataSetN][dataSetN];

for (int i = 0; i < dataSetN; i++){


for (int j = 0; j < dataSetN; j++){
for (int k = 0; k < dataSetN; k++){
nums[i][j][k] = 0;
}
}
}

// 8) nested for loop followed by single for loop


for (int i = 0; i < dataSetN; i++){
for (int j = 0; j < dataSetN; j++){
// do something
}
}

for (int i = 0; i < dataSetN; i++){


// do something
}

41
ICS4U - Java

Success Criteria: I can…


Explain the purpose of big O notation
State the big O complexity for various programs / algorithms

42
ICS4U - Java

19: Error Handling


Error handling is a means to dealing with inappropriate data entered by the user. For example, run this
code and input a letter instead of a number:
import java.util.Scanner;

class Scratch {

public static void main(String[] args){


Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scan.nextInt();
}
}

If you input anything other than an integer your program will crash with:

Try-Catch Blocks
To deal with this, anytime you take in input from the user that may be inappropriate, you have to use a
try-catch block.
try {
// the line that might crash
} catch (InputMismatchException e) {
// what to do if crash (error message)
}

This program demonstrates a try-catch block:


import java.util.InputMismatchException;
import java.util.Scanner;

class Scratch {

public static void main(String[] args){


Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
int num;

try { // the line that might crash


num = scan.nextInt();
} catch (InputMismatchException e){
// what to do in case of that error
System.out.println("inappropriate input ");
}

}
}

43
ICS4U - Java

We can use a while loop to force appropriate input:

import java.util.InputMismatchException;
import java.util.Scanner;

class trycatchexample {

public static void main(String[] args) {


Scanner scan = new Scanner(System.in);
int num = 0;

while (true) {
System.out.println("Enter a number: ");
try {
num = scan.nextInt();
break; // if it works
} catch (InputMismatchException e) {
System.out.println("inappropriate input, please try again");
scan.next(); // this clears the scanner input }
}
}
System.out.println("your number is: " + num);
}
}

The line scan.next() must be there to clear the bad scanner input. You can try running the program
without it and giving bad input to see what happens.

Checking first if its an integer, then if its in the correct range (1-10):
while (true) {
System.out.println("Enter a number between 1 and 10: ");
try {
num = scan.nextInt();
if ((num >= 1) && (num <= 10)) {
break;
} else {
System.out.println("number must be between 1 and 10.");
}
} catch (InputMismatchException e) {
System.out.println("inappropriate input, please try again");
scan.next(); // this clears the scanner input / needs to be here
}
}

44
ICS4U - Java

Exercises:

a) Create a program that asks the user to enter test scores. Use a while loop to have them keep
adding scores until they are done and store the scores in an array or ArrayList. Use a try/catch
block to ensure appropriate input. Also make sure all scores are between 0 and 100. After
collecting the input, output all test scores in a nice way.
b) Pythagorean theorem program that makes sure inputs A and B are doubles, and also
positive values
c) make a program that asks the user to enter even numbers. Make it crash proof and not
accept odd numbers. Store them in an array and use a for loop at the end to output
them all in one line

Success Criteria: I can…


Explain the purpose of a try-catch block
Use for loops to go through arrays (e.g. add all the elements, compare elements)
Write programs that use try-catch blocks (e.g. Pythagorean theorem)

45
ICS4U - Java

20: Program Testing: Test Suites and Tracing


TBD

46
ICS4U - Java

21: Multidimensional Arrays


In order to make something like a table (e.g. tic-tac-toe board, spreadsheet), we need s two-dimensional
(2D) array. We can make these in Java as well as higher dimensional arrays.

Let’s look at the structure of different arrays:

1D Array:
int num[] = new int[] {1, 2, 3};
Looks like:

1 2 3
What is the value of

a) num[0] =
b) num[1] =
c) num[2] =

2D Array: (i.e. a table)

Initializing the table:


int table[][] = new int[3][4]; // 3 rows, 4 columns

Creates a 3 row x 4 column table:

Col 0 Col 1 Col 2 Col 3


Row (0, 0) (0, 1) (0, 2) (0, 3) 0
Row (1, 0) (1, 1) (1, 2) (1, 3) 1
Row (2, 0) (2, 1) (2, 2) (2, 3) 2

Example: look at this table and answer the questions:

“A” “B” “C” “D”


“E” “F” “G” “H”
“I” “J” “K” “L”
“M” “N” “O” “P”
What letter is in the following locations?
a) (1, 0):
b) (2, 3):
c) (3, 2):

47
ICS4U - Java

Type in this code and run.

int table[][] = new int[3][4];


System.out.println(table[0].length);
System.out.println(table.length);

What is table[0].length telling you?


What is table.length telling you?

Populating the table:


You can populate a table manually, for example:
String info[][] = new String[][] {{"Matt","Drorit"},{"best","second best"}};

or:

String tictactoe[][] = new String[][] {{"O","O","O"},{"X","X","X"},{"O","O","O"}};

or:

int numTable[][] = new int[][] {{1, 2}, {3, 4}};

We can also use nested for loops to put, say, random numbers in each cell:

int table[][] = new int[3][4];


for (int i = 0; i<table.length; i++){
for (int j = 0; j<table[0].length; j++){
table[i][j] = (int)(1+Math.random()*9);
}
}

Outputting the table:

We can output the table in a nice way the same way we did it in python; by building a string for
each row, outputting the entire line, then moving down to the next row:
String currentLine;
for (int r = 0; r<table.length; r++){
currentLine = ""; // blank string for a new row
for (int c = 0; c<table[0].length; c++){
currentLine += String.valueOf(table[r][c]) + " "; // add current cell
}
System.out.println(currentLine); // output the line
}

I often use “r” and “c” for “row” and “column” but you can still use “i" and “j” if you want.

48
ICS4U - Java

Exercises:

1) Create a table of 3 rows and 3 columns. The first row is first name, second row is last name,
third row is favorite colour. Ask two of your friends their favorite colour. Then manually create a
table and output it like this:

2) Change the table output so that it looks like this:

3) After drawing the entire table, ask the user which column to output, and then output the
information in this format:

4) Have the user input the desired number of rows and columns for a table of integers.
a. Create a table of that size and populate it with random numbers between 0 and 100.
b. Output the table
c. Calculate the average of each row and add that to each output line:

5) Generate 5 x 5 tables using for loops that look like these (no hard coding numbers):

*** the last one requires the use of modulus (%2 == 0) and a few if statements.

49
ICS4U - Java

Success Criteria: I can…


Declare multidimensional arrays (2D) of different data types
Use nested for loops to assign values to a 2D array
Use nested for loops to output a 2D table

50
ICS4U - Java

22: Methods
Methods (a.k.a. Functions) are ways of isolating code to perform specific functions. Here’s a method
called “greet” that asks for a user’s name and greets them with a lovely message:

Basic Method:
import java.util.Scanner;

class Scratch {

private static void greet(){


Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String name = scan.nextLine();
System.out.println("Hello, " + name + ", it's wonderful to see you!");
}

public static void main(String[] args){


greet();
}
}

Notes:

1) The method is declared inside the main class (Scratch), but outside of the main method. I usually
put it above, but below is also fine.
2) “private” means it can only be used within this class. More on this later. You will need to have
that word there.
3) “static” is too much to get into here, but that word needs to be there.
4) “void” means it doesn’t return any values back to the main method.

Argument Version:

In this new version, the user enters their name in the main method, it is passed to the function as an
argument and the function outputs the message.
class Scratch {

private static void greet(String name){


System.out.println("Hello, " + name + ", it's wonderful to see you!");
}

public static void main(String[] args){


Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String name = scan.nextLine();
greet(name);
}
}
Notes:

1) When I call the great function, I am sending the name as an argument to the function.
2) The name from the main method is now stored in the local variable “name” in the greet
function.

51
ICS4U - Java

Example 2 – sending two arguments:


public static void main(String[] args) {
perimeter(14, 5);

// calculates and outputs the perimeter


private static void perimeter(double length, double width){
double perim = 2 * length + 2 * width;
System.out.println("the perimeter is " + perim + " units");
}

You can send as many arguments as you like of different data types, even arrays. For example:

private static void myMethod(int x, String name, double d[]){


// code goes here
}

Exercises:

Exercises:

1) Main method: ask the user for 3 foods (with 3 separate String). Send all three to a method called
favFoods(String food1, String food2, String food3) and output their three favorite foods in a fun
way.

2) Main method: ask the user for sides A and B of a right triangle. Send them to a method
getHypotenuse() that takes both sides as arguments. Calculate and output the hypotenuse.

3) Main method: generate 2 random die rolls 1-6. Send both rolls to the method getDieResults().
The method should output the following messages based on the sum:
7, 11  “winner!”
6  “tie!”
2  “snake eyes!”
Otherwise if its > 5  “greater than 5”
Otherwise, “less than 5”

4) Ask the user their country of birth and age. Send both to a method called isEligible(). If there
country of birth starts with “can” (ignore case) and they are at least 18, output “you are
eligible”. Otherwise, output “you are NOT eligble.”

52
ICS4U - Java

Methods with Arguments and Returns:

Copy and paste and run this code:


import java.util.Scanner;

class Scratch {

private static int add(int n1, int n2){


int sum = n1 + n2;
return sum;
}

public static void main(String[] args){


Scanner scan = new Scanner(System.in);
System.out.println("What is the first number? ");
int num1 = scan.nextInt();
System.out.println("What is the second number? ");
int num2 = scan.nextInt();

int total = add(num1, num2);

System.out.println("The total is " + total);


}
}

53
ICS4U - Java

Here is a screenshot:

Notes:

 Line 5: I changed the word “void” to “int” because this method returns an integer back to the
main method.
 Line 5: you can have 2 arguments or as many as you want for your function.
 Line 7: returns the sum back to the main method
 Line 17: this line calls the add function, sends it both arguments (num1 and num2) which will be
stored in the functions local variables n1 and n2.
 Line 17: the int total accepts the value returned by the function to be used later.

54
ICS4U - Java

Exercises: create, implement and run each method below:

1) Extend the above program to include methods that perform subtraction, multiplication and
division.

2) Takes the radius of a circle as the argument and returns the area.
private static double getCircleArea(double radius){}

3) Takes sides A and B of a right triangle and returns the hypotenuse.


private static double getHypotenuse(double a, double b){}

4) Takes the length and width of a rectangular and returns the perimeter.
private static double getPerimeter(double length, double width){}

5) Takes the radius and height of a cylinder and returns the volume.
private static double getCylVol(double height, double radius){}

6) Takes no arguments, but returns a random coin flip String of “H” or “T”.

private static String randomFlip(){}

7) Takes the country of citizenship and age of the user and returns boolean true if they are eligible
to vote, or false if not. (They are eligible if they are at least age 18 and are citizens of Canada).
private static boolean isEligible(int age, String country){}

8) Takes a min and max integer. Returns a random number between them (inclusive). Bonus: make
it evenly weighted for the lowest and highest values.
private static int randInt(int min, int max){}

9) Extension: takes an integer for the size of an array, min and max, returns an array of that size
with random numbers between min and max.
private static int[] getRanIntArray(int size, int min, int max){}

10) Harder: Takes a double as value and the number of integers desired. Returns a String of that
double with the correct number of decimal places.
private static String formatDouble(double value, int decimals){}

55
ICS4U - Java

Example 2: A Method to determine voting eligibility


import java.util.Scanner;

class Scratch {

// determines if eligible to vote if age >= 18 and they are Canadian


private static boolean checkeligibility(int age, String country){
String countryLower = country.toLowerCase(); // ignore capitals
if (age >= 18 && countryLower.equals("canada")){
return true;
} else {
return false;
}
}

public static void main(String[] args){


Scanner scan = new Scanner(System.in);
// getting age
System.out.println("How old are you? ");
int age = scan.nextInt();
// getting country
System.out.println("What country is your citizenship? ");
scan.nextLine(); // needs to be here in this particular case
String country = scan.nextLine();

// call the method


boolean isEligible = checkeligibility(age, country);

// use the returned value


if (isEligible) {
System.out.println("You may vote!");
} else{
System.out.println("too bad, so sad");
}
}
}

Questions:

1) What is the name of the function?


2) What are the arguments of the function?
3) What is the return type of the function?

Success Criteria: I can…


Write basic methods with no arguments or returns
Write methods that accept different / multiple data types as arguments
Write methods that return different data types, including arrays
Create methods to solve various problems and demonstrate their usage through the main()
method

56
ICS4U - Java

Example 3: Exception Catching in a Method


import java.util.Scanner;

class Scratch {

// determines if a given value is an integer and returns true or false


private static boolean isInteger(String value){
try {
int x = Integer.valueOf(value);
return true;
} catch (NumberFormatException e){
return false;
}
}

public static void main(String[] args){


Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
String s = scan.nextLine();
int num;
if (isInteger(s)){
num = Integer.valueOf(s);
System.out.println("Good!");
} else {
System.out.println("Bad!");
}
}
}

Exercises: write and implement each function to show me they are working. These are useful functions
you can use in future programs:

1) isNumeric: Write more general version of isInteger() called isNumeric(). It checks if the given
string is any number (e.g. a double), not just an integer.

2) print: Write a method called “print()” that uses System.out.println() to print a string, but doesn’t
require you to write all that out, for example:

print(“Hello, World!”) would do the same as System.out.println(“Hello, World!”)

3) random: write a function to generate a random number. It should take as arguments the
minimum and maximum value (e.g. 1 and 10) and return a random double between them. It
can use Math.random(), but this new function will be much more useful for you.

4) addArray: Write a method called addArray(double[] vals) that takes an array of doubles (vals) as
the parameter, adds them all up, and returns the sum.

5) avgArray: Write a method called avgArray() that takes an array of doubles and calculates and
returns the average. It should use your previous method addArray

57
ICS4U - Java

23: Reading and Writing to .txt Files


Storing data in variables will only work as long as the program is running and can be stored to RAM. If
you want to save those values to be loaded next time, we need to write information into an external file.
The easiest type of file is a *.txt file (*.doc will also work). Data is written to text files as a string. Here is
an example
import java.io.*;
import java.util.Scanner;
public class scratch {

public static void main (String[] args) throws IOException {


Scanner scan = new Scanner(System.in);
String fileName;
System.out.println("Enter the name of the file without .txt: ");
fileName= scan.nextLine() + ".txt"; //*.doc also works

FileWriter fw= new FileWriter(fileName); //streams to file


PrintWriter output = new PrintWriter(fw); //controls form/amount of text
int number=15;
output.println(number); // prints number then moves to the next line
output.close(); // closing the file.
}
}

*** anytime you use a file reader or writer, there is the possibility of the program throwing an exception
if the file can’t be found / can’t be written to. You can use try/catch blocks, but generally speaking you
can also simply add throws IOException in the method signature.

Run the program. Find the file you made and open it to see what is inside.

Exercises:

a) Create a program to write “Hello, World!” to one line.


b) Write “Hello, World!” 10 times on separate lines with a for loop.
c) Have the user input a sentence of many words. Write each word to a new line. Use a for loop
and search for empty spaced in the string “ “ to find each next word.
d) What happens when you try to write to a file that already exists? Does it overwrite the previous
data or simply add to it?

If you want to append to an already-existing file without overriding what is already in there, change the
line to:
FileWriter fw= new FileWriter(fileName, true);
// true appends to existing file

e) Redo exercise (c) but allow rewriting. Run the program 3 times with new sentences. Instead of
asking for a file name, just write to “output.txt”.

f) Have the user input a minimum and maximum number. Output all odd numbers between both
values into “output.txt”.

58
ICS4U - Java

g) Redo exercise (f) but output them into “output.xls” (an excel spreadsheet). Open the file in Excel
or google sheets (ignore the warnings).

Reading from your file:


import java.util.Scanner;
import java.io.*;
public class scratch {

private static String fileName, line;

public static void main (String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("What is the name of the file?");
String fileName = sc.nextLine();
try {
//Opens up an stream between program and file-fileName
FileReader fr= new FileReader(fileName);
//Opens a container that holds data arriving from fileName
BufferedReader input= new BufferedReader (fr);
//Read 10 lines.
for (int i = 0; i<10; i++) {
line = input.readLine();
System.out.println(line);
}
//closes both BufferedReader and FileReader
input.close();

}//end of try
catch(IOException e){
System.out.println("This prints because requested file does not exist.");
}//end of catch
System.out.println(line);
}

 If the filename is always the same, you can hardcode it rather than asking the user. You should
always use try/catch just in case the file isn’t in the right place.

Success Criteria: I can…


Use the filewriter and printwriter classes to create .txt files and write data to them
Use the filereader class to read information from a .txt file and store that information in an
appropriate variable or array
Write programs that use file reading, work with the data, then output new data to a new or the
same file
Specify a file path for reading and writing

59
ICS4U - Java

Other methods in the FileReader class:

Class: FileReader
Method Description
FileReader(String opens a stream so that data may flow from
fileName) the file stored in the String fileName to
the program
Class: BufferedReader
Method Description
BufferedReader(Reader creates a container holding data arriving
fr) through the stream created by fr.
BufferedReader (fr, int n determines the number of bytes of data
n) held in the buffer at any given time
close() closes the buffer as well as the stream
read() returns the next character from the buffer
(-1 if at end of string)
readLine() returns a line of text. Returns null if at
end of file.
skip(long n) skips up to n characters, and returns the
number of characters skipped.

Exercises:

a) Create a file called information.txt. Make up 3 sentences and write them in the first three lines
of the file.
b) Read and output the first line.
c) Read and output the first word of each line
d) Try reading 10 lines and output each line. How do you know when you’ve reached the end of
your file?
e) Change program (e) to recognize when it reached the end of the information in the file. Have it
break out of the loop when it gets to the end, and count/output the number of lines of
information in the file
f) Write a program that writes 100 random numbers between 1 and 100 into a file called
“randomnums.txt”. Do this in a method. Then call a second method that reads the file and find
the average of all numbers. It should return the average back to the main method and output
the value.
g) Add to the previous program: it now first stores the 100 random values in an integer array. It
then goes through the array to write the data to a file, then reads from the file and stores the
data into a new array of the correct size.

60
ICS4U - Java

24: Additional Reading Methods


Exercises:
Write the following methods. For each method, add comment describing the O(n) complexity and use
try/catch blocks in the methods as required. The first method below is done for you.

1)
// returns the number of lines in a .txt file
private static int getlines(String fileName){}

private static int getlines(String fileName){


int count = 0;
try{
FileReader fr= new FileReader(fileName);
BufferedReader input= new BufferedReader (fr);
String line = "";
while (line != null){
line = input.readLine();
count += 1;
}
count --;
input.close();

} catch (IOException e){


}
return count;
}

2)
// returns a specific line from a .txt file
private static String getline(String fileName, int line){}

3)
// takes a line from the getline method and returns the words as an array of
strings
// must be the exact size of the number of words - no padding
private static String[] getlinewords(String[] args) {}

4)
// returns every word in a .txt file as one String array. Uses the previous
method
private static String[] getallwords(String fileName){}

61
ICS4U - Java

25: Specifying Path for Writing Files


Using the previous code will write a file in the same directory as the java code file. Sometimes we want
to write a file to a specific directory (e.g. the user’s desktop). To do this we need to create an instance of
the File class:
import java.io.*;
public class scratch {

public static void main(String[] args) throws Exception{


try {
//On Windows~~~ the second "\" is needed due to escape characters
File f = new File("C:\\Users\\HP\\Desktop\\filename.txt");
// *** you can't create a file in root C:\ in windows

//On Mac and Linux~~~ File f= new


File("/Users/Matt/Desktop/filename.txt");

FileWriter fw = new FileWriter(f);


PrintWriter pw = new PrintWriter(fw);
pw.println("line 1");
pw.println("this is the second line");
pw.close();

// reading file
BufferedReader br = new BufferedReader(new FileReader(f));
System.out.println(br.readLine());

for (int i = 0; i<20; i++){


System.out.println(br.readLine());
if (br.readLine() == null){
break;
}
}
} catch (FileNotFoundException e){
System.out.println("Error: unable to write to file");
}
}//end of main

}// end of method and end of class

As this example shows, writing to a directory involves different syntax depending on the operating
system. You can specify the path based on the operating system. This code lets you check the operating
system:
String OS = System.getProperty("os.name");
System.out.println(OS);

But you can get many different versions of MAC OS so an exact name match is tricky. Instead, try:
String OS = System.getProperty("os.name").toLowerCase();
if(OS.contains("win")){
System.out.println("It's Windows");
}else if(OS.contains("mac")){
System.out.println("It's an Apple");
}

62
ICS4U - Java

Now you can tailor the file path based on the operating system.

Exercises:

a) Output your operating system using the code above.


b) Adjust the File program: it should ask the user what they want the filename to be (e.g. *.txt),
then it should create that file in your desktop directory. You can file the file with 10 lines of
random integers between 1 and 10.
c) Adjust the program so that the file writing takes places in this method that you pass File f to:

private static void writefile(File f) throws IOException {}

And the reading happens in:

private static void readfile(File f) throws IOException {}

(you must include throws IOException in each method)

63
ICS4U - Java

26: Binary File IO


Writing to text files does not allow random access. You have to start at the first byte and then move to
each successive byte in order. When writing to binary files, every piece of data entered has the same
constant size. If each item has a length of 10 bytes:

Item 1  starts at byte 0

Item 2  starts at byte 10

Item 3  starts at byte 20

Item 50  starts at byte 50 * 10 – 10 = 490

You can locate a specific item with an equation, without having to read the entire file up to that point.
E.g. if the item length is n bytes, then the item at location L is:

item = L * n – n = n(L-1)

RandomAccessFile is a class that writes to binary data files. To use it we must use:
a) import java.io.*;
b) throws IOException

Sample using binary files:


import java.io.*;
public class scratch {
public static void main(String[] args) throws IOException{
// you can specify a path if you want
RandomAccessFile raf= new RandomAccessFile("C:\\Users\\HP\\Desktop\\binary.dat","rw");

//remember that int(s) take up 4 bytes


raf.writeInt(10);//this value will begin at bye 0
raf.writeInt(20);//this value will begin at byte 4
raf.writeInt(30);//this value will begin at byte 8
raf.writeInt(40);//this value will begin at byte 12
raf.close();
raf= new RandomAccessFile("C:\\Users\\HP\\Desktop\\binary.dat","rw");

//preparing to read: 30
raf.seek(8);
System.out.println(raf.readInt());

//preparing to read: 20
raf.seek(4);
System.out.println(raf.readInt());

// how many bytes are stored


System.out.println("The file has " + raf.length() + " bytes");

int numItems = (int)raf.length()/4;

// how many items are stored


System.out.println("The file has " + numItems + " integers");

}//end of main method.


}//end of RA class

64
ICS4U - Java

Different data type sizes:

Type Bytes Values


Byte 1 -128 to 127
Short 2 -32, 768 to 32, 767
Int 4 -2, 147, 483, 648 to 2, 147, 483, 647
Long 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Float 4 6 to 7 decimal digits
Double 8 15 decimal digits
Char 2 Single character or letter

Exercises:

a) modify the program to write every multiple of 7 up to 100 with a for loop, and then output them
all with a for loop.
b) Modify (a) to store the values in an array before outputting them.
c) Use writeChar and readChar to write your first name in individual characters. Read them and
output them.
d) Modify (c) to store your name first in a String. Then use charAt() to write the chars into the file.
e) Add to program (b): use a for loop to read all the characters of your name and add them to a
string. After building the entire string, output the string.
f) Use writeLong / readLong to write the perfect squares of every integer from 1 – 1000. Then ask
the user which integer to look for. Calculate the position of that integer, seek that location and
output the value. Check your math to make sure you output the correct number.

Success Criteria: I can…


Read / write to a binary file, allowing random access
Decide whether a binary or .txt file is appropriate for various programs

65
ICS4U - Java

27: Reading/Writing In Class Task Practice


Create a program that reads data from the file “rawdata.txt”. It will store employee information:

a) Name
b) Hours worked
c) Rate of pay (e.g. 20  20 dollars an hour)

Requirements:

1) Read the given rawdata.txt file. Store the employee names, hours and rates in three separate
arrays.
2) Output the information in a nice way.
3) Write it to a new file called “calcdata.txt”. It should hold:
a. Name
b. Total pay (hours * pay rate)
4) Use should be able to input an employees order in the file (e.g. record 0, 1, 2, …) and it should
read and output their name and total pay from calcdata.txt

66

You might also like