0% found this document useful (0 votes)
61 views66 pages

Programming With Java - 2022.23 - CSE

This document provides information about a Programming with Java course offered by the Computer Science and Engineering Department at the University of Mines and Technology in Tarkwa, Ghana. It lists the course lecturers as Vincent M. Nofong, Ph.D., Albert K. K. Ansah, Ph.D., and Evans Obu, Ph.D. Candidate. The document outlines the course assessment which includes continuous assessment consisting of attendance, quizzes, and assignments (40%) and end of semester examinations consisting of a written and practical exam (60%). It also provides a table of contents that lists the topics that will be covered in the course including introductions to programming, variables, data types, selection and loops.

Uploaded by

rhf9rvk5sf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
61 views66 pages

Programming With Java - 2022.23 - CSE

This document provides information about a Programming with Java course offered by the Computer Science and Engineering Department at the University of Mines and Technology in Tarkwa, Ghana. It lists the course lecturers as Vincent M. Nofong, Ph.D., Albert K. K. Ansah, Ph.D., and Evans Obu, Ph.D. Candidate. The document outlines the course assessment which includes continuous assessment consisting of attendance, quizzes, and assignments (40%) and end of semester examinations consisting of a written and practical exam (60%). It also provides a table of contents that lists the topics that will be covered in the course including introductions to programming, variables, data types, selection and loops.

Uploaded by

rhf9rvk5sf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 66

UNIVERSITY OF MINES AND TECHNOLOGY

FACULTY OF ENGINEERING

Computer Science and Engineering Department

PROGRAMMING WITH JAVA


CE 277

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:

VINCENT M. NOFONG, PHD.

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

Students will be assessed in this course as follows:

1. Continuous Assessment (40%): Which will comprise of the following components:

(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:

(a) Written Examination (30%)


(b) Practical Examination (30%)
Contents

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

3 Mathematical Functions, Characters and String 15


3.1 Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.1.1 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.1.2 Exponent Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.1.3 Service Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.1.3.1 Rounding Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.1.3.2 The min, max, and abs Methods . . . . . . . . . . . . . . . . . . . . . 16
3.1.3.3 The random Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Compiled by Vincent M. Nofong, PhD. v


CONTENTS

3.1.4 Practicals .............................................................................................................................. 17


3.2 Character Data Types and Operations ........................................................................................ 17
3.2.1 Character Declaration and Escape Sequences ................................................................18
3.2.2 Casting Between char and Numeric Types ......................................................................18
3.2.3 Comparing and Testing Characters ..................................................................................19
3.2.4 Practicals .............................................................................................................................. 19
3.3 The String Data Type ..................................................................................................................... 19
3.3.1 Getting the Length of a String......................................................................................... 20
3.3.2 Concatenating Strings ....................................................................................................... 20
3.3.3 Converting and Trimming Strings ................................................................................... 20
3.3.4 Comparing Strings .............................................................................................................. 21

4 Selections and Loops 23


4.1 Selections......................................................................................................................................... 23
4.1.1 The if Statements .............................................................................................................. 23
4.1.1.1 The one-way if Statements ............................................................................... 23
4.1.1.2 The two-way if-else Statements ....................................................................... 23
4.1.1.3 The Nested if and Multi-way if-else Statements............................................ 24
4.1.1.4 Logical Operators .............................................................................................. 24
4.1.1.5 Switch Statements ............................................................................................. 25
4.1.1.6 if-else Statements vs switch Statements .................................................... 25
4.1.2 Practicals ............................................................................................................................. 25
4.2 Loops ............................................................................................................................................... 26
4.2.0.1 The while Loop ................................................................................................. 26
4.2.1 The do-while Loop............................................................................................................ 27
4.2.1.1 The for Loop ..................................................................................................... 27
4.2.2 Which Loop to Use? .......................................................................................................... 27
4.2.3 Nested Loops ...................................................................................................................... 28
4.2.4 Practicals ............................................................................................................................. 28

5 Exception Handling and Input/Output 29


5.1 Exception Handling ....................................................................................................................... 29
5.1.1 Catching Exceptions .......................................................................................................... 30
5.1.2 Handling Arithmetic Exceptions...................................................................................... 30
5.1.3 Handling InputMismatch Exceptions ............................................................................... 31
5.2 The File Class ................................................................................................................................. 32
5.2.1 Reading Input from Files .................................................................................................. 32
5.2.2 Writing Output to Files .................................................................................................... 32
5.2.3 Reading Data from the Web with Scanner .................................................................... 33
5.2.4 Practicals ............................................................................................................................. 33

6 Data Structures in Java 35


6.1 Arrays............................................................................................................................................... 35
6.1.1 Single Dimensional Arrays ................................................................................................ 35
6.1.1.1 Practicals ............................................................................................................ 36
6.1.2 Processing Single Dimensional Arrays ............................................................................. 36
6.1.3 Multidimensional Arrays - Two Dimensional Arrays .................................................... 37

Compiled by Vincent M. Nofong, PhD. vi


CONTENTS

6.1.4 Processing Multi Dimensional Arrays ............................................................................. 38


6.2 Array Lists ...................................................................................................................................... 39
6.2.1 Processing ArrayLists ........................................................................................................ 40
6.2.1.1 Practicals ............................................................................................................ 40
6.3 Sets ................................................................................................................................................... 40
6.3.1 HashSet................................................................................................................................ 41
6.3.1.1 Practicals ............................................................................................................. 41
6.4 Maps ................................................................................................................................................ 42
6.4.1 HashMaps .......................................................................................................................... 42
6.4.2 Practicals ............................................................................................................................ 42

7 Classes and Objects 43


7.1 Objects and their Features ........................................................................................................... 43
7.2 Classes and their Features ............................................................................................................ 43
7.2.1 Defining a Class - A Class of Rectangular Boxes .......................................................... 44
7.2.2 Accessing Object via Reference Variables ...................................................................... 45
7.2.3 Visibility Modifiers and Data Field Encapsulation ....................................................... 46
7.2.4 Inheritance and Polymorphism ....................................................................................... 46
7.2.5 The this Reference ............................................................................................................ 46
7.3 A Primer to Methods .................................................................................................................... 46
7.3.1 Practicals .............................................................................................................................47

8 Graphical User Interface Application Development 49


8.1 Introduction .................................................................................................................................... 49
8.1.1 Installing and Linking SceneBuilder to Intellij IDEA ................................................... 50
8.1.2 Creating JavaFX Applications with Intellij IDEA......................................................... 50
8.1.3 Components of JavaFX Project in Intellij IDEA ........................................................... 50
8.1.4 Components of SceneBuilder ............................................................................................ 51
8.2 Practicals .......................................................................................................................................... 51

Compiled by Vincent M. Nofong, PhD. vii


CONTENTS

Compiled by Vincent M. Nofong, PhD. viii


List of Figures

1.1 An External View of a Computer System ..................................................................................... 1


1.2 Compiler vs Interpreter.................................................................................................................... 3

2.1 Java Arithmetic Operators .............................................................................................................. 9


2.2 Rules of Operator Precedence ......................................................................................................... 9
2.3 Scanner vs BufferedReader ............................................................................................................ 10
2.4 Java Numeric Data Types .............................................................................................................. 11
2.5 Post and Pre Increment/Decrement Operators ........................................................................... 12
2.6 Equality Operators.......................................................................................................................... 13
2.7 Relational Operators ....................................................................................................................... 13

3.1 Java Trigonometric Functions ....................................................................................................... 15


3.2 Java Exponent Functions ............................................................................................................... 16
3.3 Java Rounding Functions............................................................................................................... 16
3.4 Commonly Used ASCII Codes and Their Unicode Values ........................................................ 18
3.5 Supported Escape Sequences in Java ........................................................................................... 18
3.6 Supported Character Testing Methods ........................................................................................ 19
3.7 String Manipulation Methods ....................................................................................................... 19
3.8 String Comparison Methods .......................................................................................................... 21

4.1 Java Logical Operators ................................................................................................................... 24

5.1 Exception Types .............................................................................................................................. 29

6.1 Some Common ArrayList Functions ............................................................................................ 39

7.1 The this Keyword Illustration ...................................................................................................... 47


7.2 Method Illustration - Finding the Maximum of Two Integers .................................................. 47

8.1 SceneBuilder Components ............................................................................................................. 51


8.2 GUI Practical I ................................................................................................................................ 52
8.3 GUI Practical II: Login Interface, Unsuccessful Login and Sucessful Login ........................... 53
8.4 GUI Practical II: Text Editor Interface ....................................................................................... 53
8.5 GUI Practical II: Image Viewer Interface .................................................................................... 54
8.6 GUI Practical II: Graph Ploting Interface .................................................................................. 54
8.7 GUI Practical II: Assignment Interface ....................................................................................... 54

Compiled by Vincent M. Nofong, PhD. ix


LIST OF FIGURES

Compiled by Vincent M. Nofong, PhD. x


List of Tables

Compiled by Vincent M. Nofong, PhD. xi


LIST OF TABLES

Compiled by Vincent M. Nofong, PhD. xii


Chapter 1

Introduction

1.1 Introduction to Computers

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.

Figure 1.1: An External View of a Computer System

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

Compiled by Vincent M. Nofong, PhD. 1


1. INTRODUCTION

example, the email browsers, media players, etc. We will learn to create some simple application
programs with Java

1.2 Categories of Programming Languages

Programming languages can be categorised into the following:

• 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.

• Source code translation can be done with an interpreter or compiler

1.2.1 The Compiler vs Interpreter

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

1.3 The Java Programming Language

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 comes in four platforms:


1Short descriptive words

Compiled by Vincent M. Nofong, PhD. 2


1.3 The Java Programming Language

Figure 1.2: Compiler vs Interpreter

• Java Standard Edition (Java SE): For developing client-side applications which can run
standalone or as applets on a Web browser.

• Java Enterprise Edition (Java EE): For developing server-side applications.

• 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.

1.3.1 Java Development Toolkit and its Configuration

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.

1.3.1.1 Checking and Installing the JDK Version

The JDK version can be checked on the command prompt using the following steps:

Compiled by Vincent M. Nofong, PhD. 3


1. INTRODUCTION

1. Open the Command Prompt or Powershell

2. Type java -version

3. Press the Enter key

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.

1.3.1.2 Setting/Configuring the Java Path

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

2. Right click and Select Properties

3. Select Advanced System Settings

4. Select Environment Variables

5. Under System Variables, Select Path

6. Click the Edit button

• Navigate to where the installed Java directory is on your computer


• Copy the JDK bin directory location C:\Program Files\Java\jdk-x.x.x\bin

7. Click New and Paste directory, save and exit

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.

1.3.2 Creating First Java Codes and Testing in PowerShell

1. Open Note pad or Notepad++.

2. Type the following:

public class MyFirstJavaCode{


public static void main(String [] args){
System.out.println("Welcome to Java");
}
}

Compiled by Vincent M. Nofong, PhD. 4


1.3 The Java Programming Language

3. Go to File, and Save as MyFirstJavaCode.java

4. Open the PowerShell or Command Prompt where your Java Source Code is saved.

5. Type javac MyFirstJavaCode.java

6. Press the Enter Key

7. If no errors, type java MyFirstJavaCode and press the Enter Key

8. If there are errors, read the error message and debug.

1.3.2.1 Installing IntelliJ IDEA

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

Compiled by Vincent M. Nofong, PhD. 5


1. INTRODUCTION

Compiled by Vincent M. Nofong, PhD. 6


Chapter 2

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:

• dataType variableName = value; OR dataType variableName;


• For example:

int studentMark =78;


double studentCWA;

• Things to note about the two variables declared:

There are three types of variables in Java:


1. Local variable: This is a variable which is declared inside a method.

2. Instance Variable: This is a variable which is declared inside the class but outside the method,
and is not static.

Compiled by Vincent M. Nofong, PhD. 7


2. ELEMENTARY PROGRAMMING

3. Static variable: This is a variable that is declared as static.

• The below codes illustrates examples of the three types of variables

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 must start with a letter or the underscore ( ) character.

• Symbols such as ? or % cannot be used

• Spaces are not permitted inside names

• Names are case sensitive, i.e., studentMark and studentmark are different names

• Reserved words e.g. double or class cannot be used as 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)

2. Non-primitive: String, Array, etc

2.2 Assignment Statements and Assignment Expressions


An assignment statement is used to designate values for variables. In Java, the equal to sign (=)
is used as the assignment operator while assignment expression is an expression representing a
computation involving values, variables, and operators that, taking them together, evaluates to a
value. The below listed codes show typical examples of assignment statements and expressions.

public static void main(String [] args){


double area;// Declaring area as a variable
double breadth =2.5; //Assignment statement assigning 2.5 to breadth
double length = breadth*2.6;//Assignment expression
area = breadth*length;
}

Compiled by Vincent M. Nofong, PhD. 8


2.3 Arithmetic Operators

2.3 Arithmetic Operators

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.

Figure 2.1: Java Arithmetic Operators

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;

2.3.1 Arithmetic Functions - Rules of Operator Precedence

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.

Figure 2.2: Rules of Operator Precedence

Notwithstanding, these rules, it is advisable to use parentheses when writing arithmetic functions
in Java. This is because functions in parentheses are evaluated first.

2.4 Input Reading from Keyboard or Console

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:

1. System.out to refer to the standard output device, and

Compiled by Vincent M. Nofong, PhD. 9


2. ELEMENTARY PROGRAMMING

2. System.in to refer to the standard input device.

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.

Figure 2.3: Scanner vs BufferedReader

2.4.1 Scanner Syntax

The Scanner class can be used to create an object to read input from System.in as:

• Scanner input = new Scanner(System.in);

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.

2.4.1.1 Practicals with Scanner

(a) a Java program that when run:

1. Asks the user for his/her name

2. Accepts user input from keyboard

3. Displays a welcome message with the user name.

(b) the above program such that when run:

Compiled by Vincent M. Nofong, PhD. 10


2.5 Numeric Data Types and Operators

1. Asks the user for his/her name

2. Asks the user for his/her age as an integer

3. Accepts user inputs from keyboard

4. Displays a message with the user’s name and age.

We will learn how to ensure only two integers are entered by the user under exception handling.

(c) a Java program that when run:

1. Asks a user for the length of the triangle

2. Accepts an integer as the length from the keyboard

3. Asks the user for hight of the triangle

4. Accepts a double as the height from the keyboard

5. Computes the area of the triangle

6. Displays the computed are of the triangle.

2.5 Numeric Data Types and Operators

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.

Figure 2.4: Java Numeric Data Types

Compiled by Vincent M. Nofong, PhD. 11


2. ELEMENTARY PROGRAMMING

2.5.1 Numeric Operators - Increment and Decrement Operators

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

Increment and decrement operators could be:

• Preincrement (++i) OR Postincrement (i++)

• Predecrement (−−i) OR Postdecrement (i−−)

The distinctions between post and pre increment or decrement are as shown in Figure 2.5.

Figure 2.5: Post and Pre Increment/Decrement Operators

2.5.2 Numeric Type Conversion

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.

Compiled by Vincent M. Nofong, PhD. 12


2.6 Decision Making - Equality and Relational Operators

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);

2.6 Decision Making - Equality and Relational Operators

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.

Figure 2.6: Equality Operators

Figure 2.7: Relational Operators

2.7 Practicals

1. Create a Java program that when run):

(a) Ask user to enter time in seconds as an integer


(b) Accepts user input
(c) Converts the time in seconds into minutes and seconds
(d) Displays the conversion to user.

2. Create a Java program that when run:

Compiled by Vincent M. Nofong, PhD. 13


2. ELEMENTARY PROGRAMMING

(a) Generates a random number between 0 and 4


(b) Asks the user to guess the generated number
(c) Accepts user input
(d) Displays “Congratulations, you won” if user input is same as random number
(e) Displays “You lost, number too high” if user input is higher than random number
(f) Displays “You lost, number too low” if user input is lower than random number.

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

Compiled by Vincent M. Nofong, PhD. 14


Chapter 3

Mathematical Functions,
Characters and String

3.1 Mathematical Functions


Java provides many useful methods1 in the Math class for performing common mathematical functions.
These methods for mathematical functions can be grouped into; Trigonometric methods, Exponent
methods, and Service methods. Aside these methods, the Math class provides two double constants,
PI and E which can be used as Math.PI and Math.E in any program.

3.1.1 Trigonometric Functions


The trigonometric functions (methods) supported in Java are methods for performing trigonometric
operations such as the sine and cosine operations on values.

Figure 3.1: Java Trigonometric Functions

Figure 3.1 shows the supported trigonometric functions that are supported in Java and their
descriptions.

1A method is a group of statements that perform a specific task

Compiled by Vincent M. Nofong, PhD. 15


3. MATHEMATICAL FUNCTIONS, CHARACTERS AND STRING

3.1.2 Exponent Functions

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.

Figure 3.2: Java Exponent Functions

3.1.3 Service Functions

The service functions supported in Java can be grouped into; rounding methods, random method, and
the min, max and abs methods.

3.1.3.1 Rounding 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.

Figure 3.3: Java Rounding Functions

3.1.3.2 The min, max, and abs Methods

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.

3.1.3.3 The random Method

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

Compiled by Vincent M. Nofong, PhD. 16


3.2 Character Data Types and Operations

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.

5. Write a program that displays that returns:

(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

6. Create a Java program that when run:

(a) Generates a random number between 0 and 4


(b) Asks the user to guess the generated number, Accepts user input
(c) Displays “Congratulations, you won” if user input is same as random number
(d) Displays “You lost, number too high” if user input is higher than random number
(e) Displays “You lost, number too low” if user input is lower than random number.

3.2 Character Data Types and Operations

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.

The Unicode Scheme


The Unicode scheme is an encoding scheme established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the world’s diverse languages. It was originally
designed as a 16-bit character encoding to handle the 65,536 characters possible in a 16-bit. Currently,
it has been extended to allow up to 1,112,064 characters. Those characters that go beyond the original
16-bit limit are called supplementary characters. Java supports both the original and supplementary
unicode characters.

The ASCII Scheme


The ASCII scheme is an 8-bit encoding scheme for representing all uppercase and lowercase letters,
digits, punctuation marks, and control characters. Figure 3.4 shows the commonly used ASCII code
and their Unicode Values.
1Mapping a character to its binary representation

Compiled by Vincent M. Nofong, PhD. 17


3. MATHEMATICAL FUNCTIONS, CHARACTERS AND STRING

Figure 3.4: Commonly Used ASCII Codes and Their Unicode Values

3.2.1 Character Declaration and Escape Sequences

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.

Figure 3.5: Supported Escape Sequences in Java

3.2.2 Casting Between char and Numeric Types

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.

1because \uFFF4 exceeds the byte range

Compiled by Vincent M. Nofong, PhD. 18


3.3 The String Data Type

3.2.3 Comparing and Testing Characters

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.

Figure 3.6: Supported Character Testing Methods

3.2.4 Practicals

1. Write Java statements that print out the following:

(a) John said ‘Java is fun and easy’


(b) John said “Java is fun and easy”

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.

3.3 The String Data Type

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.

Figure 3.7: String Manipulation Methods

Compiled by Vincent M. Nofong, PhD. 19


3. MATHEMATICAL FUNCTIONS, CHARACTERS AND STRING

3.3.1 Getting the Length of a String

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”.

Getting Characters from a String

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.

3.3.2 Concatenating Strings

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;

3.3.3 Converting and Trimming Strings

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”.

Compiled by Vincent M. Nofong, PhD. 20


3.3 The String Data Type

3.3.4 Comparing Strings

The String class in Java contains the following methods shown in Figure 3.8 for comparing strings.

Figure 3.8: String Comparison Methods

Practicals

1. Given String welcome = “Hello, welcome to Java”, write a Java statement to display the length
of the variable welcome.

Compiled by Vincent M. Nofong, PhD. 21


3. MATHEMATICAL FUNCTIONS, CHARACTERS AND STRING

Compiled by Vincent M. Nofong, PhD. 22


Chapter 4

Selections and Loops

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.

4.1.1 The if Statements

An if statement is a construct that enables a program to specify alternative paths of execution. As


mentioned previously, the if could be one-way, two-way, nested or multi-way if-else statement.

4.1.1.1 The one-way if Statements

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();

4.1.1.2 The two-way if-else Statements

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:

Compiled by Vincent M. Nofong, PhD. 23


4. SELECTIONS AND LOOPS

if(condition){
statements_if_condition_is_true();
}else{
statements_if_condition_is_false();
}

4.1.1.3 The Nested if and Multi-way if-else Statements

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();
}

4.1.1.4 Logical Operators

Figure 4.1: Java Logical Operators

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:

Compiled by Vincent M. Nofong, PhD. 24


4.1 Selections

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();
}

4.1.1.5 Switch Statements

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.

4.1.1.6 if-else Statements vs switch Statements

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:

• mark ≥ 80.0 “First class”

Compiled by Vincent M. Nofong, PhD. 25


4. SELECTIONS AND LOOPS

• 70.0 ≤ mark < 80.0 “Second class Upper”


• 60.0 ≤ mark < 70.0 “Second class lower”
• 50.0 ≤ mark < 60.0 “Pass”
• mark < 50.0 “Fail”

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.

4.2.0.1 The while Loop

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”

int count =0;


while(count<10){
System.out.println("Welcome to Java while loop");
count++;
}

Compiled by Vincent M. Nofong, PhD. 26


4.2 Loops

4.2.1 The do-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”

int count =0;


do{
System.out.println("Welcome to Java while loop");
count++;
}while(count<10)

4.2.1.1 The for 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:

for(initial_condition; loop_continuation_condition; action_after_each_iteration){


Statement(s);
}

The following are two examples of for loops which both print 10 lines of the statement “Welcome to
Java for loop”

for(int count=10; count>0; count--){


System.out.println("Welcome to Java while loop");
}

for(int count=0; count<10; count++){


System.out.println("Welcome to Java while loop");
}

4.2.2 Which Loop to Use?

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

Compiled by Vincent M. Nofong, PhD. 27


4. SELECTIONS AND LOOPS

in any of these three forms.

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.

4.2.3 Nested Loops

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.

Compiled by Vincent M. Nofong, PhD. 28


Chapter 5

Exception Handling and


Input/Output

5.1 Exception Handling

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.

Figure 5.1: Exception Types

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

Compiled by Vincent M. Nofong, PhD. 29


5. EXCEPTION HANDLING AND INPUT/OUTPUT

java.lang.Throwable. The types of exceptions under the Throwable class in Java are as shown in
Figure 5.1

5.1.1 Catching Exceptions

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.

5.1.2 Handling Arithmetic Exceptions

A typical Arithmetic Exception is dividing an integer by zero. Dividing a floating point number by
zero will not throw an arithmetic exception as:

• Positive floating point division by zero = positive infinity

• Negative floating point division by zero = negative infinity

• Floating point zero division by zero = NaN1

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.

Scanner input = new Scanner(System.in);


int x= 0;
int y =0;
int z=0;
System.out.print("Enter a value for X: ");
x = input.nextInt(); //Possible Input MisMatch Exception
System.out.print("Enter a value for Y: ");
y = input.nextInt(); //Possible Input MisMatch Exception
z= x/y; //Possible Arithmetic Exception
System.out.println("The division is: " + z);

1Not a Number, which means the result is undefined mathematically

Compiled by Vincent M. Nofong, PhD. 30


5.1 Exception Handling

The arithmetic exception can be handled by surrounding the possible arithmetic exception with
a try and catch block as follows:

Scanner input = new Scanner(System.in);


int x= 0;
int y =0;
int z=0;
System.out.print("Enter a value for X: ");
x = input.nextInt(); //Possible Input MisMatch Exception
System.out.print("Enter a value for Y: ");
y = input.nextInt(); //Possible Input MisMatch Exception
try{
z= x/y;
}catch(ArithmeticException e){
System.out.println("Division by zero is not permitted");
}
System.out.println("The division is: " + z);

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.

boolean check = true;


while(check){
System.out.print("Enter a value for Y: ");
y = input.nextInt(); //Possible Input MisMatch Exception
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);

5.1.3 Handling InputMismatch Exceptions

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:

boolean check = true;


boolean check2 = true;
while(check){
while(check2){
try{
System.out.print("Enter a value for Y: ");
y = input.nextInt();
check2 = false;
}catch(InputMisMatchException e){
System.out.println("Number Entered is not an Integer, Please enter an integer")
input.nextLine();
check2 = true;
}

Compiled by Vincent M. Nofong, PhD. 31


5. EXCEPTION HANDLING AND INPUT/OUTPUT

}
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);

Students are to handle the rest of the exceptions in the code.

5.2 The File Class


5.2.1 Reading Input from Files
The File class in Java contains the methods for: obtaining the properties of a file/directory, and
renaming and deleting a file/directory. The syntax for declaring a File variable is as follows:

File variableName = new File ("FileName.extension");


//E.g. File inputFile = new File("Test.txt");
OR
File variableName = new File ("FileDirectory\\FileName.extension");
//E.g. File inputFile = new File("C:\\Java\\Practical\\Test.txt");

Checking some possible file manipulations:

1. Declare a file, E.g. File in = new File (“Test.txt”);

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:

• Scanner input = new Scanner (in);


• The content of the file can now be read with the scanner variable “input”

5.2.2 Writing Output to Files

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:

PrintWriter variableName = new PrintWriter ("FileName.extension");


//E.g. PrintWriter output = new PrintWriter("Test.txt");
OR
PrintWriter variable = new PrintWriter ("Directory\\FileName.extension");
//E.g. PrintWriter output = new PrintWriter("C:\\Java\\Practical\\out.txt");

Compiled by Vincent M. Nofong, PhD. 32


5.2 The File Class

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();

5.2.3 Reading Data from the Web with Scanner

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:

URL urlObject = new URL ("url address");


//E.g. URL umatURL = new URL ("https://www.umat.edu.gh/");;

The scanner can now be used to read the content of the URL as:
Scanner input = new Scanner(umatURL.openStream());

5.2.4 Practicals

1. Create a text file on your computer with the following content:

(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.

Compiled by Vincent M. Nofong, PhD. 33


5. EXCEPTION HANDLING AND INPUT/OUTPUT

Compiled by Vincent M. Nofong, PhD. 34


Chapter 6

Data Structures in Java

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

6.1.1 Single Dimensional 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 syntax for creating an array is as follows:

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.

Compiled by Vincent M. Nofong, PhD. 35


6. DATA STRUCTURES IN JAVA

The values to an array can be initialized in various ways as shown:

double [] newMarks = {83, 76, 80}


//creates newMarks and initialises it;

double [] newMarks2 = new double[3];


newMarks2[0] = 83;
newMarks2[1] = 76;
newMarks2[2] = 80;

double [] newMarks3 = new double[3];


for(int i=0; i<newMarks3.length; i++){
newMarks3[i] = (i+2)*3;
}

The values in an array can be accessed as follows: variableType = arrayReference[index];. For


instance, double getMark = newMarks[1]; will return 76.0 from newMarks.

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.

6.1.2 Processing Single Dimensional Arrays

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:

for(int i=0; i<marks.length; i++){


System.out.print(marks[i] + " ");
}

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) For finding the largest element:

Compiled by Vincent M. Nofong, PhD. 36


6.1 Arrays

double maxMark = marks[0];


for(int i=0; i<marks.length; i++){
if(mark[i] > maxMark){
maxMark = mark[i];
}
}

(b) Finding the least element:

double minMark = marks[0];


for(int i=0; i<marks.length; i++){
if(mark[i] < minMark){
mmiMark = mark[i];
}
}

3. Sorting arrays: Some ways of sorting single dimensional arrays:

(a) Arrays.sort(arrayReference); - this sorts entire array in ascending order.


(b) Arrays.sort(arrayReference, Index1, Index2); - this sorts array from Index1 to Index2 in
ascending order.

4. Looping without indexing:

//where marks is an array of doubles


for(double entry: marks){ //for each entry in marks
System.out.println(entry);
}

5. Summing all elements - practical assignment

6. Shifting/re-arranging elements - practical assignment

7. Copying arrays - practical assignment

8. Searching arrays - practical assignment

6.1.3 Multidimensional Arrays - Two Dimensional Arrays

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:

double [][] newMarks2 = new double[2][2];


newMarks2[0][0] = 83;

Compiled by Vincent M. Nofong, PhD. 37


6. DATA STRUCTURES IN JAVA

newMarks2[0][1] = 76;
newMarks2[1][0] = 80;
newMarks2[1][1] = 84;

double [][] newMarks3 = new double[2][2];


for(int i=0; i<newMarks3.length; i++){
for(int j=0; j<newMarks3[0].length; j++){
newMarks3[i][j] = (i+j)+3;
}
}

The values in an array can be accessed as follows: variableType = arrayReference[index1][index2];.


For example, double getMark = newMarks2[1][1]; returns 84.0 from newMark2.

6.1.4 Processing Multi Dimensional Arrays

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.

for(int i=0; i<marks.length; i++){


System.out.println(Arrays.toString(marks[i]));
}

(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:

for(int i=0; i<marks.length; i++){


for(int j=0; j<marks[0].length; j++){
System.out.print(marks[i][j] +" ");
}
System.out.println();

Compiled by Vincent M. Nofong, PhD. 38


6.2 Array Lists

2. Sorting Multidimensional Arrays - By a Column: Multidimensional arrays can be sorted


similar to the single dimensional arrays as follows:

Arrays.sort(marks, new Comparator<double[] >(){


public int compare(double [] x1, double x2){
return Double.compare(x2[1], x1[1]);
}
});

6.2 Array Lists

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:

ArrayList <elementType> arrayReference = new ArrayList <elementType>();


//Example:
ArrayList <String> StudentNames = new ArrayList <String>();

Some of the common methods available in the ArrayList Class include:

• 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.

Figure 6.1: Some Common ArrayList Functions

Compiled by Vincent M. Nofong, PhD. 39


6. DATA STRUCTURES IN JAVA

6.2.1 Processing ArrayLists

1. Displaying ArrayLists: Two popular ways to display the content of an ArrayList are:

(a) Printing out the whole ArrayList. E.g System.out.println(studentNames);


(b) By printing out each element in the ArrayList one at a time. For example,

for(int i =0; i<studentNames.size(); i++){


System.out.println(studentNames.get(i));
}

2. Sorting ArrayList: ArrayLists can be sorted using Collections.sort(ArrayListName). For


example, Collections.sort(studentNames) will sort the ArrayList named studentNames.

3. Reversing ArrayList: ArrayList likewise can be reversed using Collections.reverse(ArrayListName).


For example, Collections.reverse(studentNames) will reverse the ArrayList named studentNames.

6.2.1.1 Practicals

1. Create an ArrayList and insert the following into the arraylist: John, Mike, Ama, 20.34, Daniel.

• Print out the size of the arraylist created


• Print out the content of the arraylist
• Remove 20.34 from the arraylist using the remove method
• Print out the size of the arraylist again

2. Create an Array List of String and add four names to it.

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)

Compiled by Vincent M. Nofong, PhD. 40


6.3 Sets

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>();

Content can be added to a HashSet using:

• 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).

Content can be removed from a HashSet using:

• remove: Used to remove an element to a set. For example, stdNames.remove(”John”); will


remove “John” from the set stdNames.

• 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.

The content of a HashSet can be displayed as System.out.println(stdNames);. Some other oper-


ations that can be performed on the set include:

• Union of set A and B: E.g: A.addAll(B);

• Intersection of set A and B: E.g: A.retainAll(B);

• Subtract set B from A: E.g: A.removeAll(B);

6.3.1.1 Practicals

1. Create two HashSets of Strings and add the following to each set:

• First set: “John, Mike, Clement, 20.5, Isaac”


• Second set: “John, Alice, Mary, Clement, Ama”

(a) Remove “20.5” from the first set


(b) Print the union of the two sets
(c) Print out the intersection of the two sets
(d) Print out the subtraction of the second set from the first set.

Compiled by Vincent M. Nofong, PhD. 41


6. DATA STRUCTURES IN JAVA

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.

The syntax for inserting content in a HashMap is mapReference.put(keyElementType, valueElement-


Type);. E.g., given Map<String, Integer> stdMap = new HashMap<>();, the code stdMap.put(”John
Mensah”, 39);will insert John Mensah as key with corresponding value of 39.

All content in a HashMap can be printed out as follows: System.out.println(mapReference);. For


example, System.out.println(stdMap); will print out all the content of the HashMap named stdMap.

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

2. Print out the content of the HashMap in the console

Compiled by Vincent M. Nofong, PhD. 42


Chapter 7

Classes and Objects

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.

7.1 Objects and their Features

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.

7.2 Classes and their Features

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.

Compiled by Vincent M. Nofong, PhD. 43


7. CLASSES AND OBJECTS

7.2.1 Defining a Class - A Class of Rectangular Boxes


Take the case of writing a Java program to compute the areas and volumes of rectangular boxes with
different parameters. With object oriented approach, a class of rectangular boxes can be created.
Objects (instances) of the class rectangular box can then be created for each distinct rectangular box.

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

Compiled by Vincent M. Nofong, PhD. 44


7.2 Classes and their Features

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.

7.2.2 Accessing Object via Reference Variables

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

Compiled by Vincent M. Nofong, PhD. 45


7. CLASSES AND OBJECTS

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:

• ObjectRefVariable.dataField;. For instance, rectangular.length;

• ObjectRefVariable.method(arguments);. For example, rectangular.setLength(13);

7.2.3 Visibility Modifiers and Data Field Encapsulation

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.

• Protected visibility modifiers: Reading assignment

Data field encapsulation is done by making the data fields private to protect the data and makes
class easy to maintain.

7.2.4 Inheritance and Polymorphism

Reading assignment.

7.2.5 The this Reference

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

7.3 A Primer to Methods

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:

Compiled by Vincent M. Nofong, PhD. 46


7.3 A Primer to Methods

Figure 7.1: The this Keyword Illustration

modifier returnValueType methodName (list of parameters){


//method body
}

Figure 7.2 shows a typical illustration of a method to find the maximum of two integers.

Figure 7.2: Method Illustration - Finding 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

1. Create two dimensional arrays of doubles having different sizes.

2. Write a method in the main class file that prints out the content of each array.

Compiled by Vincent M. Nofong, PhD. 47


7. CLASSES AND OBJECTS

3. Write a method in a different class file that finds the sum of all content in each array.

Compiled by Vincent M. Nofong, PhD. 48


Chapter 8

Graphical User Interface


Application Development

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:

1. Java swing is more stable and proven

2. Javafx has more consistent controls

3. CSS styling can be used in Javafx

4. Javafx has built-in animation systems

5. Javafx supports modern touch devices, apps created with raw Java swing do not have an ap-
pealing look

6. Easier to customise looks in Java swing

7. Javafx API’s are less consistent

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

Compiled by Vincent M. Nofong, PhD. 49


8. GRAPHICAL USER INTERFACE APPLICATION DEVELOPMENT

8.1.1 Installing and Linking SceneBuilder to Intellij IDEA

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;

1. Download and Install the SceneBuilder

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.

4. Click Ok twice to exit

8.1.2 Creating JavaFX Applications with Intellij IDEA

To create a new JavaFX application with Intellij IDEA:

• Go to File → New Project

• Select JavaFX and change the Project Name and Location to suit your purpose

• Leave the remaining settings as they are and click on “Next”

• Click on “Finish” and select the window you want to open the project in.

• Wait for the project to open and the dependencies to load

• In the “HelloApplication.java” file right click and select Run ’HelloApplication.main()’ to execute
your application.

8.1.3 Components of JavaFX Project in Intellij IDEA

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.

Compiled by Vincent M. Nofong, PhD. 50


8.2 Practicals

8.1.4 Components of SceneBuilder

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.

Figure 8.1: SceneBuilder Components

8.2 Practicals

Aside other basic practicals on JavaFX, the following practicals will be implemented (demonstrated)
in class using JavaFX on Intellij IDEA.

Compiled by Vincent M. Nofong, PhD. 51


8. GRAPHICAL USER INTERFACE APPLICATION DEVELOPMENT

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.

Figure 8.2: GUI Practical I

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

Compiled by Vincent M. Nofong, PhD. 52


8.2 Practicals

Figure 8.3: GUI Practical II: Login Interface, Unsuccessful Login and Sucessful Login

selected font type.

Figure 8.4: GUI Practical II: Text Editor Interface

Compiled by Vincent M. Nofong, PhD. 53


8. GRAPHICAL USER INTERFACE APPLICATION DEVELOPMENT

(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)).

Figure 8.5: GUI Practical II: Image Viewer Interface

(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)).

Figure 8.6: GUI Practical II: Graph Ploting Interface

(e) The Assignment button should display the assignment (see Figure 8.7) which the students
are supposed to implement and submit for marking.

Figure 8.7: GUI Practical II: Assignment Interface

Compiled by Vincent M. Nofong, PhD. 54

You might also like