Programming With Java - 2022.23 - CSE
Programming With Java - 2022.23 - CSE
FACULTY OF ENGINEERING
Course Lecturers
Vincent M. Nofong, Ph.D.
Albert K. K. Ansah, Ph.D.
Evans Obu, Ph.D. Cand.
January 2023
Compiled by Vincent M. Nofong, PhD. ii
Compiled from various reference materials by:
Lecture notes for the course CE 277 (Programming with Java) for the Computer Science and Engi-
neering Department at the University of Mines and Technology, Tarkwa - Ghana.
Note:
Due to the practical nature of this course, students are advised to attend all lectures, tutorials and
practicals. For unforeseen reasons that students are unable to attend lectures, tutorials or practi-
cals, students can watch some of my tutorials on this course on YouTube using the following link
(https://www.youtube.com/channel/UCSxKRS6RNGelv55Dy4H4Z3A/videos)
COURSE ASSESSMENT
(a) Attendance (10%): Attendance and participation in all class and practical activities.
(b) Theoretical Quizzes (10%): There will be at least two (2) written quizzes. Date of
quizzes will be announced in class.
(c) Practical Quizzes and Assignments (20%): There will be a number of practical quizzes
and one take home assignment. Dates of quizzes will be announced in class.
2. End of Semester Examinations (60%): This will comprise of the following components:
List of Figures ix
List of Tables xi
1 Introduction 1
1.1 Introduction to Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Categories of Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 The Compiler vs Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 The Java Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.1 Java Development Toolkit and its Configuration . . . . . . . . . . . . . . . . . 3
1.3.1.1 Checking and Installing the JDK Version . . . . . . . . . . . . . . . . 3
1.3.1.2 Setting/Configuring the Java Path . . . . . . . . . . . . . . . . . . . . 4
1.3.2 Creating First Java Codes and Testing in PowerShell . . . . . . . . . . . . . . . 4
1.3.2.1 Installing IntelliJ IDEA . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Elementary Programming 7
2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Assignment Statements and Assignment Expressions . . . . . . . . . . . . . . . . . . . 8
2.3 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3.1 Arithmetic Functions - Rules of Operator Precedence . . . . . . . . . . . . . . 9
2.4 Input Reading from Keyboard or Console . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.4.1 Scanner Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4.1.1 Practicals with Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.5 Numeric Data Types and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.5.1 Numeric Operators - Increment and Decrement Operators . . . . . . . . . . . . 12
2.5.2 Numeric Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6 Decision Making - Equality and Relational Operators . . . . . . . . . . . . . . . . . . . 13
2.7 Practicals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Introduction
A computer as basically is an electronic device (programmable) that takes information in one form
and processes it to produce data in another form. Modern computers consists of the following groups
of components: Input device(s), Processor(s), Storage device(s), Output device(s), and Software. For
this course we will focus on developing computer software using Java.
A simple overview of the main computer components is shown in Figure 1.1. The computer
hardware which is at the bottom consists of chips, boards, disks, a keyboard, a monitor, and similar
physical objects. On top of the hardware is the software which consists of the operating system,
application programs, and other system programs.
An Operating System (OS) is a program that controls the execution of application programs
and acts as an interface between applications and the computer hardware. As shown in Figure 1.1,
the operating system runs on the bare hardware and provides the base for all the other software.
An application program however is a program that is used to perform a specific task, for
example, the email browsers, media players, etc. We will learn to create some simple application
programs with Java
• Machine Language: This is the native language of computers that is made of a set of built-in
primitive instructions. These instructions are often in binary code. E.g 1011101001. It is not
easy to program, learn and/or modify code.
• Assembly Language: This was developed to make programming easier that uses mnemonics1
to represent machine language instructions. For example, the mnemonic add means add two
numbers and sub means subtract two numbers. An assembler is needed to translate assembly
language into machine code before it can be executed as computers cannot execute assembly
language.
• High Level Languages: These are platform dependent which are “English-like”, and are easy
to learn and use. Instructions are written in the form of statements, for example, ExamScore
= 25 + 42;. There are many high level languages, designed for specific purposes. Examples:
Ada, Basic, C, C++, C#, Java, Pascal, Python, Visual Basic, R, etc. A program written in
high level language is called the source program or source code. This source code has to be
translated using an interpreter or compiler into machine code for execution.
The major distinction between how the interpreter and compiler work is that: the interpreter
reads one statement from the source code, translates it to the machine code or virtual machine code,
and then executes the statement while the compiler translates the entire source code into a machine-
code file, and executes the machine-code file. Figure 1.2 shows detailed distinctions between the
compiler and the interpreter
Java programming language was originally designed for programming consumer devices. It was first
successfully used to write Internet applets. Java is much easier to use than its closest rival, C++.
Additionally it is very suitable for beginners since it is portable and applications written in Java will
run without change on Windows, UNIX, Linux, Macintosh.
• Java Standard Edition (Java SE): For developing client-side applications which can run
standalone or as applets on a Web browser.
• Java Micro Edition (Java ME): For developing applications for mobile devices
• JavaFX: For creating rich internet applications using a lightweight user-interface API.
Java has its own Application Program Interface which contains predefined classes and interfaces
for developing Java programs. Java has also has it own language specifications (a technical definition
of the Java programming language’s syntax and semantics) which can be downloaded from https:
//docs.oracle.com/javase/specs/. Before a Java application will run on any operating system,
you need to install the Java Development Toolkit (JDK) and the Java Runtime Environment.
The Java Development Toolkit (JDK) consists of a set of separate programs, which are invoked from a
command line, for developing and testing Java programs. It is important to install the JDK as a Java
developer since it contains the tools (Java Runtime Environment, interpreter/loader-java, compiler-
javac, etc) that are needed for Java development. Before installing the JDK on a computer, it is worth
it checking to see if it is already installed or not.
The JDK version can be checked on the command prompt using the following steps:
4. To check the Java compiler version: Type javac -version and press the Enter key
When the JDK version check indicates the lack of JDK on the system, it can be downloaded
oracle.com and installed. It is worth noting that there are several versions of the JDK available
which can be downloaded and install. It is however advisable to select one of the latest versions for
installation.
After installing the JDK, the path to the tools need to be configured to ensure the Command Prompt
or PowerShell can access those tools when invoked. The Java Path can be configured using the
following steps:
1. Go to My Computer Folder
Note: We will do this during practicals and learn how to create the JAVA HOME path at the System
Variables. Students can watch my tutorial (https://www.youtube.com/watch?v=QsAMhz-K8Ws) on
installing and configuring the Java Path.
4. Open the PowerShell or Command Prompt where your Java Source Code is saved.
Students are advised to install IntelliJ IDEA IDE. Students can download the Community or Ultimate
version of Intellij IDEA. For the Ultimate version, students will need to register as a student using
the institutional email. Installation steps will be demonstrated during lectures. Students can watch
the my tutorial (https://www.youtube.com/watch?v=CG9m025qrQg) on how to install Intellij IDEA
Elementary Programming
2.1 Variables
A variable is a storage location in a computer program. Each variable has a name and is supposed to
hold a value. Variables are used to store values which are to be used later in a program. Variables are
used for representing data of a certain type. To use a variable, you declare it by telling the compiler
its name as well as the type of data it can store. Variable declaration is important to ensure the
compiler allocates an appropriate amount of memory space for the variable based on its data type.
The syntax for declaring a variable is:
2. Instance Variable: This is a variable which is declared inside the class but outside the method,
and is not static.
class variables{
int studentMark =78;//An instance variable
static double studentCWA; //A static variable
void method(){
int classScore=33; //A local variable
}
}
There are some few simple rules for the names of variables, methods, and classes:
• Names are case sensitive, i.e., studentMark and studentmark are different names
•Variables of the same type can be declared together. E.g: int i, j, k; Java
has two data types available for which variables can be declared on:
1. Primitive Data Types: byte (number, 1 byte), short (number, 2 bytes), int (number, 4 bytes),
long (number, 8 bytes), float (float number, 4 bytes), double (float number, 8 bytes), char (a
character, 2 bytes), boolean (true or false, 1 bit)
Java supports arithmetic operations for; addition, subtraction, multiplication, division and remainder.
Figure 2.2 shows the six arithmetic operators and how they are expressed in Java.
Arithmetic expressions must be written in straight-line form to facilitate entering programs into
the computer. For instance, x = ab will be written as x = a/b;
For the arithmetic functions supported in Java, when there are two or more operators in a function,
their execution is governed by a set of rules as shown in Figure 2.2.
Notwithstanding, these rules, it is advisable to use parentheses when writing arithmetic functions
in Java. This is because functions in parentheses are evaluated first.
As user applications execute, at certain time points, they would need to take inputs from the user in
order to continue their execution. To allow input and output of information, Java uses:
where by default, the output device is the monitor, and, the input device is the Keyboard.
To display information to the console, the print, println, etc methods are used in Java. Though
the console input is not directly supported in Java, the Scanner or BufferedReader classes can be used
to create objects that read from the console using System.in. For this course, we will learn to use
only the Scanner for reading inputs in our Java applications. Figure 2.3 shows the main distinctions
between the Scanner and BufferedReader classes.
The Scanner class can be used to create an object to read input from System.in as:
Where the syntax new Scanner(System.in) creates an object of the Scanner type while the syntax
Scanner input declares “input” as a variable whose type is Scanner. It is worth noting that all created
scanner objects must be closed once they are no more being used.
We will learn how to ensure only two integers are entered by the user under exception handling.
Java has six numeric data types for; integers (byte, short, int, long) and floating point numbers (float,
double) with five operators (+, −, /, ∗, % ). These numeric data types have different ranges and storage
sizes as depicted in Figure 2.4.
Java supports the increment (++) and decrement (–) operators which are shorthand for incrementing
a numeric variable by 1 and decrementing a numeric variable by 1 respectively. For example, given
int i =2; int j =2;
• i++; ⇒ i becomes 3
• j−−; ⇒ j becomes 1
The distinctions between post and pre increment or decrement are as shown in Figure 2.5.
Java supports a conversion of one numeric data to another type. You can always assign a value to a
numeric variable whose type supports a larger range of values. For example, you can assign a long
value to a float variable. However, you cannot assign a value to a variable of a type with a smaller
range unless you use type casting.
Casting is basically an operation that converts a value of one data type into a value of another
data type. Java supports two types of casting:
• Widening type: This is when a small range numeric type is converted to a numeric type with a
large range.
• Narrowing type: This is when a large range numeric type is converted to a numeric type with a
smaller range.
For example, System.out.println((double)2/3)) will cast(covert) the integer division and return
a double, while System.out.println((int)2.34) will cast the double to an integer. It is worth noting
that in casting a double to and integer, the fractional part will be truncated. It is also worth noting
that we can cast some Strings into doubles, integers, floats, etc. For example, given: String height =
”1.76”;, it can be converted to a double as double newHeight = Double.parseDouble(height);
Java supports operators for testing the equality and relation of variables. These equality and relational
operators supports in Java and their usage are as shown in Figures 2.6 and 2.7 respectively.
2.7 Practicals
3. Write a program that reads two integer inputs from a user and determines if the first is a multiple
of the second.
4. Write a program that reads a Celsius degree in a double value from the console, then converts
it to Fahrenheit and displays the result. The formula for the conversion is as follows:
9
Fahrenheit = ∗ celsius + 32 (2.1)
5
5. Body Mass Index (BMI) is a measure of health based on height and weight. It can be calculated
by taking your weight in kilograms and dividing it by the square of your height in meters. The
interpretation of BMI for people 20 years or older is as follows:
BMI < 18.5: Underweight
18.5 ≤ BMI < 25.0: Normal
25.0 ≤ BMI < 30.0: Overweight
30.0 ≤ BMI: Obese
Write a program that prompts the user to enter a weight in kilograms and height in meters and
displays the BMI and the health indication of the person
Mathematical Functions,
Characters and String
Figure 3.1 shows the supported trigonometric functions that are supported in Java and their
descriptions.
Java supports five exponential functions for performing exponential operations such as natural loga-
rithm, square root, etc. Figure 3.2 shows the supported in Java and their descriptions.
The service functions supported in Java can be grouped into; rounding methods, random method, and
the min, max and abs methods.
Java supports four rounding functions for rounding values to decimal places. Figure 3.3 shows the
supported rounding functions in Java and their descriptions.
These are methods for finding the; maximum value among a set with two items (e.g. Math.max(2.4,-
5.4)), minimum value among a set of two items (e.g. Math.min(-5.4, 4.1)), and the absolute value of
a given number (e.g. Math.abs(-5.4)) respectively.
The method Math.random() generates a random double value greater than or equal to 0.0 and less
than 1.0. To generate a random integer with the Math.random() in Java between 0 and n will be done
as: (int)(Math.random()* (n+1)). For example, (int)(Math.random()* 10) generates random integers
between 0 and 9
3.1.4 Practicals
1. Write a Java program that displays the sin, cos and tan of 30 degrees.
2. Write a Java program that displays the natural log of 45, square root of 29 and 565
3. Write a Java program that displays that rounds 4.53 and -3.1 using the ceil, floor and round
methods.
4. Write a Java program that divides 2 by 6 and return the answer in two decimal places.
(a) The maximum value for the set (-2.1, -1.5, -0.6)
(b) The minimum value for the set (-2.1, -1.5, -0.6)
(c) The absolute value for -1.51 and 1.51
Computers use binary numbers internally. Characters are stored in computers as a sequence of 0s and
1s - Popularly referred to as encoding1. The Unicode scheme and ASCII code scheme are two ways
to encode a character.
Figure 3.4: Commonly Used ASCII Codes and Their Unicode Values
Character declaration in Java is similar to String declaration but with single quotations marks (‘’).
For example, char letter = ‘B’; in Java will assign the character B to the variable letter.
Java uses a special notation (escape sequence) to represent special characters. The escape se-
quence consists of a backslash (\) followed by a character or a combination of digits For example, \t
is the escape sequence for the Tab character. Figure 3.5 shows some supported escape sequences in
Java and their descriptions.
A char can be cast into any numeric type, and vice versa. When an integer is cast into a char,
only its lower 16 bits of data are used while the other part is ignored.For example, in char ch =
(char)0XAB0041, the lower 16 bits hex code 0041 is assigned to ch while the remaining is ignored.
When a floating-point value is cast into a char, the floating-point value is first cast into an int, which
is then cast into a char. When a char is cast into a numeric type, the character’s Unicode is cast into
the specified numeric type.
Implicit casting (e.g. byte b = ‘a’;) can be used if the result of a casting fits into the target
variable, else explicit casting (e.g. byte b = (byte)‘\uFFF4’;)1 must be used.
Characters can be compared using the relational operators just like comparing two numbers. Com-
parison is done using the Unicodes of the two characters. As such ’a’ < ’b’ will return true since in
Unicode; ‘a’ = 97 and ‘b’ = 98 while ’a’ < ’A’ will return false since in Unicode; ‘a’ = 97 and ‘A’ =
65. Figure 3.6 shows some character testing methods and their descriptions.
3.2.4 Practicals
2. Write Java statements which convert the following numeric types into characters: 99, 225.
3. Write Java statements which convert the following characters into integers: A, !, *, i.
The String data type is used to represent a string of characters. For example, String studentName
= “John Robertson”;. For string manipulation, Java provides the following methods shown in Figure
3.7 that support manipulation of strings.
The length() returns the number of characters in a string. For example, given, String name =“John
Mathews”;, the code System.out.println(“The length of ” + name + “ is ” +name.length()); will
return “The length of John Mathews is 12”.
The n.charAt(index) method can be used to retrieve a specific character in a string n where the
index is between 0 and n.length()-1. For example, given, String name =“John Mathews”;, then
System.out.println(name.charAt(5)); will return M which is at index 5 as illustrated below.
The concat method is used to concatenate two strings. For example, String fullName = first-
Name.concat(lastName); will concatenate firstName and lastName as the fullName. Instead of typing
concat, you can always use the plus(+) operator to concatenate. For example, String fullName =
firstName +“ ”+ lastName;
The toLowerCase() method returns a new string with all lowercase letters. The toUpperCase() method
returns a new string with all uppercase letters. The trim() method returns a new string by eliminating
whitespace characters from both ends of the string. For example, given, String name = “ John ”;,
name.toLowerCase() will return “ john ”, name.toUpperCase() will return “ JOHN ” and, name.trim()
will return “John”.
The String class in Java contains the following methods shown in Figure 3.8 for comparing strings.
Practicals
1. Given String welcome = “Hello, welcome to Java”, write a Java statement to display the length
of the variable welcome.
4.1 Selections
Java has several types of selection statements; one-way if statements, two-way if-else statements,
nested if statements, multi-way if-else statements, switch statements, and conditional expressions.
A one-way if statement executes an action if and only if the condition is true. If the condition is false,
nothing is done. The syntax for a one-way if statement is:
if(condition){
statements();
}
If the one-way if statement contains just one statement, the the block braces can be omitted as:
if(condition)
statement();
An if-else statement decides the execution path based on whether the condition is true or false. The
syntax for a two-way if-else statement is:
if(condition){
statements_if_condition_is_true();
}else{
statements_if_condition_is_false();
}
An if statement can be inside another if statement to form a nested if statement. The inner if statement
is said to be nested inside the outer if statement. There is no limit to the depth of the nesting. The
multi-way if-else statements are used when there alternative conditions to be tested. The syntax for
a multi-way if-else statement is:
if(condition1){
statements_if_condition1_is_true();
}
else if (condition2){
statements_if_condition2_is_true();
}
else if (condition3){
statements_if_condition3_is_true();
}
else if (condition4){
statements_if_condition4_is_true();
}
else {
statements_if_all_conditions_are_false();
}
Java supports the logical operators shown in Figure 4.1 that can be used to create compound
conditions in if and if-else statements.
The codes below show a typical syntax of the logical operators used in multi-way if-else statements:
if((condition1)&&(condition2)){
statements_if_both_condition1_and_condition2_are_true();
}
else if ((condition3)||(condition4)){
statements_if_either_or_both_conditions_are_true();
}
else if ((condition5)^(condition6)){
statements_if_and_only_if_one_condition_is_true_and_the_other_false();
}
else {
statements_if_all_conditions_are_not_met();
}
A switch statement executes statements based on the value of a variable or an expression. The syntax
for the switch statement is as follows:
switch(switch_statement){
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
.
.
case valueN: statement(s)N;
break;
default: statement(s)_for_default();
When using switch statements, the case value and the switch statement must be of the same data
type.
Deciding on whether to use if-else statements or a switch statement is based on readability and the
expression that the statement is testing. While an if-else statement can test expressions based on
ranges of values or conditions, a switch statement tests expressions based only on a single integer,
enumerated value, or String object.
4.1.2 Practicals
1. Using one-way if statements only, write a Java program which takes an integer as input and
prints out if the number is odd or even.
2. Write a Java program which takes marks as a double and returns the class range of the student
as follows:
3. Given the Chinese Zodiac sign below, write a Java program (using switch statements) which
accepts a user input and returns the Zodiac animal for the respective year.
4.2 Loops
Loops can be used to tell a program to execute statements repeatedly. Java provides three types of
loop statements: while loops, do-while loops, and for loops.
A while loop executes statements repeatedly while the condition is true. The syntax for the while
loop is as follows:
while(loop_continuation_condition){
Statement(s)
.
.
Statement(s)
}
The loop continuation condition is checked first before the statements are executed. The following is
an example of a while loop which prints 10 lines of the statement “Welcome to Java while loop”
The do-while loop is the same as a while loop except that it executes the loop body first and then
checks the loop continuation condition. The syntax for the do-while loop is as follows:
do{
Statement(s)
.
.
Statement(s)
}while(loop_continuation_condition)
The following is an example of a do-while loop which prints 10 lines of the statement “Welcome to
Java do-while loop”
A for loop performs an initial action once, then repeatedly executes the statements in the loop body,
and performs an action after an iteration when the loop-continuation-condition evaluates to true. The
syntax for the for loop is as follows:
The following are two examples of for loops which both print 10 lines of the statement “Welcome to
Java for loop”
You can use a for loop, a while loop, or a do-while loop, whichever is convenient. The three forms of
loop statements - while, do-while, and for - are expressively equivalent. That is, you can write a loop
Note:
The while loop and for loop are called pretest loops because the continuation condition is checked
before the loop body is executed. The do-while loop is called a posttest loop because the condition
is checked after the loop body is executed.
A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner
loops. Each time the outer loop is repeated, the inner loops are re-entered, and started anew.
4.2.4 Practicals
1. Using the while loop, write a Java code which prints out the first 5 multiples of 2.
2. Using the do-while loop, write a Java code which finds the sum of the first 8 integers.
3. Using the for loop, write a Java code which finds the sum of the first 10 integers.
An exception indicates a problem that occurs while a program executes. By the name “exception”
it indicates the problem doesn’t occur frequently. That is, under normal circumstances, the “rule”
is that a statement normally executes correctly, the problem when the rule doesn’t execute normally
thus represents “an exception to the rule”. Exception handling is important to ensure robust and fault
tolerant programs can be written that can deal with problems and continue executing or terminate
gracefully.
There are various instances at which exceptions need to be handling. For example: division by
zero, invalid method parameters, out-of-range array indices, arithmetic overflow - that is, a value
outside the representable range of values, thread interruption, etc.
Exceptions are objects, and objects are defined using classes. The root class for exceptions is
java.lang.Throwable. The types of exceptions under the Throwable class in Java are as shown in
Figure 5.1
Exceptions are handled using the try/catch statements. The try block contains the statements
that may cause an exception in your code that you are willing to handle while the the catch block
contains the handler for an exception type. The general syntax for handling exceptions is as follows:
try{
statement;
statement;
.
}catch(ExceptionClass exceptionObject){
statement;
statement;
.
}
Note:
There may be more than one catch blocks in handling exceptions - students are to find out the function
of the finally block.
A typical Arithmetic Exception is dividing an integer by zero. Dividing a floating point number by
zero will not throw an arithmetic exception as:
Considering the below code snippet meant to take inputs x and y from the user and returns z
given as, z = xy, what happens if the user enters zero for y or enters a string for either x or y instead
of a number? The possible exceptions that can occur are as indicted on the codes.
The arithmetic exception can be handled by surrounding the possible arithmetic exception with
a try and catch block as follows:
Though this handles the possible arithmetic exception that might occur, it does not allow the
user to re-enter a value for y. The user can be allowed to re-enter the value for y countless times until
y /= 0 as follows.
From the previous codes, similar to the arithmetic exception, the input mismatch exceptions in the
previous codes can be handled by surrounding the exception with a try and catch follows:
}
try{
z= x/y;
check =false;
}catch(ArithmeticException e){
System.out.println("Division by zero is not permitted");
check = true;
}
}
System.out.println("The division is: " + z);
2. In Eclipse, Type in. and scroll through the IntelliSense (press the Control and Space Keys
together if the IntelliSense doesn’t pop-up).
To read a file (for instance, a text file called Test.txt) in Java, we can use the Scanner. However,
we have to declare Test.txt as a variable of type File as File in = new File (“Test.txt”);. The content
of the file can now be read with the Scanner as follows:
PrintWriter class can be used to create a file and write data to a text file. A PrintWriter object for a
text file can be created as follows:
The content to be written in the created file can be done using the syntax:
output.println(Content); or output.print(Content). Remember to always close your PrintWriter after
usage. E.g: output.close();
Just like data can be read from a file on your computer, you can read data from a file on the Web.
To read the content from a Web file, you first of all create the URL object. The syntax to create a
URL object is:
The scanner can now be used to read the content of the URL as:
Scanner input = new Scanner(umatURL.openStream());
5.2.4 Practicals
(a) Write a Java program to read the content of the file you created and print out the content
in the console.
(b) Write a Java program to read the content of the file you created and print out the content
and their respective types (integer, boolean, string, etc.) in the console. E.g:
String: Name
boolean: true
double: 26.1
(c) Write a Java program to read the content of the file you created and re-write the content
all in CAPS to a new text file called Out.txt.
2. Write a program to read the content on the file for UMaT’s website’s home page.
Data structures are used in almost every program or software. They are essential ingredients of
many efficient algorithms. Some data structures are highly specialised for specific tasks. Typical data
structures which will be discussed in this chapter include: Arrays, ArrayLists, Sets and Maps
6.1 Arrays
An array is a group of variables containing values of the same type. A single array variable can
reference a large collection of data of the same type. The syntax for declaring array variables is as
follows:
elementType [] arrayReference;
//E.g. double [] marks;
This declaration above does not allocate any space in memory for the array, only a storage location
is created for the reference to the array marks.
The code double [ ] marks = new double [10] creates an array called marks to store doubles. The
syntax to assign a value to an index of an array is as follows: arrayReference [index] = value;. E.g:
marks [7] = 86; as shown below will assign the value 86 to index 7 of marks.
6.1.1.1 Practicals
1. Create a single dimensional array of integers and assign the first 10 positive integers to your
array.
2. Create a single dimensional array of strings and assign 10 strings to your array.
3. Create an array of doubles and using a for loop, assign the first 5 multiples of 2 to your array.
4. Create a text file of integers (one integer per line), write a Java code to read the text file and
assign the content to an array of integers.
• Hint: Read the text file first, count the number of lines, use the number of lines to declare
your array size, read the text file and assign the content of the file to array.
1. Displaying arrays: Two ways of displaying the content of a single dimensional array are:
(a) Printing out the entire content of the array using the toString method. For example,
System.out.println(Arrays.toString(marks));
(b) Printing the content using a loop. For example, the following will print the content of the
array called marks:
2. Finding the largest and least elements: The least and largest elements of an array can be
found in various ways. Two simple ways are:
A two-dimensional array consists of an array of one-dimensional arrays. The syntax for declaring a
two-dimensional array variable is as follows:
The syntax to assign a value to an index of a two dimensional array is as follows: arrayRefer-
ence[index1][index2] = value;. For example, marks1 [2][1] = 89; will assign 89 to row 3 column 2 of
the array marks1.
The values to a multidimensional array can be initialized similar to the single dimensional arrays
as follows:
newMarks2[0][1] = 76;
newMarks2[1][0] = 80;
newMarks2[1][1] = 84;
1. Displaying arrays: Three ways of displaying the content of a two-dimensional array are:
(a) Printing out the entire content of the array using the deepToString method. For example,
System.out.println(Arrays.deepToString(marks))
(b) Printing out the content of the array using a loop. For example, the following will print
the content of the array called marks.
(c) Printing out each element using a nested for loop. For instance, for the 2 by 2 array marks,
its content can be printed out as:
An Array List is a collection class used to store groups of related objects in memory. Unlike arrays,
Array Lists can grow (when the size is exceeded) and shrink (when objects are removed) when needed.
Additionally, the ArrayList class provides methods for common tasks (e.g: inserting or removing
items). The syntax for declaring an Array List variable is as follows:
• add: This method adds an element to the end of the ArrayList. E.g: studentNames.add(“John
Addo”); will add John Addo to the end of studentNames created in the previous slide.
• clear: Removes all the elements from the ArrayList. E.g studentNames.clear(); will remove all
elements from studentNames.
1. Displaying ArrayLists: Two popular ways to display the content of an ArrayList are:
6.2.1.1 Practicals
1. Create an ArrayList and insert the following into the arraylist: John, Mike, Ama, 20.34, Daniel.
3. Create an Array List of integers and add the first four multiples of three to it.
4. Create an Array List of doubles and add the five doubles to it.
5. Create a text file of integers (one integer per line), write a Java code to read the text file and
assign the content to an array of integers.
• Hint 1: Read the content of the text file into an arraylist, use the size of the arraylist to
declare your array size, transfer the content of the arraylist to the array of integers.
6.3 Sets
Java provides three classes of Set: (a) HashSet, (b) LinkedHashSet and (c) TreeSet. This course will
focus only on HashSets and students are to learn about the LinkedHashSets and TreeSets. It is worth
noting that any instance of a Set contains no duplicate elements. That is, given S as a set, no two
elements e1 and e2 can be in S such that e1.equals(e2)
6.3.1 HashSet
A HashSet can be used to store duplicate-free elements of the same type. Set are useful in mathematical
process such as finding the union, intersection or set subtraction between two sets. The syntax for
declaring a HashSet is as follows: Set <elementType> hashsetRef = new HashSet<String>();. For
example, Set <String> stdNames = new HashSet<String>();
• add: Used to add only one element to a set. For example, stdNames.add(“John”); will add the
string “John” to the HahSet stdNames.
• addAll: This method is used to add all element of one set to another. For example, std-
Names.addAll(stdOldNames); will add all the content of stdOldNames to stdNames (where
stdOldNames is another set of type String).
• removeAll: This method is used to remove all element of one set from another. For example,
stdNames.removeAll(stdOldNames); will remove all elements of stdOldNames from stdNames -
where stdOldNames is another set of type String.
6.3.1.1 Practicals
1. Create two HashSets of Strings and add the following to each set:
6.4 Maps
A map is a container object that stores a collection of key/value pairs. For each key, the map stores
the corresponding value. A map cannot contain duplicate keys. Each key and its corresponding value
form an entry stored in a map where the keys are like indexes. Maps are important because they
enable fast retrieval, deletion, and updating of the pair through the key. Though Java provides three
classes of Maps: (a) HashMap, (b) LinkedHashMap, and (c) TreeMap, this section will focus only on
HashMaps.
6.4.1 HashMaps
A HashMap stores key-value pair where the keys are unique without duplicates. The syntax for declar-
ing a HashMap is Map<keyElementType, valueElementType> mapReference = new HashMap<>();.
For example, Map<String, Integer> stdMap = new HashMap<>(); will create a HashMap with key
type as string and corresponding value type as an integer.
You can iterate through the HashMap and print out the key and corresponding values as follows:
6.4.2 Practicals
1. Create a HashMap and insert the following student index numbers and corresponding marks in
the HashMap
(a) 42200213: 89
(b) 42225413: 65
(c) 42234513: 89
(d) 42233413: 78
Classes and objects provide a way to organise your code into generic, reusable pieces. With classes
and objects, methods and properties can be made private, so other programmers don’t have to know
anything about the class or object, they simply have to know what services the object offers and how
to access them. Additionally, classes and objects enable programmers to write programs using the
object oriented approach.
Object are basic runtime entities in object oriented systems. An object represents an entity that can
be distinctively identified. For example, a student, a box, a circle, a dog, loan, etc. Objects often
have unique identities, states and behaviours. The features of object include:
1. State: The state of an object in programming is represented by its data fields with their current
values. For instance, a rectangle has data fields of length and breadth (the properties which
characterise the rectangle).
2. Behaviour: The behaviour of an object is defined by methods that can be invoked to ask the
object to perform a function. For example, for the object rectangle, methods like getArea(),
setLength(), setBreadth() and so on can be created and invoked to ask the object perform a
function.
A class is a collection of objects of similar type. A class is a template that defines what an object data
fields and methods will be. Once a class is created any number of objects can be created (instantiated).
Classes provide special methods and types (constructors) which are invoked to create new objects. A
Java class uses variables to define data fields and methods to define actions.
The syntax for defining the class of rectangular boxes in our example is as follows:
Since the data fields in this definition have not been assigned values, when the constructor (rect-
angular()) is called to create the rectangle class, a rectangle with having length, breadth and height
as zeros will be created.
Other constructors can be added to ensure users can create objects of the rectangular class with
specified parameters for length, breadth and height as follows:
Methods to enable change the length, breadth and height of the rectangle can be added as:
Finally, methods for calculating the area and volume of the rectangle can be added as:
A constructor is a special kind of method which is invoked to create an object using the new
operator. Typical features or characteristics of constructors include: (a) they must have same name
as the class itself, (b) they do not have return types, and (c) they are invoked using the new operator
when an object is created.
The Object class can be: (a) separate class file in the same or different project or (b) on the same
class file as the file with the main class.
To use an object’s data and methods for any given object class, the class object variable has to
be declared as ClassName ObjectRefVariable;. For example, from the previous rectangular box
class we can declare rectangular newRectangular; where newRectangular is the object variable
which can reference a rectangular object. A single statement can be used to combine the declaration,
creation and assignment of an object reference using the syntax: ClassName ObjectRefVariable
= new ClassName();. For example, rectangular newRectangular = new rectangular();.
After an object is created, its data and methods can be accessed using the dot (•) operator.
Object’s methods and data can be accessed with syntax such as:
These are used to modify the visibility of a class and its members. If no visibility modifiers, then
by default the classes, methods and data fields are accessible by any class in the same package. The
types of visibility modifiers in Java are:
• Public visibility modifiers: Class methods and data fields with this modifier can be accessed
from any other class
• Private visibility modifiers: Class methods and data fields are only accessible within its
class.
Data field encapsulation is done by making the data fields private to protect the data and makes
class easy to maintain.
Reading assignment.
The keyword this refers to an object itself. It can be used inside a constructor to invoke another
constructor. It is often used to reference a class’s hidden data fields. An illustration of the this
keyword is as shown in Figure 7.1
A method is a collection of statements that are grouped together to perform an operation. Methods
can be used to define reusable code and organize and simplify code. A method definition consists of
its method name, parameters, return type and body. The syntax for defining a method is as follows:
Figure 7.2 shows a typical illustration of a method to find the maximum of two integers.
A method can be a separate class file in the same or different project or on the same class file as
the file with the main class. Calling/Invoking methods executes the code in the method. The syntax
for calling a method is as follows: methodName(list of parameters);. For example, from the method
in Figure 7.2, int maxNumber = max(2, 9); calls the method max which assigns the maximum value
to the variable maxNumber. From a given set of codes, methods can also be extracted from the codes
using the refactor - this will be illustrated in class.
7.3.1 Practicals
2. Write a method in the main class file that prints out the content of each array.
3. Write a method in a different class file that finds the sum of all content in each array.
8.1 Introduction
Note: This chapter is purely practical and students are advised to be in class for the practical
tutorial. I have however created video tutorials on some aspects of this chapter which can be accessed
via https://www.youtube.com/channel/UCSxKRS6RNGelv55Dy4H4Z3A/videos
Java supports two tools for Graphical User Interface application development: Java Swing and
JavaFX. Though both can be used separately to develop GUI applications, they have the follow
advantages and disadvantages:
5. Javafx supports modern touch devices, apps created with raw Java swing do not have an ap-
pealing look
For this chapter, we will be using JavaFX and Intellij IDEA. Though students can use Eclipse or
Netbeans, they are advised1 to use Intellij IDEA.
1Eclipse IDE is known to have some unresolved issues with regards to exporting JAR files.s
SceneBuilder is a drag and drop UI designer which will be used in the practicals for JavaFX application
development. To install and link SceneBuilder to Intellij IDEA;
2. On Intellij IDEA, go to File, Settings and select Languages and Frameworks, Select JavaFX
3. In the Path to SceneBuilder, navigate to the Installation director of SceneBuilder and Select the
SceneBuilder.exe.
• Select JavaFX and change the Project Name and Location to suit your purpose
• Click on “Finish” and select the window you want to open the project in.
• In the “HelloApplication.java” file right click and select Run ’HelloApplication.main()’ to execute
your application.
The main components after creating a JavaFX application in Intellij IDEA are:
1. The Controller class (HelloController.java) : This Java class file will contain all the event handlers
for your JavaFX application.
2. The Main class (HelloApplication.java): This Java class will contain the main method of your
JavaFX application.
3. The FXML file (hello-view.fxml): This FXML file will contain the codes for your GUI. You can
open this file with the SceneBuilder add components to your GUI using drag and drop without
coding.
4. The POM file (pom.xml): The Project Object Model (pom) an XML file that contains informa-
tion about the project and configuration details used by Maven to build the project.
Figure ?? shows the interface of the SceneBuilder which will be drag and drop tool for all our JavaFX
tutorials. The main components of the SceneBuilder are:
1. The Library Panel: The Library panel provides a list of available GUI elements/controls which
can be added to the FXML file.
2. The Document Panel: The Document Panel displays the hierarchy of components added to
FXML file as well as settings to the Java class file that will handle events when the application
runs.
3. The Inspector Panel: The Inspector panel contains settings for the components added to the
FXML file. Settings such as the properties of components, their layout and method names for
event handling are found here.
4. The Content Panel: The Content panel provides an interface for positioning the graphical user
interface elements that make up the FXML layout.
Though students will be taken through detailed explanations during practicals on the SceneB-
uilder, students can watch my tutorial (https://www.youtube.com/watch?v=m5wT2uaGDVw) on SceneB-
uilder Basics.
8.2 Practicals
Aside other basic practicals on JavaFX, the following practicals will be implemented (demonstrated)
in class using JavaFX on Intellij IDEA.
1. Design the user interface program which when run starts with the login screen in Figure 8.2
(a). If user enters a wrong password and/or user name, Figure 8.2 (b) should be presented to
the user. If the user enters the correct user name and password, Figure 8.2 (c) should welcome
user. When message dialog box in Figure 8.2 (c) is closed, Student Details form in Figure 8.2
(d) should presented to user while login screen disappears. When user fills the Student Details
form, all details of the student should be written to a text file and saved on the computer.
2. Design the user interface program which when run has the following functionalities:
(a) Starts with the login interface in Figure 8.3 (a). If the user enters the wrong password
and/or user name, the unsuccessful login message is displayed as in Figure 8.3 (b). A
successful login will display Figure 8.3 (c). The Close menu item under File indicated in
Figure 8.3 (d) should close the main interface and return to the login interface while the
About menu item under Help should display information about the developer.
(b) The Text Editor button should display a text editing interface for text editing as in Figure
8.4 (a). The Open Text File button should display the Open File dialog box to enable
user select a text file and once the Open button on the dialog box is clicked, content of the
selected text file should be copied to the text editor as shown in Figure 8.4 (b). The Save
To Text File button should show the Save dialog box (see Figure 8.4 (c)) to enable user
select a text file and once the Save button on the dialog box is clicked, content on the text
editor should be written on the selected text file overwriting old content on the selected
text file. The menu items under Font Size (see Figure 8.4 (d)) should change the font size
of content in the Text Editor to the selected font size while the menu items under Font
Type (see Figure 8.4 (e)) should change the font type of content in the Text Editor to the
Figure 8.3: GUI Practical II: Login Interface, Unsuccessful Login and Sucessful Login
(c) The View Images button should display an image viewer with a preselected image (see
Figure 8.5 (a)). The Load Image button should allow the user select a picture to replace
the displayed preselected image(see Figure 8.5 (b)).
(d) The Plot Graph button below the View Images should display the graph interface (see
Figure 8.6 (a)). The Plot Graph button besides the Logout button should plot a graph
with pre-set values(see Figure 8.6 (b)).
(e) The Assignment button should display the assignment (see Figure 8.7) which the students
are supposed to implement and submit for marking.