Progamming With Java - Lecture Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 170

School of Computing and Information Sciences

Department of Computer Science

Programming with Java (CSC 417)


2022/2023 Academic Year, Fourth Year, First Semester

Callistus Ireneous Nakpih, Ph.D.


Lecture Session 1
Introduction to Java
Programming
What is Java
What is Java
• Java is high level programming language
• Software developed with Java have a unique
feature of being able to work on any platform
regardless of the kind of computer and operating
system.
• In Java programmers are able to handle memory
manipulations; this prevents errors due to
improper memory usage.
• Java programs can access data over the web. It
can be used to develop distributed applications
that use resources from any other network.
What is Java
• Java source code is both compiled and
interpreted; the codes are compiled to bytecode
which is in machine language. Bytecodes are
platform independent, they can run on any
machine that has a Java interpreter, (write once run
anywhere)
• When a program has to be executed the
bytecode is fetched into memory and interpreted.
• There is a Java run-time system called Java
virtual Machine, which is the interpreter for
bytecode
What is Java
• In programming, errors in codes are called bugs, and, the
process of detecting and removing errors from code is
called debugging.
• In Java, a compiler checks for syntactic errors in the code
and lists them, all errors must be corrected before the
code can be executed.
• Java compels programmers to handle unexpected errors;
this ensures that java programs are reliable, robust, bug-
free, and do not crash
• Java has a function called Multithreading, which is the
ability to perform multiple tasks at the same time.
What is Java
• The key features that describe java (in summary)
– It is simple
– Portable
– Object-oriented
– Distributed
– Interpreted
– Secure
– Robust
– Architecture neutral
– High-performance
– Multithreaded
– dynamic
Java Syntax and Structure
Java Syntax and Structure
• Syntax in programming is the set of rules and
structure defined for coding in a particular
language. The syntax defined the vocabulary,
grammar and spelling of a programming
language
• Java was developed following C++
Java Syntax and Structure
MyClass.java (file name)
public class Main {
public static void main(String[] args) {
System.out.println("Hello Java Students");
}
}
Java Syntax and Structure
• Every line of code that runs in Java must be inside
a class. In our example, we named the class Main.
A class should always start with an uppercase first
letter.
• Java is case-sensitive: "MyClass" and "myclass"
are not the same in Java.
• The name of the java file must match the class
name. When saving the file, save it using the class
name and add ".java" to the end of the filename

Java Syntax and Structure
• Class – Main (name of class must be capital)
• Method (functions) – main (name of a method must
begin with a lowercase, e.g. myMethod, main etc. )
• Any code inside the main() method will be executed
• Access specifier/modifiers – Public, Private
• Curly braces {} are used to mark the beginning and the
end of a java code.
• Every statement or code in java must end with a
semicolon ;
Java Syntax and Structure
• The data members and methods of a class are
defined inside the class body.
• In java, braces { } mark the beginning and end
of a class or method. E.g.
Public class Employee
{
}
Java Syntax and Structure
Declaring methods in java
<access_specifier><return_type><method_nam
e> ([argument_list])
{
}
Java Syntax and Structure
access_specifier
• An access specifier/modifier defines where a
method can be accessed. A public specifier
allows the method to be executed from
another class. A private provides access to
methods for only the current class
Java Syntax and Structure
return_type
• The return_type of a method is the data type
of the value that is returned by the method.
• public void displayEmpName (); // returns no
value,
• public float calculateAllowance (); // returns a
value of float data type
Java Syntax and Structure
The System class
• To communicate with the computer, a
program needs to use certain system
resources such as the display device and the
keyboard.
• Java makes use of all these resources with the
help of a class called System, which contains
all the methods that are required to work with
these resources.
Java Syntax and Structure
The System class
• System is one of the most important and
useful classes provided by Java. It provides a
standard interface to common system
resources like the display device and the
keyboard.
Java Syntax and Structure

The out Object


• It is an object encapsulated inside the System
class, and represents the standard output device.
This object contains the println () method.
The println () method
• The println () method displays the data on the
screen. Eg.
• System.out.println (“Hello World”);
• Will display “Hello World” on the screen.
Java Syntax and Structure
The main method
• In a Java application, you may have many classes. Within
those classes, you may have many methods. The method
that you need to execute first should be the main ()
method.
• Syntax for the main () method is-
Public static void main (String args [])
{
}
• The main () method should exist in a class that is declared
as public.
• The primary name of the file in which the code is written,
and the name of the class that has the main () method
should be exactly the same
Java keywords or reserved words
• Java keywords or reserved words
• Java language is based Unicode which is
Lecture Session 2
Java Data Types and
Variables
JAVA DATA TYPES
Java Data Types
• A data type is the specifies the type and size
of values or literals that can be stored in a
variable.
• Each data type determines the kind of
operations that can be performed on them.
• Java has two main data types
– Primitive/standard data types
– Abstract/derived data types
Primitive Data Type
• These are basic data types built into the Java
language
• Java has eight primitive data types
Primitive Data Type
Data Type Description Bit Size Range
byte Byte-length integer 8 -128 to 128 (signed)
0 to 255 (unsigned)
short Short integer 16 -215 to 215 -1
int Integer 32 -231 to 231 -1
long Long integer 64 -263 to 2163 -1
float Single precision 32 +/- about 1039
floating point
double Double precision 64 +/- about 10317
floating point
char Single character 16
Boolean Boolean value; true 1
or false
Primitive Data Type
• Numeric data types; byte, short, int, long, float,
double
• byte, short, int, and long can hold only numbers
• float and double can hold decimal values
• All the data types can hold both negative and
positive values
• However, the keyword unsigned can be use to
restrict the range of values to positive numbers
• boolean can hold either true or false value
• Char can hold just a single character
Abstract/Derived Data Types
• Abstract data types are based on primitive
data types with more functionalities
• They are not built into the Java language, they
are defined by the programmer.
JAVA VARIABLES
Java Variables
• Variables are labels/names given to memory
locations to store data. This makes it easier to
refer to a specific memory location for its data
to be accessed or modified. All variables in
Java must be declared before use.
• There are three main categories of Java
Variables;
– Local Variable
– Static Variable
– Instance Variable
Types of Variables
Local Variable: is declared inside the body of a
method. Such variables cannot be accessed or used
by other methods, except for the method they are
declared in, and they cannot be defined by static
keyword
Instance Variable: is declared outside a method,
but inside a Class without static keyword. The value
of an instance variable can be changed by any
method in the class, but it is not accessible from
outside the class
Static Variable: is also declared outside a method
but inside a Class, declared with the static keyword.
Variable naming conventions
• These are rules that guides the naming of
variables in order to make programs readable
• A variable name:
– Must not be a keyword in Java.
– Must not begin with a digit.
– Must not contain embedded spaces.
– Can contain characters from various alphabets,
like Japanese, Greek, and Cyrillic.
Variable declaration
• All the attributes of a class are defined as data
members. The syntax used to declare a class
variable is: <data_type> <variable_name> =
value, e.g. int a = 4; String name = “Ada”;
• As the braces “{ }” are used to mark the
beginning and end of a class, a semicolon “;”
is used to mark the end of a statement.
Character and String Variables
• char (character) takes single alphabets in
single quotation marks, e.g. char name = ‘s’;
• strings can take a combination of characters
including numbers in double quotation marks;
String name = “UTAS”;
Numeric Variables
• Numeric variables can take integers and
decimal numbers
• int x;
• int y =3;
• double num = 4.23;
• float num2 = (float) 3.32;
Basic program structure
Code 1
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Basic program structure
Code 2
public class Main {
public static void main(String[] args) {
int x = 42;
double y = 5.3;
System.out.println(x);
System.out.println(y);
}
}
Java comments
• Comments are non-excutable parts of a
program
• Java uses a double of the forward slash (//)
singl-line statements out statement
• It uses /** …….**/ for multiple line statement
Reading input
Reading input
• System.in.read( ) is a Java console input,
• It reads characters from standard input.
• By default, standard input is line buffered, so
you must press ENTER before any characters
that you type will be sent to your program.
• If System.in.read( ) is being used, the program
must specify the throws java.io.IOException
clause. This line is necessary to handle input
errors.
Reading input
Other methods for reading input
• import java.util.Scanner;
//the next code creates the scanner object
• Scanner sc = new Scanner(System.in)
//the next code takes input from a user
• int x = sc.nextInt();
Lecture Session 3
Java Operations
Expressions and
Statements
Java Operations
Arithmetic operations
• The following arithmetic operators can be used in
a Java program; addition (+), subtraction (-),
multiplication (*), division (/), remainder(%).
Exercise
• A) Write a program to assign 30 to variable x, 54
to variable y, and the sum of x and y to the
variable z, and print out z.
• B) write a program to compute the following;
(27*3)+(4.3+2-1)/2
Increment and decrement operators
• To increase a variable by a value, we use the
operator ++
• to decrease, we use –
• These operators are placed either before or
after a variable
Comparison operations

Comparison Meaning Example

Operators Op
== Equal op1 = = op2
!= Not Equal op1 != op2
< Less than op1 < op2
> Greater than op1 > op2
<= Less than or op1 <= op2
equal
>= Greater than or op1 >= op2
equal
Logic Operators
Logical Use Return true if

Operators Op
&& op1 && op2 If both are true

|| op1 || op2 If one is true

! !op Op is false

& Op1 & op2 If both are true ,


always evaluates op1
and op2
| Op1 | op2 If one is true, always
evaluates op1 and op2
Java Expressions and Statements
Expressions
• An expression is a construct made up of
variables, operators, and method invocations,
which evaluates to a single value.
• E.g. int x = 4 or String name = “Gyogobu”
• We can have compound expressions from
smaller ones
• E.g. 3*2*8, a + b /c etc.
Statement
• A statement forms a complete unit of
execution.
• The are the instructions that directs the
program what actions to perform
• Statements must be terminated with
semicolon
• Types of Statements: Declaration Statements,
Expression Statements, Control/Conditional
Statements.
Declaration Statements
• These are statements that have variables
names declared with specific data types;
• The specified data type determines the kind of
values/literals a variable can hold.
• E.g.
– int x;
– char s;
– String name;
Expression Statement
• An expression terminated with a semicolon is an
expression statement.
• The following types of expressions can be made
into a statement by terminating them with a
semicolon (;).
– Assignment expressions
– Any use of increment ++ or decrement operators --
– Method invocations
– Object creation expressions
Expression Statement
• assignment statement, e.g.
<a declared variable> = 142.512;
float x = 142.512;
• method invocation statement, e.g.
System.out.println(“Gyogobu!");
• object creation statement, e.g.
Student Level200 = new Student();
• increment statement, e.g.
<a_value> ++;
5++;
i++;
Control/Conditional Statement
Control/Conditional Statement
• A control or conditional statement executes based
on a condition. There are three basic control
structures; Sequential, Selection, Repetition
• Sequential: default mode; Sequential execution of
code statements is done one line after another.
• Selection: used for decision-making, branching, or
choosing between 2 or more alternative paths. Java
has 2 types of selection statements: If-else
statements and Switch-case statements
• Repetition: used for looping, i.e. repeating a piece
of code multiple times in a row. Java has three types
of loops: while, Do-while, and for
Control/Conditional Statement
IF statement

public class ifExample {

public static void main(String[] args) {

int x = 10;
int y = 50;

if(x > y) { System.out.println("x is greater");}

}}
Control/Conditional Statement
If-else statement
• General form;
if (condition) statement1;
else statement2
• If the condition is true, then statement1 is executed.
Otherwise, statement2 (if it exists) is executed. In no
case will both statements be executed.
• A statement may be a single statement or a compound
statement enclosed in curly braces (i.e. a block).
• The condition is any expression that returns a boolean
value.
• The else clause is optional.
Control/Conditional Statement

if-Else Example

public class ForLoop {

public static void main(String[] args) {

int x = 10;
int y = 50;

if(x > y) { System.out.println("x is greater");}


else {System.out.println("y is greater");}
}}
Control/Conditional Statement
• Exercise: write a program to display “failed
grade” if a grade is less than 50, or display
“pass grade” if the grade is greater than 50.
Control/Conditional Statement
If else-if Ladder
• A common programming construct that is based upon a sequence
of nested ifs is the if else- if ladder. This is the general structure:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
Control/Conditional Statement
• The if statements are executed from the top
down. As soon as one of the conditions
controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder
is bypassed. If none of the conditions is true, then
the final else statement will be executed.
• The final else acts as a default condition; that is, if
all other conditional tests fail, then the last else
statement is performed.
• If there is no final else and all other conditions
are false, then no action will take place.
If-else Example

public class IfElseIf {

public static void main(String[] args) {


int marks = 50;
if (marks>= 80) {System.out.println("Excellent");}
else if(marks>=70) {System.out.println("Very Good");}
else if(marks>=60) {System.out.println("Good");}
else if(marks>=50) {System.out.println("Average");}
else {System.out.println("Poor");}
}}
Control/Conditional Statement
Code: if-else-if statement
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
Control/Conditional Statement
• Exercise: write a program to display the
following grades according to their
corresponding marks;
Grade Marks
A 81 to 100
B 71 to 80
C 61 to 70
D 51 to 60
E 40 to 50
F Less than 40
Control/Conditional Statement
Code 3
class IfElse {
public static void main(String args[ ]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Control/Conditional Statement
Switch Statement
• The switch statement is Java's multiway
branch statement. It provides an easy way to
dispatch execution to different parts of your
code based on the value of an expression.
• As such, it often provides a better alternative
than a large series of if-else-if statements.
Control/Conditional Statement
General structure of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
Control/Conditional Statement
• The expression must be of type byte, short,
int, or char;
• Each of the values specified in the case
statements must be of a type compatible with
the expression.
• Each case value must be a unique literal (that
is, it must be a constant, not a variable).
• Duplicate case values are not allowed.
Control/Conditional Statement
• The switch statement works like this: The value of
the expression is compared with each of the
literal values in the case statements. If a match is
found, the code sequence following that case
statement is executed.
• If none of the constants matches the value of the
expression, then the default statement is
executed.
• However, the default statement is optional.
• If no case matches and no default is present,
then no further action is taken.
Control/Conditional Statement
• The break statement is used inside the switch
to terminate a statement sequence.
• When a break statement is encountered,
execution branches to the first line of code
that follows the entire switch statement.
• This has the effect of "jumping out" of the
switch.
Code
public class switchExample
{
public static void main(String[] args)
{
int week = 6;
switch(week)
{
case 1: System.out.println("Sunday"); break;
case 2: System.out.println("Monday"); break;
case 3: System.out.println("Tuesday"); break;
case 4: System.out.println("Wednesday"); break;
case 5: System.out.println("Thursday"); break;
case 6: System.out.println("Friday"); break;
case 7: System.out.println("Saturday");
default: System.out.println("No valid day of the week"); break;
}}}
Control/Conditional Statement
• The break statement is optional. If you omit
the break, execution will continue on into the
next case. It is sometimes desirable to have
multiple cases without break statements
between them.
• For example, consider the following program:
Code
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default: System.out.println("i is 10 or more"); }
Control/Conditional Statement
Nested Switch statements
• You can use a switch as part of the statement
sequence of an outer switch. This is called a
nested switch.
• Since a switch statement defines its own
block, no conflicts arise between the case
constants in the inner switch and those in the
outer switch.
Control/Conditional Statement
Example
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
Control/Conditional Statement
• From the above, the case 1: statement in the
inner switch does not conflict with the case 1:
statement in the outer switch. The count
variable is only compared with the list of cases
at the outer level. If count is 1, then target is
compared with the inner list cases.
Control/Conditional Statement
• The switch differs from the if in that switch can
only test for equality, whereas if can evaluate any
type of Boolean expression. That is, the switch
looks only for a match between the value of the
expression and one of its case constants.
• No two case constants in the same switch can
have identical values. Of course, a switch
statement enclosed by an outer switch can have
case constants in common.
• A switch statement is usually more efficient than
a set of nested ifs.
Control/Conditional Statement
For loop
The usage of for loop is as follows
for (initial statement; termination condition; increment
instruction)
statement;
• When multiple statements are to be included in the for
loop, the statements are included inside curly braces. Thus,
for (initial statement; termination condition; increment instruction)
{
statement1;
statement2;
}
Control/Conditional Statement
Code
int i;
for(i=0; i<6; i++)
{
System.out.println(i);
}
Control/Conditional Statement
• Like all other programming languages, Java
allows loops to be nested. That is, one loop
may be inside another.
Control/Conditional Statement
Code
class Nested {
public static void main(String args[ ]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Control/Conditional Statement
While loop
• The while loop is Java's most fundamental
looping statement. It repeats a statement or
block while its controlling expression is true.
Here is its general form:
while (condition) {
// body of loop
}
Control/Conditional Statement
• The condition can be any Boolean expression.
• The body of the loop will be executed as long
as the conditional expression is true.
• When condition becomes false, control passes
to the next line of code immediately following
the loop.
• The curly braces are not necessary if only a
single statement is being repeated.
Control/Conditional Statement
Do…while statement
• If the conditional expression controlling a while loop is
initially false, then the body of the loop will not be
executed at all.
• However, sometimes it is desirable to execute the body
of a while loop at least once, even if the conditional
expression is false to begin with.
• In other words, there are times when you would like to
test the termination expression at the end of the loop
rather than at the beginning. Fortunately, Java supplies
a loop that does just that: the do-while.
• The do-while loop always executes its body at least
once, because its conditional expression is at the
bottom of the loop.
Control/Conditional Statement
General form
do {
// body of loop
} while (condition);
Control/Conditional Statement
• Each iteration of the do-while loop first
executes the body of the loop and then
evaluates the conditional expression. If this
expression is true, the loop will repeat.
Otherwise, the loop terminates.
• As with all of Java's loops, condition must be a
Boolean expression.
Control/Conditional Statement
public class doWhileExample
{
public static void mani(String[] args)
int t = 5;
int fact2 =1;
int m = 1;
do
{
fact2* = m;
m++;
} while (i<=n);
System.out.println(factorial of ” + t + “is” + fact2);

}
Control/Conditional Statement
• The do-while loop is especially useful when
you process a menu selection, because you
will usually want the body of a menu loop to
execute at least once.
Control/Conditional Statement
• In the program, the do-while loop is used to
verify that the user has entered a valid choice.
If not, then the user is re-prompted. Since the
menu must be displayed at least once, the do-
while is the perfect loop to accomplish this.
Control/Conditional Statement
Break Statement
• By using break, you can force immediate
termination of a loop, bypassing the
conditional expression and any remaining
code in the body of the loop. When a break
statement is encountered inside a loop, the
loop is terminated and program control
resumes at the next statement following the
loop.
Control/Conditional Statement
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[ ]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Control/Conditional Statement
• As you can see, although the for loop is
designed to run from 0 to 99, the break
statement causes it to terminate early, when i
equal 10.
Control/Conditional Statement
Continue Statement
• Sometimes it is useful to force an early
iteration of a loop. That is, you might want to
continue running the loop, but stop
processing the remainder of the code in its
body for this particular iteration.
Control/Conditional Statement
• This is, in effect a goto, just pass the body of the
loop to the loop's end.
• The continue statement performs such an action.
In while and do-while loops, a continue
statement causes control to be transferred
directly to the conditional expression that
controls the loop.
• In a for loop, control goes first to the iteration
portion of the for statement and then to the
conditional expression. For all three loops, any
intermediate code is bypassed.
Control/Conditional Statement
// Demonstration continue statement.
class Continue {
public static void main (String[] args) {
for (int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println ("");
}
}
}
Control/Conditional Statement
• This code uses the % operator to check if i is
even. If it is, the loop continues without
printing a newline.
• As with the break statement, continue may
specify a label to describe which enclosing
loops to continue.
Lecture Session 4
Object Oriented
Programming (OOP) in
Java
OOP Concepts
Features of OOP
• Object Oriented Programming approach is the
bundling of both data and functions into one
unit known as object.
• The functions of a particular object can only
access the data in the object providing high
level of security for the data.
• The functions in the object are known as
member functions or sometimes as methods.
Features of OOP
The key features of OOP programming languages
are; Objects and Classes
• An Object is a program representation of some
real-world thing (i.e person, place or an event).
• Objects can have both attributes (data) and
behaviours (functions or methods). Attributes
describe the object with respect to certain
parameters, and Behaviour or functions describe
the functionality of the object.
Features of OOP
• Example of object
Polygon Object Bank Account

Attributes Behaviour Attributes Behaviour


Position Fill Move Erase Account number DeductFunds
Color Border Changecolor Account Name Transferfunds
color Balance DepositFunds
Showbalance
Features of OOP
• Exercise: complete the table for the Car and
Student objects
Car Student

Attributes Behaviour Attributes Behaviour


Brand Accelerate Full Name Register
Breaks ID View Results
Chasis # GPA
Turn Pay Fees
Colour Gender
Programme
# of seats Email
Features of OOP
• According to Pressman, Objects can be any one of
the following:
a) External entities
b) Things
c) Occurrences or events
d) Roles
e) Organisational units
f) Places
g) Data Structures
Features of OOP
• For example, objects can be an menu or
button in an graphic user interface program or
it may be an employee in an payroll
application.
• Objects can also represent a data structure
such as a stack or a linked list. It may be a
server or a client in an networking
environment.
Features of OOP
• Objects with the same data structure and
behavior are grouped together as class.
• In other words, Objects are “instances” of a
class.
• Classes are templates that provide definition
to the objects of similar type.
• Objects are like variables created whenever
necessary in the program.
Features of OOP
Encapsulation
• Classes and Objects support data encapsulation and
data hiding which are key terms describing object
oriented programming languages.
• Data and functions are said to be bound together or
encapsulated in an single entity as object. The data is
said to be hidden thus not allowing accidental
modification.
• With encapsulation, we don’t have to know the
internal working mechanism of classes before we can
use them.
• E.g. we don’t have to know the computer keyboard
mechanism works before we can use it to type.
Features of OOP
Inheritance
• Inheritance is one of the most powerful feature
of OOP Languages that allows you to derive a
class from an existing class and inherit all the
characteristics and behaviour of the parent class.
• This feature allows easy modification of existing
code and also reuse code. The ability to reuse
components of a program is an important feature
for any programming language
Features of OOP
Polymorphism and Overloading
• Operator overloading feature allows users to define
how basic operators work with objects. The operator +
will be adding two numbers when used with integer
variables. However when used with user defined string
class, + operator may concatenate two strings. Similarly
same functions with same function name can perform
different actions depending upon which object calls the
function. This feature of Java where same operators or
functions behave differently depending upon what
they are operating on is called as polymorphism (Same
thing with different forms). Operator overloading is a
kind of polymorphism.
Features of OOP
• OOP approach offers several advantages to
the programmers such as
– Code can be reused in situations requiring
customization
– Program modeling and development is closer to
real world situations and objects
– Easy to modify code
– Only required data bound to operations and thus
hiding data from unrelated functions
Classes, Objects, Methods and
Constructors
Classes and Objects
• In Java an object is an instance of a class.
• A class is a group of logically related objects
that have similar properties.
• A method is a function that is created in class
which defines the behavior (function) of the
object.
• We have already seen the basic structure of a
java program and how a class and method are
created.
Classes and Objects
• In java an object is created from a class by specifying
the class name followed by the object name, and with
the keyword new. In the example below, we have
created an object called myObj from the Main class

public class Main {


int a = 7; //global variable/ class attribute
public static void main(String[] args) {
Main myObj = new Main(); //the object
System.out.println(myObj.a);
}}
Classes and Objects
class Student{
int idx; //class attribute
String name;
int age;
public static void main(String args[]){
Student s1=new Student();//the object
System.out.println(s1.idx); //printing object value
System.out.println(s1.name);
System.out.println(s1.age);
} }

//not that the object s1 is an instance of the class Student


Classes and Objects
• Student
• Functions/behavior /method
– Register course
– Attendance
Classes and Objects
• We can have more than one object in one class.

public class Main {


int a = 7;
int b = 8;
public static void main(String[] args) {

Main myObj1 = new Main(); //object 1


Main myObj2 = new Main(); //object 2
System.out.println(myObj1.a);
System.out.println(myObj2.b);
}
}
Classes and Objects
• We can also create an object in a class and access it from a different class. We can either have the
two classes below in a single file or in two separate files. Here, we have to save our first class with a
file name test_oop.java as follows.

public class test_oop {


int a =4;
int b =10;
int c = a + b; }
• our second class has to be saved with a file name Test_oop2.java. as follows;

public class Test_oop2 {


public static void main(String[] args) {
test_oop myObj = new test_oop();//new object from test_oop class
test_oop obj2 = new test_oop();
System.out.println(myObj.a);
System.out.println(obj2.b + myObj.c); } }

• Note that one class/file contains attributes, and the other class/file contains the main() method for
execution.
Classes and Objects
Example 2
class Student{
int idx;
String name;
int age;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student(); //object from Student class
System.out.println(s1.idx);
System.out.println(s1.name);
}
}
Methods
public class methodz {

public static void main(String[] args) {


//use class parameters in main method
String name = "kim";
int x = 9;
int y = 10;
if(x<y) {add(x,y);//+ function call}
else {multiply(x,y); //* function call}}
//addition function
public static void add(int a, int b) {
int z = a + b;
System.out.println(z);}//end of addition function
//multiplication function
public static void multiply(int a, int b) {
int z = a*b;
System.out.println(z);}//end of multiplication function}}
Objects initialization
Objects initialization: storing data in them.
There are three main ways
• By reference variable
• By method
• By constructor
Objects initialization
Initializing objects by referencing
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101; //initializing variable id by reference
s1.name=“KWOYIRE"; //initializing variable id by reference
System.out.println(s1.id+" "+s1.name);//printing members with a white spac
e
}
}
Objects initialization
We can also create multiple objects and initialize them by reference.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
Student s1=new Student(); //Creating objects 1
Student s2=new Student(); //Creating objects 2
s1.id=101; //Initializing objects 1 by reference
s1.name=“KWOYIRE"; //Initializing objects 1 by reference
s2.id=102; //Initializing objects 2 by reference
s2.name=“Mwinkara"; //Initializing objects 2 by reference
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name); } }
Objects initialization
Initialization by method
• In the following example the test_oop class has
been recreated with two defined methods
insertData(double o, double h) and
computeSine().
• We can create two objects of test_oop class and
initialize the value to these objects by invoking
the insertData() method. We also compute and
display the data of the objects by invoking the
computeSine() method
Objects initialization
public class triangle {
double opposite;
double hypotenuse;

void insertData(double o, double h) {


opposite = o;
hypotenuse = h; }

void computeSine( )
{System.out.println(opposite/hypotenuse);}
}
Objects initialization
//second class with object defined from test_oop calss
public class triangle2 {
public static void main(String[] args) {
Class name name of object = new class name
triangle sine1 = new triangle();//new object from test_oop class
triangle sine2 = new tringle ();

sine1.insertData(10, 7);
sine2.insertData(7, 20);

sine1.computeSine();
sine2.computeSine(); } }
Objects initialization
Initializing objects by Constructor
• A constructor is a special method that is used to initialize objects
• Note, when initializing an object through a constructor the constructor name must be the
same as the class name
public class Main {
String fName;
String sName;
int age;
//defining a Main constructor with the same
public Main (String fn, String sn, int a) {
fName = fn;
sName = sn;
int age = a; }
//defining the main method for executing the code
public static void main(String[] args) {
Main records = new Main( “Daniel”, “Adda“, 78); //initializing Main constructor with data
System.out.println(records.fName + " " + record.sName + “ “ + record.age); } }
Inheritance
• As mentioned earlier, inheritance which is one
of the key features of OOP allows us to create
a class that can take or inherit all the methods
and attributes of another class. This makes it
very flexible for reuse of Java code
• We use the keyword extends to inherit from a
parent class.
Inheritance
public class test_oop {
int a = 4;
int b = 6;
double opposite;
double hypotenuse;

void insertData(double o, double h) {


opposite = o;
hypotenuse = h; }

void computeSine() {System.out.println(opposite/hypotenuse);}


}
Inheritance
public class Test_oop2 extends test_oop {
public static void main(String[] args) {

test_oop myObj = new test_oop();


myObj.insertData(10, 7);
myObj.computeSine();
}}
//the class Test_oop2 becomes a child class or a subclass,
and will inherit all the attributes and methods of the
parent class or supper class test_oop
Inheritance
//illustrating inheritance. Example 2

//Parent/Super Class
public class Employee {
//class parameters
private int empNum; //integers declare private cannot be
accessed in other subclasses (data hiding)
private double empSal;

//class methods
public int getEmpNum(){
return empNum;}
public double getEmpSal() {
return empSal;}

public void setEmpNum(int num) {


empNum = num;}
public void setEmpSal(double sal){
empSal = sal;}
//subclass to inherit Employee class
public class EmployeeWithTerritory extends Employee{
//this class is also an employee but with extra attributes and
methods
//we would have had to repeat the code of the super class and
then add the extra para and method here
//however we can us create this class to inherit all
attributes and methods of Employee
//and then just add the extra
//this employee is just a type of employee with exatra
features

private int territory;


public int getTerritoryNUm() {
return territory;}
public void setTerritoryNum(int num) {
territory = num;
}}}
Encapsulation
• Encapsulation allows programmers to hide some
data which they intend that users do have access
to.
• Encapsulation is achieved by declaring class
variables/attributes as private
• For instance, if we had declared the class above
as follows; private int a; and private int b; then
the class Test_oop2 wouldn’t have been able to
inherit them.
Lecture Session 4
Arrays
Definition and Concept of an Array
• An Array is a list or collection of data items
which are stored in a computer memory,
referred to by a common variable name called
Array name and Subscript/index.
• Arrays have;
– Element− Each item stored in an array is called an
element.
– Index − the location of an element an array has a
numerical index, which is used to access the
element. Index usually begins from zero (0).
Callistus I. Nakpih, PhD - CKT UTAS,
Navrongo
Definition and Concept of an Array
Advantage of using an array:
• Multiple and huge quantity of data items can
be stored under single variable name
• Arrays saves memory space
• Arrays helps to arrange the data (Sorting)
items in particular order [ascending /
descending]
• Search data items in Array is faster.
Callistus I. Nakpih, PhD - CKT UTAS,
Navrongo
Types/Concepts of Arrays
There are two main types or concepts of Array:
• One/Single Dimensional array
• Multi-dimensional Arrays or matrix.

Callistus I. Nakpih, PhD - CKT UTAS,


Navrongo
Declaration, Initialisation and
Instantiation of Arrays
Array Declaration
• Declaring an array is denoting its datatype, jus
as it is done for Java variables.
• An array can take any of these forms;
datatype[ ] arrayName;
datatype [ ]arrayName;
datatype arrayName[ ];
Declaration, Initialisation and
Instantiation of Arrays
Array Instantiation
• This is creating an instance of an array/ array
object.
Structure for instantiating an array
datatype VariableName = new datatype[size];
• The size of the is array is usually specified
when instantiating the array
Declaration, Initialisation and
Instantiation of Arrays
Array Instantiation
• We can instantiate array objects just as we
instantiate class objects using the keyword new
• double array2 = new double[20]
• the above statement means that have declared
array2 of type double, and instantiated it as a
double object (using the new keyword), and set
the size of the array to 20.
• This also means that, elements can be stored in
array2 in subscripts 0 to 19
Declaration, Initialisation and
Instantiation of Arrays
Array initialisation
• Initialising an array means assigning a value to
the array. E.g.
• int num1[0]=10;
– This means we are assigning element 10 into
subscript/index 0 position of array num1
– Subsricpts/indexes always begin from 0
//Example code to illustrate Array declaration, instantiation and initialisation

public class ArrayExample{

public static void main(String[] args) {


int a[]=new int[4];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
//traversing array
for(int i=0;i<a.length;i++)//length is the property
of array
System.out.println(a[i]);
}}
/**Example to illustrate initializing an
array with elements **/

public class ArrayExample2 {

public static void main(String[] args) {


int[] array2 = {1, 13, 50,100,200};

/**when you initialise an array upon its


creation, you don’t need to set its size**/

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


{System.out.println(array2[i]);}
}}
/**add 3 to every array element **/

public class ArrayExample2 {

public static void main(String[] args) {


int[] array2 = {1, 13, 50,100,200};

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


array2[i] += 3;
{System.out.println(array2[i]);}
}}
//Array search example
Import java.util.Scanner;
public static void arraySearch() {
Scanner sc = new Scanner(System.in);

int itemOrdered = sc.nextInt();

int[] validValues = {101, 108, 201, 311, 409, 411, 412};

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


if(itemOrdered == validValues[x]) {
System.out.println("Valid Item");
break; }
else {System.out.print("Not Valid");}
break;
}}
/**a program to travers through an array an state if an
element is valid if the is between 10 and 120, otherwise
invalid**/
public class ArrayExample3 {
public static void main(String[] args) {

int[] array3 = {700, 10, 13, 50,100,200, 500};


for (int i=0; i< array3.length; i++) {
if(array3[i] >=10 && array3[i]<=120) {

System.out.println(array3[i] + " valid");


}
else {System.out.println(array3[i] + " Not valid");}
}}
}
Class exercise
• write a program; create an array and initailise
the array with some random numbers
• Let your program take input from a user; if the
the number of the user is in the array, your
program should print the number and state
that is is valid, e.g. the number 3 is valid
• If the number of the user is not in the array,
the program should print the number and
state that it is not valid
Lecture Session 5
Error/Exception Handling
Error/Exception Handling
Introduction
• An exception is an unexpected error or
condition
• A program can be written to generate
different types of exceptions such as;
– Your program ask user for input, but the user
enters invalid data
– Your program attempts to divide a number by 0
– Your programe attempts to save data into a full
disk
Introduction
• The object-oriented techniques to manage
such errors the group of methods known as
exception handling.
• Note that exceptions are objects; their class
name is Exception
• In Java, there are two basic classes of errors;
Errors and Exceptions.
• Both of these classes descend from the
Throwable class illustrated in the next slide.
Structure of Exceptions
• Throwable
– Exception
• IOException
• RuntimeException
– ArithmaticException
– ArrayIndexOutofBoundsException
– Others
• Others
– ErrorExceptions
• OutofMemoryExceptions
• InternalErrorException
• others
The Error Class
• The Error class represents more serious errors
from which your program usually cannot
recover.
• Errors are the ones you make in your own
program; like misspelling a class name.
• Also when your program cannot locate a
required class, or run out of memory, an error
occurs.
The Exception Class
• The Exception Class comprises of less serious
errors that represents unusual conditions that
rises while a program is running and from
which a program can recover.
• Example of Exception class errors include;
perfuming an illegal arithmetic operation, or,
using a wrong array subscript.
Try and Catch
• When you write a segment of code in which
something might go wrong, you have to place
the code in a try block, which is a block of
code you attempt to execute while
acknowledging that an Exception might occur.
Try and Catch
• A try block consist of the following;
– The try keyword.
– An opening curly brace.
– The statement that might cause the exception.
– A closing curly brace.
• There must be at least one catch block
immediately following a try block.
• A catch block is the segment of code that can
handle an exception that might be thrown by the
try block that precedes
• Each catch block can catch one type of Exception
Try and Catch
• A catch block can be created by typing the
following;
– The catch keyword
– An opening parenthesis
– An Exception type
– A name for an instance of the Exception type
– a closing parenthesis
– An opening curly brace
– Statements that take the action you want use to
handle the error condition
– A closing curly brace
Try and Catch
• If a method throws an Exception that will be
caught, you must also use the keyword throw,
followed by an Exception type in the method
header.
• The code in the next slide shows the general
structure of a try…catch pair
//General Structure of try…catch
public class soemMethod() throws someException {
try {
//Statements that might cause an Exception
}
catch(someException ExceptionInstance) {
//what to do about it
}
//statements here execute even if there was no Exception
}
/**try…catch example 1; throwing and catching
multiple exceptions **/
public class ExceptionHandling {
public static void main(String[] args) throws
ArithmeticException, IndexOutOfBoundsException {
int number = 17, denomenator= 0, result;
int[] arrayB = {7,17,27};
try {
result = number/denomenator; //first try
result = arrayB[number]; // second try}
}
catch(ArithmeticException error) {
System.out.println("Arithmetic Error");
}
catch(IndexOutOfBoundsException error) {
System.out.println("Index error");
}
}}
//try…catch example 2
public class ExceptionHandling {

public static void main(String[] args) {


try {
//statement that might cause exception
int x = 15/0;
}
//handling the exception using catch
catch(ArithmeticException e) {
System.out.println(e);
}
//the rest of the program
System.out.println("the rest of the program follows
here...");
}}
Using finally Block
• When you have actions you must perform at the
end of try…catch sequence, you can use finally
block.
• The code within finally block executes whether
the preceding try block identifies Exceptions or
not.
• Usually, the finally block is used to perform a
clean-up task that must happen whether or not
any Exception occurred, and whether or not
Exceptions that occurred were caught.
//General Structure of finally block
public class soemMethod() throws someException
{
try {
//Statements that might cause an Exception
}
catch(someException ExceptionInstance) {
//what to do about it
}
finally {
//Statements here always execute
}

}
//finally example
public class ExceptionHandling {

public static void main(String[] args) {


try {
//statement that might cause exception
int x = 15/0;
}
//handling the exception using catch
catch(ArithmeticException e) {
System.out.println(e);
}
finally {
System.out.println(“this part executes whether an
exception is thrown, caught or none; it executes
regardless of what eve happens");
}}
How to Create custom Exceptions
• There are over 40 categories of Java
Exceptions, however, you need exceptions to
handle other behavior of your program which
are not pre-defined for you in Java.
• You might want to throw an Exception when
your bank balance is negative; or when user
enters a negative number for people, or
outside party attempts to access your email.
How to Create custom Exceptions
• To create your own Throwable Exception, you
must extend a subclass of Throwable.
• Throwable has two sub class; Exception and
Error which are used to distinguish
recoverable and non-recoverable errors.
• Because you always want to create your own
Exceptions for recoverable errors, you should
extend your Exceptions from Exception class.
How to Create custom Exceptions
• You can extends any existing class, such as
ArithmeticException, NullPointerException
etc., but usally it is good to extend directly
from Exceptions.
• The general way is to first create your
exception, save it in file so that you can use it
in a program on a different file.
/**custom exception example. This is saved in a file
for later use**/
//note that supper() refers to the supper class object
//
public class InvalidNumberException extends Exception{

public InvalidNumberException() {
super("You entered an Invalid number; should be
between 1 and 5");
}}
//program that uses the custom exception
//in this program, you want a user to enter numbers between 1
and 5, otherwise an exception should be thrown**/
import java.util.Scanner;
public class CustomException{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("Enter number between 1 and 5");


int userNum = sc.nextInt();
try {
if(userNum <1 || userNum >5) {
throw new InvalidNumberException();
}}
catch(InvalidNumberException error) {
System.out.println(error.getMessage());
}}}
/**Example 2; another way is to pass an argument
message to the constructor
InvalidNumberException() then the error text
will be passed to the same constructor in the
program when the exception is thrown**/

public class InvalidNumberException extends


Exception{

public InvalidNumberException(String message)


{
super(message);

}
//Example 2: program that uses the custom exception
/**here the error text is passed to the constructor
InvalidNumberException() **/

import java.util.Scanner;
public class CustomException{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("Enter number between 1 and 5");


int userNum = sc.nextInt();
try {
if(userNum <1 || userNum >5) {
throw new InvalidNumberException(”Invalid Number”);
}}
catch(InvalidNumberException error) {
System.out.println(error.getMessage());
}}}
END OF NOTES

You might also like