Object Oriented Programming - 2 PDF
Object Oriented Programming - 2 PDF
COMPUTING CENTRE
While all reasonable precautions have been taken in the preparation of this
document, including both technical and non-technical proofing. University of Dar es
Salaam Computing Centre and all staff assume no responsibility for any errors or
omissions. No warranties are made, expressed or implied with regard to these
notes. University of Dar es Salaam Computing Centre shall not be responsible for
any direct, incidental or consequential damages arising from the use of any
material contained in this document. If you find any errors in these training
modules, please inform University of Dar es Salaam Computing Centre. Whilst
every effort is made to eradicate typing or technical mistakes, we apologise for any
errors you may detect. University of Dar es Salaam Computing Centre manuals are
updated on a regular basis, so your feedback is both valued by us and will help us
to maintain the highest possible standards.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 3 OBJECT ORIENTED PROGRAMMING
Table of contents
Introduction.................................................................................................................................... 6
Course Description................................................................................................................................. 6
Course Objectives .................................................................................................................................. 6
Delivery Methodology ............................................................................................................................ 6
Chapter 1: Introduction to java ................................................................................................... 7
1.1. History of java ............................................................................................................................. 7
1.2. Types of Java Applications ........................................................................................................... 7
1.3. Features of java .............................................................................................................................. 8
1.4. Tools needed to create and run a java program........................................................................ 9
1.5. Local Environment Setup .............................................................................................................. 9
1.6. Popular Java Editors .................................................................................................................... 10
1.7. How to create and run a Java Program in the Computer ....................................................... 10
1.8. SDK Tools...................................................................................................................................... 12
Chapter 2. OOP CONCEPTS................................................................................................... 14
2.1 Java OOPs Concepts ................................................................................................................... 14
2.2 Procedural Programming Languages......................................................................................... 14
2.3 Object-Oriented Programming Languages ................................................................................ 15
2.4 Advantage of OOPs over Procedure-oriented programming language ................................ 15
Chapter 3. Basic concepts ........................................................................................................ 17
3.1 Statements and expressions ....................................................................................................... 17
3.2 Comments....................................................................................................................................... 17
3.3 Data types and literals .................................................................................................................. 17
3.4 Operators ........................................................................................................................................ 20
3.5 Type casting ................................................................................................................................... 24
3.6 Identifiers......................................................................................................................................... 24
3.7 Variables and constants ............................................................................................................... 25
3.8 The anatomy of a simple program .............................................................................................. 26
Chapter 4. Classes and Objects .............................................................................................. 28
4.1 Class declaration ........................................................................................................................... 28
4.2 Member Variables Declaration .................................................................................................... 29
4.3 Defining Methods ........................................................................................................................... 29
4.4 Constructors ................................................................................................................................... 31
4.5 Access Modifiers ............................................................................................................................ 32
4.6 The Garbage Collector ................................................................................................................. 32
4.7 Packages and class library .......................................................................................................... 32
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 4 OBJECT ORIENTED PROGRAMMING
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 6 OBJECT ORIENTED PROGRAMMING
Introduction
Course Description
The course introduces students to key features of object oriented programming
languages and utilization of common programming structures and constructs of
Object Oriented Programming Language in creating computer programs. The course
also helps a student to design large-scale software systems based on requirements
specification
Course Objectives
At the end of the course students should be able to
1. Describe characteristics of object oriented programming language
2. Describe object and its relation with class
3. Compare and contrast object oriented programming with procedural
programming languages
4. Apply control structures and modular approach in creating computer
programs
5. Apply classes and methods in program development
6. Apply overload and override in programs development
7. Create and use abstract data types
8. Design modular solutions to a given problem statement
9. Develop software by employing the principles of encapsulation, data
abstraction and polymorphism
10.Implement abstract classes and interfaces in software development
11.Make appropriate use of advanced features such as inheritance, exception
handling, I/O, references and GUIs in software implementation
Delivery Methodology
The course will be delivered in form of lectures in the classroom and in the
Computer lab accordingly. Exercise with real life nature will be provided during and
at the end of the class. The manual is also designed such that one can follow the
course at own time and pace
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 7 OBJECT ORIENTED PROGRAMMING
What is Java
Java is a high level, robust, secured and object-oriented programming language.
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java
is currently used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus etc.
Web Applications such as irctc.co.in, javatpoint.com etc.
Enterprise Applications such as banking applications.
Mobile
Embedded System
Smart Card
Robotics
Games etc.
1) Standalone Application
It is also known as desktop application or window-based application. An
application that we need to install on every machine such as media player,
antivirus etc. Abstract Window Toolkit (AWT) and Swing are used in java for
creating standalone applications.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 8 OBJECT ORIENTED PROGRAMMING
2) Web Application
An application that runs on the server side and creates dynamic page, is called
web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for
creating web applications in java.
3) Enterprise Application
An application that is distributed in nature. Some of the more common types of
enterprise applications include automated billing systems, payment processing,
content management Enterprise Resource Planning (ERP), and Business Intelligence
e.t.c.
It has the advantage of high level security, load balancing and clustering. In java,
Enterprise Java Beans (EJB) is used for creating enterprise applications.
Applications are designed to solve problems encountered by large enterprises.
Enterprise applications are not only useful for large corporations, agencies, and
governments, however. The benefits of an enterprise application are helpful, even
essential, for individual developers and small organizations in an increasingly
networked world.
The features that make enterprise applications powerful, like security and reliability,
often make these applications complex. The Java EE platform is designed to reduce
the complexity of enterprise application development by providing a development
model, API, and runtime environment that allows developers to concentrate on
functionality.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java Micro
Edition(ME) are used for creating mobile applications.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 9 OBJECT ORIENTED PROGRAMMING
Follow the instructions to download java and run the .exe to install Java on your
machine. Once you installed Java on your machine, you would need to set
environment variables to point to correct installation directories.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 10 OBJECT ORIENTED PROGRAMMING
Environment variable PATH should be set to point to where the Java binaries have
been installed. Refer to your shell documentation if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the
end of your '.bashrc: export PATH=/path/to/java:$PATH'
Notepad: On Windows machine you can use any simple text editor like
Notepad, Notepad++ or TextPad.
Netbeans: is a Java IDE that is open-source and free which can be
downloaded from https://netbeans.org/downloads/index.html.
Eclipse: is also a Java IDE developed by the eclipse open-source community
and can be downloaded from http://www.eclipse.org/.
System.out.println("Hello World");
}
}
Save the file as text file with the name Hello.java and save it in your home
directory eg if your account name is Salima and you are using windows then save in
c:\users\salima\Hello.java
How to Compile a Java Program
Before a program can be run on your computer, it must first be compiled.
Compilation is a process that will transform your program into a form the computer
can execute.
The computer cannot execute the Java statements as they currently appear in
the program; the statements must be translated to an intermediate form for
execution.
The output from the compiler is the same program, now represented by a set of
Java byte codes. Java byte codes are a set of instructions written for a hypothetical
computer, known as the Java virtual machine.
In addition to translation, a compiler reports on any grammatical errors made by
the programmer in the language statements of the program. If errors are reported,
it is necessary to return to the editor to correct the errors, resave the program, and
then recompile the program.
If you are working on a PC using Microsoft’s Windows environment, then open an
MSDOS window and change your subdirectory to wherever you saved your Java
program. The command to compile a Java program using the Java SDK is javac. To
compile the first program listed, you would issue the following command:
javac Hello.java
The byte code produced by the compiler will be stored in a file called Hello.class.
You should not try to edit or print a class file.
If you get errors listed in the MSDOS window, they could be caused by the following
problems.
You have not modified the path entry of your system environmental
variable correctly and the computer cannot execute the command
javac to compile your program.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 12 OBJECT ORIENTED PROGRAMMING
You have made a mistake when typing the program and the syntax of
at least one statement might be incorrect.
You should carefully examine all three cases and make any necessary amendments
before you recompile the program.
How to Execute (run) a Java Program
The program stored as Java byte codes is loaded into the memory of the computer,
and is read and translated by an interpreter. An interpreter will read the byte code
one “line” at a time, and translate each line, in turn, into a sequence of commands
that can be directly executed by the computer. There exist different interpreters for
different computers. The interpreter reads the respective byte codes and instructs
the computer to execute the meanings of the instructions.
If the compilation is successful, you can execute (run) the program. The command
to execute or run a Java program using the Java SDK is java. To execute the
HELLO WORLD program you would issue the following command
in the same window where you compiled the program:
java Hello
If the program has executed correctly, the output should appear in your screen as
Hello World
You can stop the program by clicking on the X in the upper-right corner of the
window, by choosing Close from the pull-down menu or
by pressing the Alt-F key combination.
It is possible for a program to fail during the execution phase, in which case it must
be stopped from any further execution. If modifications to the program are
required, it is necessary to perform the amendments on the source file, recompile
and rerun the program
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 13 OBJECT ORIENTED PROGRAMMING
java—the Java Interpreter that you use to run programs written in the java
programming language
EXCERCISES
1. What is Java?
2. Why are interpreted languages slower than compiled ones?
3. explain different features of java
4. explain how you will type and run a java program
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 14 OBJECT ORIENTED PROGRAMMING
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects.
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as a single unit. In
encapsulation the variables of a class will be hidden from other classes, and
can be accessed only through the methods of their current class, therefore it
is also known as data hiding.
Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most
common use of polymorphism in OOP occurs when a parent class reference
is used to refer to a child class object.
Data abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 15 OBJECT ORIENTED PROGRAMMING
The design method used in procedural programming is called Top Down Design.
This is where you start with a problem (procedure) and then systematically break
the problem down into sub problems (sub procedures). This is called functional
decomposition, which continues until a sub problem is straightforward enough to be
solved by the corresponding sub procedure. The difficulties with this type of
programming, is that software maintenance can be difficult and time consuming.
When changes are made to the main procedure (top), those changes can cascade
to the sub procedures of main, and the sub-sub procedures and so on, where the
change may impact all procedures in the pyramid.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 16 OBJECT ORIENTED PROGRAMMING
EXCERCISES
1. What is OOP?
2. What are the four pillars of OOP?
3. Differentiate procedure from OO programming
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 17 OBJECT ORIENTED PROGRAMMING
3.1.1 Expressions
int cadence = 0;
3.1.2 Statements
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
3.2 Comments
Comments are added in the code to provide information about the code you write
and this makes the code easier to understand. All professionally written codes will
have sufficient comments in it to make the code easily readable and easily
maintainable.
Java support three kinds of comments and they are given below:-
Single line comment:
Single line comment begins with // and ends at the end of the line.
Multi line comment
Multi line comment begins with /* and ends with */ that spans multiple lines.
Document comment
Documentation style comments begin with /** and terminate with */ and
that spans multiple lines. (Note that documentation comment starts with /**
whereas multi line comment start with /* )
Javadoc program uses this documentation comments to generate HTML
pages of API documentation from Java source code files.
Data
Data is defined as the quantities, characters, or symbols on which operations are
performed by a computer, which may be stored and transmitted in the form of
electrical signals and recorded on magnetic, optical, or mechanical recording media.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 18 OBJECT ORIENTED PROGRAMMING
byte:
Byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an int.
Example: byte a = 100 , byte b = -50
short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short
is 2 times smaller than an int
Default value is 0.
Example: short s = 10000, short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there
is a concern about memory.
The default value is 0.
Example: int a = 100000, int b = -200000
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 19 OBJECT ORIENTED PROGRAMMING
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point
numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f
double:
Double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values,
generally the default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
Boolean:
Boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true
char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example: char letterA ='A'
Java Literals:
A literal is a source code representation of a fixed value. They are represented
directly in the code without any computation.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 20 OBJECT ORIENTED PROGRAMMING
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base
16) or octal(base 8) number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using
these number systems for literals. For example:
String literals in Java are specified like they are in most other languages by
enclosing a sequence of characters between a pair of double quotes. Examples of
string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals as
well. They are:
3.4 Operators
An operator is a symbol that represents a specific action. For example, a plus sign
(+) is an operator that represents addition. The basic mathematic operators are +
addition, - subtraction,* multiplication,/ division
They are used to manipulate primitive data types. Java operators can be classified
as unary, binary, or ternary—meaning taking one, two, or three arguments,
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 21 OBJECT ORIENTED PROGRAMMING
respectively. A unary operator may appear before (prefix) its argument or after
(postfix) its argument. A binary or ternary operator appears between its
arguments.
Assignment Operators =
Arithmetic Operators - + * / % ++ --
Java has eight different operator types: assignment, arithmetic, relational, logical,
bitwise, compound assignment, conditional, and type.
ASSIGNMENT OPERATORS
The java assignment operator statement has the following syntax:
<variable> = <expression>
Eg x = 10;
ARITHMETIC OPERATORS
Java provides eight Arithmetic operators. They are for addition, subtraction,
multiplication, division, modulo (or remainder), increment (or add 1), decrement
(or subtract 1), and negation.
The binary operator + is overloaded in the sense that the operation performed is
determined by the type of the operands. When one of the operands is a String
object, the other operand is implicitly converted to its string representation and
string concatenation is performed.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 22 OBJECT ORIENTED PROGRAMMING
Eg x= y + z;
RELATIONAL OPERATORS
Relational operators in Java are used to compare 2 or more objects. Java provides
six relational operators:
greater than (>), less than (<), greater than or equal (>=), less than or equal
(<=), equal (==), and not equal (!=).
All relational operators are binary operators, and their operands are numeric
expressions.
LOGICAL OPERATORS
Logical operators return a true or false value based on the state of the Variables.
There are six logical, or boolean, operators. They are AND, conditional AND, OR,
conditional OR, exclusive OR, and NOT. Each argument to a logical operator must
be a boolean data type, and the result is always a boolean data type.
BITWISE OPERATORS
Java provides Bit wise operators to manipulate the contents of variables at the bit
level.
These variables must be of numeric data type ( char, short, int, or long). Java
provides seven bitwise operators. They are AND, OR, Exclusive-OR, Complement,
Left-shift, Signed Right-shift, and Unsigned Right-shift.
COMPOUND OPERATORS
Compound operators perform shortcuts in common programming operations. Java
has eleven compound assignment operators.
Syntax:
= argument2.
The above statement is the same as, argument1 = argument1 operator argument2.
CONDITIONAL OPERATORS
The Conditional operator is the only ternary (operator takes three arguments)
operator in Java. The operator evaluates the first argument and, if true, evaluates
the second argument. If the first argument evaluates to false, then the third
argument is evaluated. The conditional operator is the expression equivalent of the
if-else statement. The conditional expression can be nested and the conditional
operator associates from right to left: (a?b?c?d:e:f:g) evaluates as
(a?(b?(c?d:e):f):g)
Type conversion allows a value to be changed from one primitive data type to
another. Conversion can occur explicitly, as specified in the program, or implicitly,
by Java itself. Java allows both type widening and type narrowing conversions.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 23 OBJECT ORIENTED PROGRAMMING
OPERATOR PRECEDENCE
The order in which operators are applied is known as precedence. Operators with a
higher precedence are applied before operators with a lower precedence. The
operator precedence order of Java is shown below. Operators at the top of the table
are applied before operators lower down in the table. If two operators have the
same precedence, they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default
precedence.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 24 OBJECT ORIENTED PROGRAMMING
int x = 10;
byte y = (byte)x;
3.6 Identifiers
Identifiers are the names of variables, methods, classes, packages and interfaces.
Unlike literals they are not the things themselves, just ways of referring to them.
E.g. num1, name, etc.
Rules for identifiers:
to 9. No spaces or special characters are allowed. The dollar sign and the
underscore are discouraged.
They can be of any length
They are case-sensitive.
You cannot use a java keyword (reserved word) for an identifier
x+y
Every variable has a name, called the variable name, and a data type. The
opposite of a variable is a constant. Constants are values that never change.
Because of their inflexibility, constants are used less often than variables in
programming.
Data-type identifier; or
Data-type identifier-list;
Example: int x;
Int x,y,z;
Variables cab be initialized (set to an initial value) by the programmer at the point
of declaration, using the following syntax:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 26 OBJECT ORIENTED PROGRAMMING
import list
class name
main method
Declaration of constants
Declaration of variables
Program statements
In the Java language, when you execute a class with the Java interpreter, the
runtime system starts by calling the class's main() method. The main() method
then calls all the other methods required to run your application
Exercises
1. If semicolons are needed at the end of each statement, why does the
comment line // My first Java program goes here not end with a semicolon?
2. How important is it to put the right number of blank spaces on a line in a
Java program?
3. I have several word processing programs on my system. Which should I use
to write Java programs?
4. What is a character?
5. I couldn't find any errors in the line where the compiler noted an error. What
can I do?
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 28 OBJECT ORIENTED PROGRAMMING
1. Modifiers such as public, private, and a number of others that you will
encounter later.
2. The class name, with the initial letter capitalized by convention.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 29 OBJECT ORIENTED PROGRAMMING
3. The name of the class's parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
4. A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one
interface.
5. The class body, surrounded by braces, {}.
The class body contains fields, methods, and constructors for the class. A class uses
fields to contain state information and uses methods to implement behavior.
The circle class uses the following line of code to define its field:
private double radius;
The fields of circle is named radius and is of data type double. The public keyword
identifies these fields as public members, accessible by any object that can access
the class.
Types
All variables must have a type. You can use primitive types such as int, float,
boolean, etc. Or you can use reference types, such as strings, arrays, or objects.
Variable Names
All variables, whether they are fields, local variables, or parameters, follow the
same naming rules and conventions. That is; -
The only required elements of a method declaration are the method's return type,
name, a pair of parentheses, (), and a body between braces, {}.
More generally, method declarations have six components, in order:
1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void
if the method does not return a value.
3. The method name—the rules for field names apply to method names as well,
but the convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including
the declaration of local variables, goes here.
Naming a Method
By convention, method names should be a verb in lowercase or a multi-word name
that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-
word names, the first letter of each of the second and following words should be
capitalized. Here are some examples:
run
runFast
getFinalData
You specify a class variable or a class method by using the static keyword in the
member's declaration. A member that is not declared as static is implicitly an
instance member. Class variables are shared by all instances of a class and can be
accessed through the class name as well as an instance reference. Instances of a
class get their own copy of each instance variable, which must be accessed through
an instance reference.
Instance variables and methods that are accessible to code outside of the class that
they are declared in can be referred to by using a qualified name. The qualified
name of an instance variable looks like this:
objectReference.variableName
objectReference.methodName(argumentList)
or:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 31 OBJECT ORIENTED PROGRAMMING
objectReference.methodName()
4.4 Constructors
Constructors that initialize a new instance of a class use the name of the class and
look like methods without a return type.
public Circle(double r)
radius = r;
To create a new circle object called myCircle, a constructor is called by the new
operator:
new Circle(10) creates space in memory for the object and initializes its fields.
Although circle only has one constructor, it could have others, including a no-
argument constructor.
Both constructors could have been declared in circle because they have different
argument lists. As with methods, the Java platform differentiates constructors on
the basis of the number of arguments in the list and their types.
You don't have to provide any constructors for your class, but you must be careful
when doing this. The compiler automatically provides a no-argument, default
constructor for any class without constructors. This default constructor will call the
no-argument constructor of the superclass. In this situation, the compiler will
complain if the superclass doesn't have a no-argument constructor so you must
verify that it does. If your class has no explicit superclass, then it has an implicit
superclass of Object, which does have a no-argument constructor.
You can use a superclass constructor yourself. The MountainBike class at the
beginning of this lesson did just that. This will be discussed later, in the lesson on
interfaces and inheritance.
You can use access modifiers in a constructor's declaration to control which other
classes can call the constructor.
Note: If another class cannot call a Circle constructor, it cannot directly create
Circle objects.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 32 OBJECT ORIENTED PROGRAMMING
You create an object from a class by using the new operator and a constructor. The
new operator returns a reference to the object that was created. You can assign the
reference to a variable or use it directly.
The first (left-most) modifier used lets you control what other classes have access
to a member field. For the moment, consider only public and private. Other access
modifiers will be discussed later.
In the spirit of encapsulation, it is common to make fields private. This means that
they can only be directly accessed from the circle class. We still need access to
these values, however. This can be done indirectly by using public methods that
obtain the field values for us. For example, the getRadius() method.
Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and
it is also easier to locate the related classes.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 33 OBJECT ORIENTED PROGRAMMING
Creating a package:
While creating a package, you should choose a name for the package and include a
package statement along with that name at the top of every source file that
contains the classes, interfaces, enumerations, and annotation types that you want
to include in the package.
The package statement should be the first line in the source file. There can be only
one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and
annotation types will be placed in the current default package.
To compile the Java programs with package statements you have to do use -d
option as shown below.
Then a folder with the given package name is created in the specified destination,
and the compiled class files will be placed in that folder
Example
The type constraints are used to control where the java library classes can be
replaced with routine versions without affecting type perfection of programs.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 34 OBJECT ORIENTED PROGRAMMING
Static analysis is then used to control those applicants for which unused
library functionality and synchronization can be removed safely from the
allocated types.
The profile data is collected about the usage features of the customization
candidates to determine where the allocation of custom library classes is
likely to be cost-effective.
To base on the static analysis results and the profiling information the
custom library classes are automatically generated from a template.
The byte code of the client application is rewritten to use the generated
custom classes. This byte code rewriting is completely see-through to the
programmer.
Exercises
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 35 OBJECT ORIENTED PROGRAMMING
Statement effect
if(x == 0) Prints “zero” if x has the value 0.
System.out.println("zero");
if(x == 0) Prints “zero” if x has the value 0,
System.out.println("zero"); if(x != 0) Prints “non-zero” otherwise.
System.out.println("non-zero");
if(x == 0) Prints “zero” if x has the value 0,
System.out.println("zero"); else prints “non-zero” otherwise
System.out.println("non-zero");
if(x == 0) Prints “zero” if x has the value 0,
System.out.println("zero"); prints “positive” if x is positive,
else prints “negative” if x is negative.
if(x > 0)
System.out.println("positive");
else
System.out.println("negative");
if(x != 0) Prints “positive” if x is positive,
if(x > 0) and non-zero. Prints “ negative”
System.out.println("positive"); if x is negative
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 36 OBJECT ORIENTED PROGRAMMING
else.
System.out.println("negative");
All of the conditional statements which we have seen have just a single statement
as the then-statement or the else-statement. When we need to perform two actions
in some case then we need to bracket them together with left and right braces.
Without these the effect is quite different.
Statement effect
if(x < 0){ Changes the sign of x and prints
System.out.println("negative"); Negative if x is negative.
}
x *= -1;
if(x < 0) Prints negative if x is negative.
System.out.println("negative"); Changes the sign of x whether it was
x *= -1; negative or not.
When for matting computer programs we will normally use blank-space indentation
to convey hints to the reader about statement structure. However, as far as the
compiler for the Java language is concerned, one blank space is as good as ten so
the different effect of the two statements is achieved by the use of the left and
right braces, and not by the blank-space indentation at the start of the line.
Statement Effect
switch(x){ Prints “zero” if x has the value 0,
case0: System.out.println ("zero");
break;
default: System.out.println ("non-
zero"); prints “non-zero” otherwise.
break; }
Without the break statements the flow of control falls through the statement so that
the first matching statement is executed and then all of the statements which follow
it. Since this is rarely useful, a switch statement almost always has a break
statement at the end of each case.
In the example shown above we have only one case treated specially in the switch.
We could have more. The if-then-else statement allows to choose between two
possible sub-statements but the switch allows us to choose between any number of
them. The other cases also appear in the body of the switch statement with the
default case coming at the end.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 37 OBJECT ORIENTED PROGRAMMING
If the value of exp1 is true, then the value of Exp2 will be the value of the
whole expression.
If the value of exp1 is false, then Exp3 is evaluated and its value becomes
the value of the entire expression.
The ?: is called a ternary operator because it requires three operands and can be
used to replace if-else statements, which have the following form:
if(condition){
var = X;
}else{
var = Y;
}
For example, consider the following code:
if(y < 10){
var = 30;
}else{
var = 40;
}
Above code can be rewritten like this:
var = (y < 10) ? 30 : 40;
Here, var is assigned the value of 30 if y is less than 10 and 40 if it is not.
5.6. Iteration
There may be a situation when you need to execute a block of code several number
of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
programming languages:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 38 OBJECT ORIENTED PROGRAMMING
Java programming language provides the following types of loop to handle looping
requirements.
Syntax:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the
loop will be executed. This will continue as long as the expression result is true.
When the condition becomes false, program control passes to the line immediately
following the loop
Here, key point of the while loop is that the loop might not ever run. When the
expression is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Example:
while( x < 20 ) {
System.out.print("value of x : " + x );
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 39 OBJECT ORIENTED PROGRAMMING
x++;
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Syntax:
The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. and this step ends with a
semi colon (;)
Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop will not be executed and control
jumps to the next statement past the for loop.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 40 OBJECT ORIENTED PROGRAMMING
After the body of the for loop gets executed, the control jumps back up to
the update statement. This statement allows you to update any loop control
variables. This statement can be left blank with a semicolon at the end.
The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update step, then
Boolean expression). After the Boolean expression is false, the for loop
terminates.
Example:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
Expression: This evaluates to the array you need to loop through. The
expression can be an array variable or method call that returns an array.
Example:
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
Syntax:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.
If the Boolean expression is true, the control jumps back up to do statement, and
the statements in the loop execute again. This process repeats until the Boolean
expression is false.
Example:
public class Test {
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 42 OBJECT ORIENTED PROGRAMMING
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 43 OBJECT ORIENTED PROGRAMMING
5.11. Arrays
Arrays are a way to store a list of items. Arrays can contain any type of value (base
types or objects), but you can’t store different types in a single array.To create an
array in Java, you use three steps:
Declare a variable to hold the array.
Create a new array object and assign it to the array variable.
Store things in that array.
Declaring Array Variables
Array variables indicate the type of object the array will hold (just as they do for
any variable) and the name of the array, followed by empty brackets ([])
int temps[]; OR
int[] temps;
Creating Array Objects
The second step is to create an array object and assign it to that variable. There
are two ways to do this:
• The first way is to use the new operator to create a new instance of an array:
String[] names = new String[10];
When you create an array object using new, all its elements are initialized for
you (0 for numeric arrays, false for boolean, ‘\0’ for character arrays, and
null for everything else)
• You can also create and initialize an array at the same time. Instead of using
new to create the new array object, enclose the elements of the array inside
braces, separated by commas:
String[] chiles = { “jalapeno”, “anaheim”, “serrano,” “habanero,” “thai” }
An array the size of the number of elements you’ve included will be automatically
created for you.
Accessing Array Elements
To get at a value stored within an array, use the array subscript expression:
myArray[subscript];
The myArray part of this expression is a variable holding an array object. The
subscript is the slot within the array to access. Array subscripts start with 0.
You can test for the length of the array in your programs using the length instance
variable - it’s available for all array objects, regardless of type
Changing Array Elements
To assign a value to a particular array slot, merely put an assignment statement
after the array access expression:
myarray[1] = 15;
Multidimensional Arrays
Java does not support multidimensional arrays. However, you can declare and
create an array of arrays, and access them as you would C-style multidimensional
arrays:
int coords[][] = new int[12][12];
coords[0][0] = 1;
coords[0][1] = 2;
the following example demonstrate arrays of arrays implementation
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 44 OBJECT ORIENTED PROGRAMMING
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}
Exercises
1. Write a program that computes the product of two square matrices of
boolean values
2. Write a code fragment that prints the contents of a two-dimensional boolean
array, using * to represent true and a space to represent false. Include row
and column numbers.
3. What pitfalls should I watch out for when using arrays?
4. Factorials are used frequently in probability problems. The factorial of a
positive integer n (written n! and pronounced “n factorial”) is equal to the
product of the positive integers from 1 to n. Write an application that
calculates the factorials of 1 through 20. Use type long. Display the results in
tabular format. What difficulty might prevent you from calculating the
factorial of 100?
5. If a loop never ends, how does the program stop running?
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 45 OBJECT ORIENTED PROGRAMMING
Chapter 6. Polymorphism
6.1 What is polymorphism in programming?
Polymorphism is the capability of a method to do different things based on the
object that it is acting upon. In other words, polymorphism allows you define one
interface and have multiple implementations. I know it sounds confusing. Don’t
worry we will discuss this in detail.
It is a feature that allows one interface to be used for a general class
of actions.
An operation may exhibit different behavior in different instances.
The behavior depends on the types of data used in the operation.
It plays an important role in allowing objects having different internal
structures to share the same external interface.
Polymorphism is extensively used in implementing inheritance.
Example:
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 46 OBJECT ORIENTED PROGRAMMING
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times: first having 1 int parameter,
second one has 2 int parameters and third one is having double arg. The methods
are invoked or called with the same type and number of parameters used.
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Example:
}
}
public class DerivedClass extends BaseClass
{
public void methodToOverride() //Derived Class method
{
System.out.println ("I'm the method of DerivedClass");
}
}
Output:
Exercises
1. What is polymorphism?
2. Name types of polymorphism in java
3. What is method overloading
4. Differentiate method overloading from method overriding
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 49 OBJECT ORIENTED PROGRAMMING
Chapter 7. Abstraction
7.1 Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only important things to the user and hides the internal
details for example sending sms, you just type the text and send the message. You
don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve abstraction: -
There are two ways to achieve abstraction in java
1. Abstract class
2. Interface
abstract class A {}
abstract method
A child class that inherits an abstract method must override it. If they do not, they
must be abstract and any of their children must override it.
Rule: If there is any abstract method in a class, that class must be abstract.
Rule: If you are extending any abstract class that has abstract method, you must
either provide the implementation of the method or make this class abstract.
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and
methods are public and abstract.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 51 OBJECT ORIENTED PROGRAMMING
In this example, Vigo interface have only one method, its implementation is
provided in the Test class.
interface Vigo
{
void printme();
}
class Tutor implements Vigo
{
public void printme()
{
System.out.println("I am a Turor");
}
}
public class Test
{
public static void main(String args[])
{
Tutor t = new Tutor();
t.printme();
}
}
In the following example Tutor class inherits printme() and status() behaviours
from Vigo and Vertigo classes respectively.
interface Vigo
{
void printme();
}
interface Vertigo
{
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 52 OBJECT ORIENTED PROGRAMMING
void status();
}
class Tutor implements Vigo,Vertigo
{
public void printme()
{
System.out.println("I am a Turor");
}
public void status()
{
System.out.println("I am alive");
}
}
public class Test
{
public static void main(String args[])
{
Tutor t = new Tutor();
t.printme();
t.status();
}
}
Interface inheritance
A class implements interface but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
Exercises
1. What is abstraction?
a. Interface
b. Abstract class
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 53 OBJECT ORIENTED PROGRAMMING
Chapter 8. Encapsulation
8.1 Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single
unit, for example capsule i.e. mixed of several medicines.
Encapsulation is the technique of making the fields in a class private and providing
access to the fields via public methods. If a field is declared private, it cannot be
accessed by anyone outside the class, thereby hiding the fields within the class. For
this reason, encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and
data being randomly accessed by other code defined outside the class. Access to
the data and code is tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code
without breaking the code of others who use our code. With this feature
Encapsulation gives maintainability, flexibility and extensibility to our code.
The Java Bean class is the example of fully encapsulated class.
Let's see the simple example of encapsulation that has only one field with its setter
and getter methods.
//save as Student.java
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
}
}
//save as Test.java
class Test{
public static void main(String[] args){
Student s=new Student();
s.setname("vijay");
System.out.println(s.getName());
}
}
The public methods are the access points to this class' fields from the outside java
world. Normally, these methods are referred as getters and setters. Therefore any
class that wants to access the variables should access them through these getters
and setters.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 54 OBJECT ORIENTED PROGRAMMING
Exercises
1. What is encapsulation
2. What are the benefits of encapsulation
3. Give an example of encapsulation
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 55 OBJECT ORIENTED PROGRAMMING
Chapter 9: Inheritance
9.1. Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of parent class, and you can add new methods and fields also.
The extends keyword indicates that you are making a new class that derives from
an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new
class is called a subclass.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 56 OBJECT ORIENTED PROGRAMMING
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee. It
means that Programmer is a type of Employee.
class Employee{
float salary=40000;
int bonus=10000;
In the above example, Programmer object can access the field of own class as well
as of Employee class i.e. code reusability.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 57 OBJECT ORIENTED PROGRAMMING
When a class extends multiple classes i.e. known as multiple inheritance. For
Example:
Consider a scenario where A, B and C are three classes. The C class inherits A and
B classes. If A and B classes have same method and you call it from child class
object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Exercises
1. Can a class have more than one superclass so that it inherits additional
methods and behavior?
2. What is inheritance
3. Can a child always inherit properties from its parent?
4. Explain different types of inheritance in java.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 58 OBJECT ORIENTED PROGRAMMING
Once runtime receives the exception object, it tries to find the handler for the
exception. Exception Handler is the block of code that can process the exception
object. The logic to find the exception handler is simple – starting the search in the
method where error occurred, if no appropriate handler found, then move to the
caller method and so on. So if methods call stack is A->B->C and exception is
raised in method C, then the search for appropriate handler will move from C->B-
>A. If appropriate exception handler is found, exception object is passed to the
handler to process it. The handler is said to be “catching the exception”. If there
are no appropriate exception handler found, then program terminates printing
information about the exception.
Note that Java Exception handling is a framework that is used to handle runtime
errors only, compile time errors are not handled by exception handling framework.
Specific keywords in java program are used to create an exception handler block;
The keywords are shown in the following section.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 59 OBJECT ORIENTED PROGRAMMING
Because the exception is handled within the class, the Java interpreter does not
display an error message when something like 6x is used as a command-line
argument.
You can often deal with problems related to user input and other unexpected data
by using try-catch blocks.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 60 OBJECT ORIENTED PROGRAMMING
1. Errors: Errors are exceptional scenarios that are out of scope of application
and it’s not possible to anticipate and recover from them, for example
hardware failure, JVM crash or out of memory error. That’s why we have a
separate hierarchy of errors and we should not try to handle these situations.
Some of the common Errors are OutOfMemoryError and StackOverflowError.
2. Checked Exceptions: Checked Exceptions are exceptional scenarios that we
can anticipate in a program and try to recover from it, for example
FileNotFoundException. We should catch this exception and provide useful
message to user and log it properly for debugging purpose. Exception is the
parent class of all Checked Exceptions and if we are throwing a checked
exception, we must catch it in the same method or we have to propagate it
to the caller using throws keyword.
3. Runtime Exception: Runtime Exceptions are cause by bad programming,
for example trying to retrieve an element from the Array. We should check
the length of array first before trying to retrieve the element otherwise it
might throw ArrayIndexOutOfBoundException at runtime. RuntimeException
is the parent class of all runtime exceptions. If we are throwing any runtime
exception in a method, it’s not required to specify them in the method
signature throws clause. Runtime exceptions can be avoided with better
programming.
Throwable
Error Exception
IOException RuntimeException
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 61 OBJECT ORIENTED PROGRAMMING
There are some constraints such as the exception object is final and we can’t
modify it inside the catch block.
Most of the time, we use finally block just to close the resources and sometimes we
forget to close them and get runtime exceptions when the resources are exhausted.
These exceptions are hard to debug and we might need to look into each place
where we are using that type of resource to make sure we are closing it. So java 7
one of the improvement was try-with-resources where we can create a resource in
the try statement itself and use it inside the try-catch block. When the execution
comes out of try-catch block, runtime environment automatically close these
resources. Sample of try-catch block with this improvement is:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 62 OBJECT ORIENTED PROGRAMMING
} catch (Exception e) {
e.printStackTrace();
MyException.java
Notice that we can have a separate method to process different types of error
codes that we get from different methods, some of them gets consumed because
we might not want to notify user for that or some of them we will throw back to
notify user for the problem.
Catch Late – Since java enforces to either handle the checked exception or to
declare it in method signature, sometimes developers tend to catch the
exception and log the error. But this practice is harmful because the caller
program doesn’t get any notification for the exception. We should catch
exception only when we can handle it appropriately. For example, in above
method I am throwing exception back to the caller method to handle it. The
same method could be used by other applications that might want to process
exception in a different manner. While implementing any feature, we should
always throw exceptions back to the caller and let them decide how to handle
it.
Closing Resources – Since exceptions halt the processing of program, we
should close all the resources in finally block or use Java 7 try-with-resources
enhancement to let java runtime close it for you.
Logging Exceptions – We should always log exception messages and while
throwing exception provide clear message so that caller will know easily why
the exception occurred. We should always avoid empty catch block that just
consumes the exception and doesn’t provide any meaningful details of
exception for debugging.
Single catch block for multiple exceptions – Most of the times we log
exception details and provide message to the user, in this case we should
use java 7 feature for handling multiple exceptions in a single catch block.
This approach will reduce our code size and it will look cleaner too.
Using Custom Exceptions – It’s always better to define exception handling
strategy at the design time and rather than throwing and catching multiple
exceptions, we can create a custom exception with error code and caller
program can handle these error codes. It’s also a good idea to create a utility
method to process different error codes and use it.
Naming Conventions and Packaging – When you create your custom
exception make sure it ends with Exception so that it will be clear from name
itself that it’s an exception. Also make sure to package them like it’s done in
JDK, for example IOException is the base exception for all IO operations.
Use Exceptions Judiciously – Exceptions are costly and sometimes it’s not
required to throw exception at all and we can return a boolean variable to the
caller program to indicate whether an operation was successful or not. This is
helpful where the operation is optional and you don’t want your program to
get stuck because it fails.
Document the Exceptions Thrown – Use javadoc @throws to clearly specify the
exceptions thrown by the method, it’s very helpful
Exercises
1. Why some errors are called exceptions?
2. What is the key reason for using finally blocks?
3. What happens to a local reference in a try block when that block throws an
Exception?
4. Give a key advantage of using catch (Exception exceptionName).
5. What happens if no catch handler matches the type of a thrown object?
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 65 OBJECT ORIENTED PROGRAMMING
11.2 Stream
A stream can be defined as a sequence of data. There are two kinds of Streams
InPutStream: The InputStream is used to read data from a source.
OutPutStream: the OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but
this manual covers very basic functionality related to streams and I/O. We would
see most commonly used example one by one:
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though
there are many classes related to byte streams but the most frequently used
classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an input file
into an output file:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close(); }
}
}
}
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 66 OBJECT ORIENTED PROGRAMMING
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as
Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most
frequently used classes are , FileReader and FileWriter.. Though internally
FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
major difference is that FileReader reads two bytes at a time and FileWriter writes
two bytes at a time.
We can re-write above example which makes use of these two classes to copy an
input file (having unicode characters) into an output file:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put above
code in CopyFile.java file and do the following:
javac CopyFile.java
java CopyFile
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 67 OBJECT ORIENTED PROGRAMMING
Standard Streams
All the programming languages provide support for standard I/O where user's
program can take input from a keyboard and then produce output on the computer
screen. If you are aware if C or C++ programming languages, then you must be
aware of three standard devices STDIN, STDOUT and STDERR. Similar way Java
provides following three standard streams
Standard Input: This is used to feed the data to user's program and usually
a keyboard is used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's
program and usually a computer screen is used to standard output stream
and represented as System.out.
Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used to standard error stream and
represented as System.err.
Following is a simple program which creates InputStreamReader to read standard
input stream until the user types a "q":
import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep above code in ReadConsole.java file and try to compile and execute it as
below. This program continues reading and outputting same character until we
press 'q':
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 68 OBJECT ORIENTED PROGRAMMING
The two important streams are FileInputStream and FileOutputStream, which would
be discussed in this manual:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using
the keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object
to read the file.
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read
the file. First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods
which can be used to read to stream or to do other operations on the stream.
FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object
to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write
the file. First, we create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods,
which can be used to write to stream or to do other operations on the stream.
Example:
Following is the example to demonstrate InputStream and OutputStream:
import java.io.*;
public class fileStreamTest{
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 70 OBJECT ORIENTED PROGRAMMING
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++){
System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given numbers in binary
format. Same would be output on the stdout screen.
Creating Directories:
There are two useful File utility methods, which can be used to create directories:
The mkdir( ) method creates a directory, returning true on success and false
on failure. Failure indicates that the path specified in the File object already
exists, or that the directory cannot be created because the entire path does
not exist yet.
The mkdirs() method creates both a directory and all the parents of the
directory.
Following example creates "/tmp/user/java/bin" directory:
import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Compile and execute above code to create "/tmp/user/java/bin".
Note: Java automatically takes care of path separators on UNIX and Windows as
per conventions. If you use a forward slash (/) on a Windows version of Java, the
path will still resolve correctly.
Listing Directories:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 71 OBJECT ORIENTED PROGRAMMING
You can use list( ) method provided by File object to list down all the files and
directories available in a directory as follows:
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try{
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file.list();
// for each name in the path array
for(String path:paths)
{
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
This would produce following result based on the directories and files available in
your /tmp directory:
test1.txt
test2.txt
ReadDir.java
ReadDir.class
When we wish to pass the String array, we simply include the elements of the array
as simple Strings beside the class name. Enclosing the Strings in quotes is optional.
Consecutive Strings are separated with a space. For example, if we wish to pass a
three element String array containing the values "1", "2", and "3" any of the
following lines is entered on the command prompt.
java Add 1 2 3
java Add "1" "2" "3"
Since these arguments are passed through the command line, they are known as
command line arguments. The String arguments passed are stored in the array
specified in the main() declaration. args[] is now a three element String array.
These elements are accessed in the same way as the elements of a normal array.
The following is the complete Add program which is capable of adding any number
of integers passed as command line arguments.
Exercises
1. What is a stream
2. Write a program that will accept inputs from the user and store them to a file
3. Write a program that will copy contents of one file to another file
4. Write a program that will accept two numbers typed by a user and compare
them
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 74 OBJECT ORIENTED PROGRAMMING
To create and display an interface, you create objects, set their variables, and call
their methods. The techniques are the same as those you used during the previous
topics as you were introduced to object-oriented programming.
When you are putting a graphical user interface together, you work with two kinds
of objects: components and containers. A component is an individual element in a
user interface, such as a button or slider. A container is a component that can be
used to hold other components.
The first step in creating an interface is to create a container that can hold
components. In an application, this container is often a frame or a window.
These containers are created using Swing's JWindow and JFrame classes. To make
the Swing package of classes available in a Java program, use the following
statement:
import javax.swing.*;
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 75 OBJECT ORIENTED PROGRAMMING
One way to make use of a frame in a Java application is to make the application a
subclass of JFrame. Your program will inherit the behavior it needs to function as a
frame. The following statements create a subclass of JFrame:
import javax.swing.*;
public class MainFrame extends JFrame {
public MainFrame() {
// set up the frame
}
}
This class creates a frame, but doesn't set it up completely. In the frame's
constructor method, you must do several actions when creating a frame:
You also must make the frame visible, unless for some reason it should not be
displayed when the application begins running.
All of these things can be handled in the frame's constructor method. The first thing
the method must contain is a call to one of the constructor methods of JFrame,
using the super statement. Here's an example:
super();
The preceding statement calls the JFrame constructor with no arguments. You also
can call it with the title of your frame as an argument:
super("Main Frame");
This sets the title of the frame, which appears in the title bar along the top edge, to
the specified string. In this example, the text greeting "Main Frame" will appear.
If you don't set up a title in this way, you can call the frame's setTitle() method
with a String as an argument:
setTitle("Main Frame");
The size of the frame can be established by calling its setSize() method with two
arguments: the width and height. The following statement sets up a frame that is
350 pixels wide and 125 pixels tall:
setSize(350, 125);
Another way to set the size of a frame is to fill it with components and then call the
frame's pack() method with no arguments, as in this example:
pack();
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 76 OBJECT ORIENTED PROGRAMMING
The pack() method sets the frame up based on the preferred size of each
component inside the frame. Every interface component has a preferred size,
though this is sometimes disregarded, depending on how components have been
arranged within a container. You don't need to explicitly set the size of a frame
before calling pack()—the method sets it to an adequate size before the frame is
displayed.
Every frame is displayed with a button along the title bar that can be used to close
the frame. On a Windows system, this button appears as an X in the upper-right
corner of the frame. To define what happens when this button is clicked, call the
frame's setDefaultCloseOperation() method with one of four JFrame class variables
as an argument:
The last thing that's required is to make the frame visible: call its setVisible()
method with true as an argument:
setVisible(true);
This opens the frame at the defined width and height. You also can call it with false
to stop displaying a frame.
The following program contains the source code described in this section. Enter
these statements and save the file as SaluteFrame.java.
import javax.swing.*;
public class SaluteFrame extends JFrame {
public SalutonFrame() {
super("Hello World !");
setSize(350, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] arguments) {
SaluteFrame sal = new SaluteFrame();
}
}
The program contain a main() method, which turns this frame class into an
application that can be run at the command line. After you compiling this into a
class, run the application with the following command:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 77 OBJECT ORIENTED PROGRAMMING
java SaluteFrame
The only thing that SaluteFrame displays is a greeting "Hello World!” The frame is
an empty window, because it doesn't contain any other components yet.
Buttons
One simple component you can add to a container is a JButton object. JButton, like
the other components you'll be working with during this hour, is part of the
java.awt.swing package. A JButton object is a clickable button with a label that
describes what clicking the button will do. This label can be text, graphics, or both.
The following statement creates a JButton called okButton and gives it the text
label OK:
JButton okButton = new JButton("OK");
add(okButton);
When you add components to a container, you do not specify the place in the
container where the component should be displayed. The arrangement of
components is decided by an object called a layout manager. The simplest of these
managers is the FlowLayout class, which is part of the java.awt package.
To make a container use a specific layout manager, you must first create an object
of that layout manager's class. A FlowLayout object is created with a statement,
such as the following:
Once a layout manager has been created, the container's setLayout() method is
called to associate the manager with the container. The only argument to this
method should be the layout manager object, as in the following example:
pane.setLayout(fff);
This statement designates the fff object as the layout manager for the pane
container.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 78 OBJECT ORIENTED PROGRAMMING
setSize(225, 80);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
FlowLayout flo = new FlowLayout();
setLayout(flo);
JButton play = new JButton("Play");
JButton stop = new JButton("Stop");
JButton pause = new JButton("Pause");
add(play);
add(stop);
add(pause);
setVisible(true);
}
public static void main(String[] arguments) {
Playback pb = new Playback();
}
A JLabel component displays information that cannot be modified by the user. This
information can be text, a graphic, or both. These components are often used to
label other components in an interface, hence the name. They often are used to
identify text fields.
A JTextField component is an area where a user can enter a single line of text. You
can set up the width of the box when you create the text field.
The following statements create a JLabel component and JTextField object and add
them to a container:
setLayout(flo);
add(pageLabel);
add(pageAddress);
The pageLabel label is set up with the text Web page address: and a JLabel.RIGHT
argument. This last value indicates that the label should appear flush right.
JLabel.LEFT aligns the label text flush left, and JLabel.CENTER centers it. The
argument used with JTextField indicates that the text field should be approximately
20 characters wide. You also can specify default text that will appear in the text
field with a statement such as the following:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 79 OBJECT ORIENTED PROGRAMMING
This statement would create a JTextField object that is 20 characters wide and has
the text US in the field.
The text contained within the object can be retrieved with the getText() method,
which returns a string:
As you might have guessed, you also can set the text with a corresponding
method:
This sets the text to the official name of Libya, which is the longest in the world,
edging out the second-place finisher: the United Kingdom of Great Britain and
Northern Ireland.
Check Boxes
A JCheckBox component is a box next to a line of text that can be checked or
unchecked by the user. The following statements create a JCheckBox object and
add it to a container:
setLayout(flo);
add(jumboSize);
meals.add(frogLegs);
meals.add(fishTacos);
meals.add(emuNuggets);
setLayout(flo);
add(jumboSize);
add(frogLegs);
add(fishTacos);
add(emuNuggets);
This creates three check boxes that are all grouped under the ButtonGroup object
called meals. The Frog Leg Grande box is checked initially, but if the user checked
one of the other meal boxes, the check next to Frog Leg Grande would disappear
automatically.
Combo Boxes
To create a JComboBox object, you have to add each of the choices after creating
the object, as in the following example:
profession.addItem("Butcher");
profession.addItem("Baker");
profession.addItem("Candlestick maker");
profession.addItem("Fletcher");
profession.addItem("Fighter");
profession.addItem("Technical writer");
setLayout(flo);
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 81 OBJECT ORIENTED PROGRAMMING
add(profession);
This example creates a single JComboBox component that provides six choices from
which the user can select.
profession.setEditable(true);
Text Areas
A JTextArea component is a text field that enables the user to enter more than one
line of text. You can specify the width and height of the component. For example,
the following statements create a JTextArea component with an approximate width
of 40 characters and a height of 8 lines, and then add the component to a
container:
setLayout(flo);
add(comments);
Panels
The other components you'll learn to create are panels, which are created in Swing
using the JPanel class. JPanel objects are the simplest kind of container you can use
in a Swing interface. The purpose of JPanel objects is to subdivide a display area
into different groups of components. When the display is divided into sections, you
can use different rules for how each section is organized.
You can create a JPanel object and add it to a container with the following
statements:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 82 OBJECT ORIENTED PROGRAMMING
setLayout(flo);
add(topRow);
Panels are often used when arranging the components in an interface. Unlike other
containers, panels do not have a content pane. Instead, you can add components
by calling the panel's add() method directly. You also can assign a layout manager
directly to the panel by calling its setLayout() method.
Panels also can be used when you need an area in an interface to draw something,
such as an image from a graphics file. Another convenient use of JPanel is to create
your own components that can be added to other classes. This is demonstrated in
this hour's workshop.
There are several layout managers you can use to affect how components are
shown. The default manager for panels is the FlowLayout class in the java.awt
package
Under FlowLayout, components are dropped onto an area in the same way words
are organized on a printed page in English—from left to right, then on to the next
line when there's no more space.
setLayout(topLayout);
You also can set up a layout manager to work within a specific container, such as a
JPanel object. You can do this by using the setLayout() method of that container
object. The following statements create a JPanel object called inputArea and set it
up to use FlowLayout as its layout manager:
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 83 OBJECT ORIENTED PROGRAMMING
inputArea.setLayout(inputLayout);
The Crisis application has a graphical user interface with five buttons. Load your
word processor and open up a new file called Crisis.java. Enter the following code
and save the file when you're done.
After compiling the Crisis application, you can run it with the following command:
java Crisis
The FlowLayout class uses the dimensions of its container as the only guideline for
how to lay out components. Resize the window of the application to see how
components are instantly rearranged. Make the window twice as wide, and you'll
see all of the JButton components are now shown on the same line. Java programs
often will behave differently when their display area is resized.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 84 OBJECT ORIENTED PROGRAMMING
The following statements create a container and set it to use a grid layout that is
two rows wide and three columns tall:
setLayout(grid);
GridLayout places all components as they are added into a place on a grid.
Components are added from left to right until a row is full and then the leftmost
column of the next grid is filled.
The next layout manager to experiment with is the BorderLayout class, also in
java.awt. The following statements create a container that uses border layout,
placing components at specific locations within the layout:
setLayout(crisisLayout);
add(panicButton, BorderLayout.NORTH);
The BorderLayout manager arranges components into five areas: four denoted by
compass directions and one for the center area. When you add a component under
this layout, the add() method includes a second argument to specify where the
component should be placed. This argument should be one of five class variables of
the BorderLayout class: NORTH, SOUTH, EAST, WEST, and CENTER are used for
this argument.
Like the GridLayout class, BorderLayout devotes all available space to the
components. The component placed in the center is given all the space that isn't
needed for the four border components, so it's usually the largest.
As you are arranging components within a container, you might want to move
components away from the edges of the container. This is accomplished using
Insets, an object that represents the border area of a container.
The Insets class, which is part of the java.awt package, has a constructor method
that takes four arguments: the space to leave at the top, left, bottom, and right on
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 85 OBJECT ORIENTED PROGRAMMING
the container. Each argument is specified using pixels, the same unit of measure
employed when defining the size of a frame.
The around object represents a container border that is 10 pixels inside the top
edge, 6 pixels inside the left, 10 pixels inside the bottom, and 3 pixels inside the
right.
To make use of an Insets object in a container, you must override the container's
getInsets() method. This method has no arguments and returns an Insets object,
as in the following example:
return squeeze;
}
Applets are programs designed to run as part of a World Wide Web page. When a
Java applet is encountered on a page, it is downloaded to the user's computer and
begins running.
Programming applets with Java is much different from creating applications with
Java. Because applets must be downloaded from a page each time they are run,
they're smaller than most applications to reduce download time. Also, because
applets run on the computer of the person using the applet, they have numerous
security restrictions in place to prevent malicious or damaging code from being run.
JApplet is a subclass of Applet, a class in the java.applet package. Being part of this
hierarchy enables the applets you write to use all the behavior and attributes they
need to be run as part of a web page. Before you begin writing any other
statements in your applets, they will be able to interact with a web browser, load
and unload themselves, redraw their window in response to changes in the browser
window, and handle other necessary tasks.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 86 OBJECT ORIENTED PROGRAMMING
In applications, programs begin running with the first statement inside the main()
block statement and end with the last closing bracket (}) that closes out the block.
There is no main() method in a Java applet, so there is no set starting place for the
program. Instead, an applet has a group of standard methods that are handled in
response to specific events as the applet runs.
The following are the events that could prompt one of the applet methods to be
handled:
The program is loaded for the first time, which causes the applet's init() and
start() methods to be called.
Something happens that requires the applet window to be redisplayed, which
causes the applet's paint() method to be called.
The program is stopped by the browser, which calls the applet's stop()
method.
The program restarts after a stop, which calls the start() method.
The program is unloaded as it finishes running, which calls the destroy()
method.
Unlike applications, applet class files must be public because the JApplet class is
also public. (If your applet uses other class files of your own creation, they do not
have to be declared public.)
Your applet's class inherits all the methods that are handled automatically when
needed: init(), paint(), start(), stop(), and destroy(). However, none of these
methods do anything. If you want something to happen in an applet, you have to
override these methods with new versions in your applet program.
The paint() method is used to display text, shapes, and graphics within the applet
window. Whenever something needs to be displayed or redisplayed on the applet
window, the paint() method handles the task. You also can force paint() to be
handled with the following statement in any method of an applet:
repaint();
Aside from the use of repaint(), the main time the paint() method is handled is
when something changes in the browser or the operating system running the
browser. For example, if a user minimizes a web page containing an applet, the
paint() method will be called to redisplay everything that was onscreen in the
applet when the applet is later restored to full size.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 87 OBJECT ORIENTED PROGRAMMING
Unlike the other methods you will be learning about, paint() takes an argument.
The following is an example of a simple paint() method:
The argument sent to the paint() method is a Graphics object. The Graphics class of
objects represents an environment in which something can be displayed, such as an
applet window. As you did with Swing programs, you may cast this to a Graphics2D
object to employ more sophisticated graphical features.
Later, you'll learn about drawString(), a method for the display of text that's
available in both the Graphics and Graphics2D classes.
If you are using a Graphics or Graphics2D object in your applet, you have to add
the following import statements before the class statement at the beginning of the
source file:
import java.awt.Graphics;
import java.awt.Graphics2D;
Note: If you are using several classes that are a part of the java.awt package of
classes, you can use the statement import java.awt.* to make all of these classes
available for use in your program.
Initializing an Applet
The init() method is handled once—and only once—when the applet is run. As a
result, it's an ideal place to set up values for any objects and variables that are
needed for the applet to run successfully. This method is also a good place to set up
fonts, colors, and the screen's background color. Here's an example:
setLayout(flo);
add(run);
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 88 OBJECT ORIENTED PROGRAMMING
If you are going to use a variable in other methods, it should not be created inside
an init() method because it will only exist within the scope of that method.
For example, if you create an integer variable called displayRate inside the init()
method and try to use it in the paint() method, you'll get an error when you
attempt to compile the program. Create any variables you need to use throughout a
class as object variables right after the class statement and before any methods.
At any point when the applet program starts running, the start() method will be
handled. When a program first begins, the init() method is followed by the start()
method. After that, in many instances there will never be a cause for the start()
method to be handled again. In order for start() to be handled a second time or
more, the applet has to stop execution at some point.
The stop() method is called when an applet stops execution. This event can occur
when a user leaves the web page containing the applet and continues to another
page. It also can occur when the stop() method is called directly in a program.
Destroying an Applet
The destroy() method is an opposite of sorts to the init() method. It is handled just
before an applet completely closes down and completes running.
This method is used when something has been changed during a program that
should be restored to its original state. It's another method you'll use more often
with animation than with other types of programs.
One way to place applets on a web page is by using an applet tag and several
attributes. The following is an example of the HTML required to put an applet on a
page:
</applet>
The code attribute identifies the name of the applet's class file. If more than one
class file is being used with an applet, code should refer to the main class file that is
a subclass of the JApplet class.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 89 OBJECT ORIENTED PROGRAMMING
If there is no code attribute, all files associated with the applet should be in the
same folder as the web page that loads the program. codebase should contain a
reference to the folder or subfolder where the applet and any related files can be
found. In the preceding example, codebase indicates that the StripYahtzee applet
can be found in the javadir subfolder.
The height and width attributes designate the exact size of the applet window on
the web page. It must be big enough to handle the things you are displaying in
your applet.
In between the opening <applet> tag and the closing </applet> tag, you can
provide an alternate of some kind for web users whose browser software cannot run
Java programs (less than two percent of all web users run browsers that fall into
this group).
A Sample Applet
This hour's first project is an applet that displays the string "Hello world !”.
Load your word processor and create a new file called SaluteApplet.java. Enter the
following text and save it when you're done.
This applet does not need to use the start(), stop(), or destroy() methods, so they
are not included in the program. Compile the program with the javac compiler tool,
if you're an JDK user, or another tool.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 90 OBJECT ORIENTED PROGRAMMING
Before you can use the drawString() method, you must have a Graphics or
Graphics2D object that represents the applet window.
The paint() method of all applets includes a Graphics object as its only argument,
which can be cast to a Graphics2D object:
When you have created a Graphics2D object like this, you can call its drawString()
method to display text on the area represented by the object.
The text to display, which can be several different strings and variables
strung together with the + operator
The x position (in an (x,y) coordinate system) where the string should be
displayed
The y position where the string should be displayed
The (x,y) coordinate system in an applet is used with several methods. It begins
with the (0,0) point in the upper-left corner of the applet window.
Although you have compiled the SaluteApplet program into a class file, you cannot
run it using a Java interpreter such as java. If you do, you'll get an error message
looking like this:
The error occurs because a Java interpreter runs applications by calling its main()
method. Applets don't include this method. Instead, to run an applet, you need to
create a web page that loads the applet. To create a web page, open up a new file
on your word processor and call it SaluteApplet.html. Enter the following program
and then save the file.
<html>
<head>
<title>Hello World !</title>
</head>
<body bgcolor="#000000" text="#FF00FF">
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 91 OBJECT ORIENTED PROGRAMMING
<center>
This a Java applet:<br>
<applet code="SaluteApplet.class" height=150 width=300>
You need a Java-enabled browser to see this.
</applet>
</body>
</html>
All applets you write can be tested with the appletviewer tool that comes with the
Java Development Kit. You can see the output of the SaluteApplet applet by typing
the following:
appletviewer SaluteApplet.html
One thing to note about appletviewer is that it only runs the applets that are
included in a web page, and does not handle any of the other elements such as text
and images.
Applets can also be loaded by web browsers, if they are equipped with the Java
Plug-in. To attempt this at a command line, type the following command:
SaluteApplet.html
You can also choose File, Open from the browser's menu to find and open the page.
If you can't get this applet to run in Firefox or another web browser, the most likely
reason is that the browser needs the Java Plug-in.
Though popular web browsers began including their own Java interpreters with the
first release of the language in the mid-'90s, these interpreters failed to keep
current.
If you installed the Java Development Kit, you were given a chance to install the
Java Plug-in at the same time.
The Java Plug-in runs Java applets in place of the web browser's Java interpreter.
Once the Java Plug-in is installed, all future Java 2 applets will run automatically if
they specify that the Plug-in should be used to run them.
The plug-in is part of the Java Runtime Environment, which can be downloaded at
no cost from Sun's Java site at the address http://java.com.
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 92 OBJECT ORIENTED PROGRAMMING
Parameters are stored as part of the web page that contains an applet. They are
created using the HTML tag param and its two attributes: name and value. You can
have more than one param tag with an applet, but all of them must be between the
opening <applet> tag and the closing </applet> tag, which also support
parameters). The following is an applet tag that includes several parameters:
</applet>
This example could be used to send news headlines to an applet that scrolls them
across the screen. Because news changes all the time, the only way to create a
program of this kind is with parameters.
You use the name attribute to give the parameter a name. This attribute is
comparable to giving a variable a name. The value attribute gives the named
parameter a value.
int speed;
String speedParam = getParameter("speed");
if (speedParam != null) {
speed = Integer.parseInt(speedParam);
}
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 93 OBJECT ORIENTED PROGRAMMING
This example sets the speed variable by using the speedParam string. You have to
test for null strings before setting speed because the parseInt() method cannot
work with a null string. When you try to retrieve a parameter with getParameter()
that was not included on a web page with the param tag, it will be sent as null,
which is the value of an empty string.
Exercises
1. How are components arranged if I don't assign a layout manager to a container?
2. Create a frame that contains another frame and make both of them visible at the same
time.
3. Create the following GUI. You do not have to provide any functionality.
4.
5. Create the following GUI. You do not have to provide any functionality.
6.
7. Create the following GUI. You do not have to provide any functionality.
8.
9. Write an applet that asks the user to enter two floating-point numbers, obtains the two
numbers from the user and draws their sum, product (multiplication), difference and
quotient (division).
10. Write an applet that asks the user to enter two floating-point numbers, obtains the
numbers from the user and displays the two numbers, then displays the larger number
followed by the words "is larger" as a string on the applet. If the numbers are equal, the
applet should print the message "These numbers are equal."
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 94 OBJECT ORIENTED PROGRAMMING
References
1. https://docs.oracle.com/javase/tutorial/
2. http://www.tutorialspoint.com/java/
3. http://www.javatpoint.com/java-tutorial
4. http://javabeginnerstutorial.com/core-java/
University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645