0% found this document useful (0 votes)
28 views340 pages

OOP Module

The document provides an introduction to Object-Oriented Programming (OOP), highlighting its principles, advantages, and comparison with procedural programming. It explains key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and message communication, emphasizing how OOP models real-world problems more effectively. Additionally, it outlines the benefits of OOP, including improved code reusability, easier maintenance, and enhanced security.

Uploaded by

adanalemu8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views340 pages

OOP Module

The document provides an introduction to Object-Oriented Programming (OOP), highlighting its principles, advantages, and comparison with procedural programming. It explains key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and message communication, emphasizing how OOP models real-world problems more effectively. Additionally, it outlines the benefits of OOP, including improved code reusability, easier maintenance, and enhanced security.

Uploaded by

adanalemu8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 340

Infolink University College

Dilla Campus
Department of Information Technology
Object Oriented in Java
Compiled By: Daniel Dufera (Msc)

Chapter 1
Introduction to Object Oriented Programming

1
What is Object-Oriented Programming?
 Object Oriented Programming (OOP) is a different method
of thinking about programming.
 In procedural programming (structured), we think about
methods and the execution flow through these methods.
 We think separately about data and how the methods
interact with data.
 Object-Oriented Programming, however, forces us to think
in terms of objects and the interaction between objects.
 An object is a self-contained entity that describes not
only certain data, but also the procedures to maintain the
data.

2
Types of Programming Paradigms
 Paradigm means a set of ideas, a concept or hypothesis.
 Therefore; programming paradigm refers to style of
programming.
 In the fundamentals of programming – II (C++), we
have seen procedural programming (function
programming), now let’s compare and contrast the two
programming paradigms.
 These are:
 Procedural Programming Paradigm
 Object Oriented Programming Paradigm

3
Procedural Programming
 The procedural-oriented programs are made up of
functions.
 Functions are less reusable.
 Functions are not well-encapsulated as a self-contained
reusable unit.
 The procedural languages are not suitable of high-level
abstraction for solving real life problems.
 The traditional procedural-languages separate the data
structures (variables) and algorithms (functions).

4
Cont’d…

 The design method in procedural programming is TOP-DOWN approach.


 This is where you start with a problem (procedure) and then systematically
break the problem into sub problems (sub procedures).
 The problem in this style is during maintenance is time consuming.
 Procedural programming is great because it is simple, typically straight
forward ( or can be written such that it is straight forward), and with
proper design, it allows good isolation and containment for variables and
properly scoped with functions and control loops.
5
Object Oriented Paradigm
 The basic unit of OOP is a class, which encapsulates both the
static properties and dynamic operations within a "box",
and specifies the public interface for using these boxes.
 Since classes are well-encapsulated, it is easier to reuse
these classes.
 In other words, OOP combines the data structures and
algorithms of a software entity inside the same box.
 OOP languages permit higher level of abstraction for solving
real-life problems.
 The OOP languages (such as Java, C++ and C#) let you
think in the problem space, and use software objects to
represent and abstract entities of the problem space to solve
the problem.

6
… Cont’d
Scenario
 As an example, suppose you wish to write a computer soccer games
(which I consider as a complex application).
 It is quite difficult to model the game in procedural-oriented
languages. But using OOP languages, you can easily model the
program accordingly to the "real things" appear in the soccer games.
 Player: attributes include name, number, location in the field, and
etc; operations include run, jump, kick-the-ball, and etc.
 Ball:
 Referee:
 Field:
 Audience:
 Weather:

 Most importantly, some of these classes (such as Ball and Audience)


can be reused in another application, e.g., computer basketball game,
with little or no modification.
 The design method in OOP is bottom-up.
7
Overview of OO Principles
 In OO, data is critical – data is not allowed to move freely around a system,
but it is tied closely to the functions that operate on it.
 Data is also protected from unintentional modification by other functions.
 In OO programming, a system or problem is decomposed into entities called
objects.
 An object has data members and functions – in Java, functions are known
as methods.
 Data is protected because the data belonging to an object can only be
accessed and modified by the methods of that object.
 Different objects can 'talk' to each other through their methods – in this way,
Object A cannot directly modify data belonging to Object B – but it can call a
method of Object B that in turn modifies the data.

8
… Cont’d
 To summarize the OO approach:
 Emphasis on data, not procedure
 Programs are made up of objects
 The data structures reflect characteristics of the objects
 Methods that operate on the data of an object are tied
into the data structure
 Data is hidden from external functions
 Objects can communicate with each other through
methods
 New data and methods can be easily added when
necessary
 Takes a bottom-up approach to program design

9
… Cont’d
 The basic concepts of OO are:
 Objects and classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic (late) binding
 Message communication

10
Objects and Classes
 Objects are the basic runtime entities in an OO program.
 An object:
 Is an identifiable thing or individual
 Is of significance to the system
 Has characteristic behaviour (i.e. functionality)
 Has states reflected in the attributes (data) held about the
object
 An object is a self-contained abstraction of an item.
 The item could be a student record, employee record, a
customer record or any screen window.
 An object is an instance of a class.
 It can be uniquely identified by its name and it defines a state
that is represented by the values of its attribute at a particular
point of time.

11
Cont’d…
 A class is user-defined data type that is used to
implement an abstract object, giving us the capability to
use OOP with Java.
 A class includes members.
 A member can be either data known as a data member
or a method, known as a member method.
 A class is the definition of a set of objects which are all
similar in terms of their attributes, associations and
functionality.
 e.g. customer class defines all customer objects.
 A class model is a static view of objects which exist in the
system users' world.

12
Cont’d…

 Objects interact with each other by sending messages between them.


 Message: Customer 'Solomon Tekle', Amend Address (Kebele 17, Hawasa)

 Sending this message is known as invoking or calling the method


'Amend Address'.
 The Customer class definition tells the program what the format of the
Amend Address method is – including the method name, what values
it takes (the parameters) and what it returns (what data-type to
expect for the response).
13
Cont’d…
Members
 A class has one or more variable types, called members.
 The two types of members are data members and member methods.
 Data members: data members of a class are exactly like the
variables in structures.
eg. class car
{
String name;// data member
Color color;
}
 Member methods: are methods/ functions defined within a class that
act on the data members in the class.
eg. class First
{
void new_line()//this is a member method
{
System.out.println();
System.out.println(“Hello”);
}
}
14
Cont’d…
 Methods can be public or private.
 Public methods:
 Are triggered by receipt of a message from another object
 Have a public interface
 Can be defined at the class or object level
 Can be inherited
 Private methods:
 Are triggered by methods within an object
 Are internal to a class
 Can be changed without affecting any methods outside the class
 Private and Public keywords in general determines the visibility of class member.
 Each member function and data member of a class has an attribute known as its
visibility.
 A class member’s visibility determines who can use the member.
 Java has three levels of visibility as follows.
 public
 private
 protected
15
Cont’d…
eg. class Employee
{
private String empName;
private String address;
private String city;
}
 Private members can be accessed only by a member method of that class. They
can’t be accessed by a non-member method; the data is hidden from the
outside world.
eg. class Employee
{
public String empName;
public String address;
public Sring city;
}
 This class contains the class visibility label public.
 By declaring a class member public, we make that member accessible to both
member and non- member methods.

16
Data Abstraction and Encapsulation
 Encapsulation means the wrapping up of data and
methods into a single unit (a class).
 It also means that the data inside a class is hidden from
everything outside the class.
 The data can only be accessed by invoking the methods
of the class.
 Encapsulation separates the interface (which captures the
outside view of a class) of an abstraction and its
implementation.

17
Cont’d…
 A goal of OOP is to differentiate the use of an object from the
implementation of that object. One method to accomplish this is
through the usage of data hiding.
 Data hiding enable us to completely encapsulate an object’s data
members.
 Data hiding prevents the users of an object from directly accessing the
data members of the class.
 The usage of data hiding provides the following benefits.
 Users of the class are isolated from the actual representation of the
data.
 Class programmers can change how data is represented or even,
where data comes from, without affecting applications that use the
class.
 Abstraction refers to the way in which a class represents only the
essential features of the set of objects it models – a class does not
include background or extra details that are not relevant to the system.

18
Inheritance
 Inheritance: defines a relationship among classes, wherein
one class shares the structure or behavior defined in one or
more classes.
 Inheritance represents a hierarchy of abstractions, in which a
subclass inherits from one or more super classes.
 Typically a subclass redefines the existing structure and
behaviors of its super classes.
 Inheritance helps:
 Support design for change
 Support incremental development
 Support design of reusable components
 Inheritance is the way in which objects of one class get the
properties of objects of another class.
 This includes the data and the methods.

19
Cont’d…

 In the above figure , an Employee 'is a' Person and a Retiree 'is a' Person.
 Inheritance is generally used where the relationship between classes can be
described as 'is-a' or 'is-a-kind-of'.
 The full definition of an Employee includes not only the attributes in the Employee
class but also those in the Person class – because it inherits them.
 So an Employee has attributes: Name, Address, Date of Birth, Salary, Department, Rank.
 Employee and Retiree are sub-classes of Person – a sub-class only needs to define
those attributes that are unique to it, that do not apply to the super-class (or parent
class).
 Inheritance provides the idea of reusability – the Person class can be reused without
making changes to it, because another class can be made to inherit from it.
 Java avoids multiple inheritance.
20
Abstract and Concrete Classes
 Consider the previous diagram, if the only types of Person that
exist were Employees and Retirees, then the Person class would
never have any objects.
 In this case, the Person class is abstract – objects of this
class can never be instantiated (created).
 If other types of Person besides Employees and Retirees do
exist, then the Person class is concrete – because objects of
this class can be instantiated.
 An abstract class is convenient to define characteristics that are
shared by two or more classes.
 If the inheritance concept did not exist, the Employee and
Retiree classes would have to explicitly include the attributes
that are common to them – leading to some code duplication.

21
Polymorphism
 The word polymorphism means the ability to take more than
one form.
 In terms of the OOP, this means that a particular operation may
behave differently for different subclasses of the same class.

• At runtime, objects of the class Circle would invoke the Calculate Area method
from the Circle class while objects of the class Square would invoke the
Calculate Area method from the Square sub-class.
• The method will still have the same name in each sub-class, as it is inherited
from the parent class. This is the concept of polymorphism.

22
Dynamic (late) binding
 In the section above, on polymorphism, it was stated that 'at
runtime, objects of the class Circle would invoke the Calculate
Area method from the Circle class while objects of the class
Square would invoke the Calculate Area method from the
Square sub-class'.
 This idea is called dynamic binding or late binding.
 This means that the code associated with a given procedure
call is not known until the time of the call at runtime.
 For the Calculate Area method, the code that is executed
depends on the class of the object for which it is called.

23
Message communication
 An OO program consists of a set of objects that communicate with
each other. Objects can communicate with each other by invoking
methods.
 The process of programming in an OO language involves these steps:
 Create classes – a class defines a set of objects that have
common characteristics
 Create objects from the class definitions
 Establish communications between the objects

 The passing of a message, or invoking of a method, between objects


involves specifying the name of the object, the name of the method
and the information (parameters) to be sent.
 For example: Employee1.promote(' Manager')

 This call is to an object named 'Employee1' – this is an instance of the


Employee class.
 It is invoking the promote() method of the Employee class, passing
'Manager' as the rank to promote Employee to.

24
The Benefits of OO
 OOP enable us to model real-world problem through programs in
more logical manner.
 Because objects are discrete entities, we can debug, modify and
maintain them more easily.
 The concept of inheritance and the data-oriented approach allow a lot
of re-use of existing classes and helps to eliminate redundant code.
 Programs can be built using working modules that already know how
to communicate with each other. This means that programs do not
always have to be written from scratch – thus saving development
time and increasing productivity.
 Encapsulation (hiding of data) helps with the building of more secure
programs.
 The work for a project can be divided by class/object – making it
easier to split work up between a team of developers.
 OO systems can be easily upgraded from small to larger systems.
 Software complexity can be easily managed.

25
Overview of Java Programming and Types of Java Program
A Brief History of Java
 Java was originally developed by Sun Microsystems, a US
company, in 1991.
 Its first name was Oak and it was designed for the
development of software for consumer electronic devices
such as televisions and video recorders.
 As such, one of the main goals for the language was that it
be simple, portable and highly reliable.
 The team based the new language on the existing C and
C++ languages, but they removed features of C and C++
that were seen as being the sources of problems.
 In 1993, the WWW (World Wide Web) was starting to be
used, transforming the previously text-based internet into a
more graphic-rich environment.

26
Cont’d…
 The team developing the Oak language came up with the
idea of creating small programs, called applets, which
would be able to run on any computer that was connected to
the internet.
 In 1995, Oak was renamed Java due to some legal issues –
the name does not have any particular meaning.
 Java was supported by many IT companies, including the big
internet browser developers, Netscape and Microsoft.
 Since then, Java has become one of the main languages
used for internet programming and also as a general-
purpose object-oriented language for stand-alone
applications.

27
What is Java?
 The Java language is object-oriented and programs written in
Java are portable –they can be run on many different
platforms (e.g. Windows, Mac, Linux, Solaris).
 Java is different from other programming languages because a
Java program is compiled and interpreted.
 The Java compiler translates the program into an intermediate
language called Java bytecodes.
 Java bytecodes are platform-independent – this means they can
be run on different operating systems (e.g. Windows and Mac).
 There are different Java interpreters for different platforms.
 The interpreter parses and runs each of the Java bytecode
instructions.

28
Cont’d…
 Compilation only needs to happen one time, whereas interpretation
happens every time the program is executed.
 The source code for a Java program is saved to one or more .java files.
 The compiler generates a .class file for each .java file.
 A .java file can be opened and viewed in any text editor, but a .class
file is bytecode so it cannot be viewed in the same way.
 Every Java interpreter is actually an implementation of something
called the Java VM (Virtual Machine).
 It is called a Virtual Machine because it is like a computer that does not
physically exist – the VM exists only within the memory of the
computer.
 The Java bytecodes are like a set of machine code instructions for the
Java VM.
 A web browser that is Java-enabled is an example of an interpreter.
 The big benefit of the Java way of doing things is that the program
code can be written once, compiled and then run on many different
platforms.
29
Cont’d…

 The Java platform consists of:


 The Java VM
 The Java API (Application Programming Interface).

 The API provides libraries of pre-written, ready-to-use


components that provide standard functionality. A library groups a
number of related classes and interfaces together into what is called a
Java package.
 In order to write Java programs, you need to have the Java SDK
(Software Development Kit) installed on your PC. This includes the API
and the VM, as well as compilers and debuggers for Java.
30
Why Java?
 Java is widely used language because:
 Java is a modern OOP. The designers of Java spent much time
studying the features of classical OOP languages such as Smalltalk
and C++, and made a successful effort to incorporate the good
features and omit the less desirable ones.
 Java is secure, robust and portable. That is, Java language:
 Enables the construction of virus-free, tamper-free system (Secure)
 Supports the developments of programs that do not overwrite memory
(Robust)
 Yields programs that can be run on different types of computers without
change (Portable)
 Java supports the use of advanced programming concepts
such as threads. A thread is a process that can run concurrently
with other processes.
 Java enables users to develop and deploy applications on the:
 Desktop computers…………..Standalone Application (Java SE)
 Internet for servers …………..Servlets, Applets (Java EE)
 Small hand-held devices ……. Mobile Application (Java ME)
 Drawback: Java runs more slowly than most modern
programming languages because it is interpreted.
31
Definitions of Java Applications and java Applets
 Java Applications
 Java applications are the programs executed on the computer
independently.
 Java applications use the main method for execution.
 Java applications run alone but require JRE.
 Java Applets
 It is small program uses another application program for its
execution.
 Applets don’t use the main method.
 Applets can’t run independently require API’s (Ex. Web API)
 A Java applet can only run in a browser.
 An applet is run only when an HTML page requests that it be
executed. In place of a browser, we can use a utility called applet
viewer- is a minimal browser – it ignores all other HTML commands
except the one used to run an applet.

32
Editing, Compiling and Interpreting
 Writing and running a java program involves the following
phases.
 Phase 1: Writing a program
 Writing a java program involves editing a file with an editor. The
following are some Java Integrated Development Environments
(IDEs).
 Jbuilder, NetBeans , Sun ONE Studio, Eclipse, jEdit, Jcreator,
BlueJ, jGRASP, etc.
 Most of these editors can be downloaded for free.
 Any text editor can also be used for creating Java programs.
 Programs written on IDEs or any other editors are known as Source
Code.
 Java source code file names end with .java extension.
 Program is created in an editor and stored on disk in a file ending
with .java.

33
Cont’d …
 Phase 2: Compiling Java Programs into Bytecodes
 Since a computer cannot understand a source program, program called
a compiler is used to translate the source program into a machine
language program called an object program.
 With Java, you write the program once, and compile the source
program into a special type of object code, known as bytecode.
 The bytecode can then run on any computer (platform) with a Java
Virtual Machine.
 A virtual machine is a software application that simulates a computer-
JVM is one of the most widely used virtual machine.
 Java Virtual Machine, which is part of JRE, is software that interprets
Java bytecode. Compiler creates bytecodes and stores them on disk in
a file ending with .class.
Java Bytecode

Java Virtual
Machine

Any
Computer

34
Cont’d …
 Phase 3: Loading a program
 A program must be placed in memory before it can execute: a
process known as loading.
 The class loader takes the .class file (produced during
compilation process) containing the program’s bytecodes and
transform them to primary memory.
 The class loader also loads any of the .class files provided by
java that your program uses.
 The .class files can be loaded from a disk on your system or
over a network.
 Phase 4: Bytecode Verification
 Involves examining bytecodes to ensure that they are valid and
do not violate Java’s security restriction.
 Java enforces strong security, to make sure that Java programs
arriving over the network do not damage your files or your
system (as computer viruses and worms might).
35
Cont’d …
 Phase 5: Execution
 The JVM executes the program’s bytecodes, thus performing the
actions specified by the program.
 .class file is not final machine code yet. It is virtual machine
code.
 JVM need a second compilation to convert virtual machine code
to real machine code. We call it just-in-time compiler (JIT).
This greatly affects the speed of the execution.
 Traditionally, our C/C++ program can finish all the compilation
before execution.
 The generated machine code could run directly on OS or
hardware.
 Interpreter reads bytecodes and translates them into a language
that the computer can understand, possibly storing data values
as the program executes.

36
Cont’d …
A Simple Java Program
 In order to write Java programs, you need to have the Java
SDK (Software Development Kit) installed on your PC.
 This includes the API and the VM, as well as compilers and
debuggers for Java.
 You can write a java program using note pad.
 Then you can compile and run your program using cmd.
 The following code is a java program that prints the string
“Hello, World”.
public class HelloWorld
{
public static void main(String[] args)
{ // Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}

37
Cont’d …
Steps:
 Save your program with the same as your class name and with
.java extension.
 In the above case it will be named as HelloWorld.java.
 Before actually starting compiling and running java source
code, environmental variable path must be set.
 Set path to JDK bin directory: set path= C:\Program Files
(x86)\Java\jdk1.6.0_29\bin
 Set class path to the current directory: set classpath=
C:\Users\BW\Documents\NetBeansProjects
 To Compile:
 Write the command Javac Helloworld.Java as shown below

38
Cont’d …
 Compiling the source could will add a new file ,
HelloWorld.class to the folder containing the source code.
 To Run:
 Write the command Java HelloWorld as shown below

At the end the out ‘Hello World’ will be displayed.

39
Chapter 2

Basics in Java Programming

40
Overview
 All Java code is written inside classes.
 By convention, class names begin with an upper case letter,
and any new words in the name begin with an upper case letter.
public class Circle
{
}
 Inside the class, the code can be divided into fields,
constructors and methods.
 The fields are the data members of the class. The data
members can be class variables or instance variables.
 The constructors are special methods that are called when an
object is instantiated from the class.
 The methods implement the behaviour of the objects
belonging to the class.

41
Java Characteristics
 Java is simple in that it retains much familiar syntax of C++.
 It is strongly typed. This means that every thing must have a
data type.
 Java performs its own memory management avoiding the
memory leaks that plague programs written in languages
like C and C++.
 Java is completely object oriented.
 Java is multi-threaded, allowing a program to do more than
one thing at a time.
 Network-Savvy: extensive library of routines for coping
with TCP/IP protocols like HTTP and FTP.
 Secure and Robust: Java is intended for writing programs
that are reliable and secure in a variety of ways.
 Portable and architecture neutral.

42
Structure of a Java Program
 Java is a pure object oriented language, and hence
everything is written within a class block.

 The structure of a java program is:

 Documentation

 Package Statement

 Import Statements

 Interface Statements

 Class Definition

 Main Class Definition …


43
Comment Statements
 Documentation is the body of explanatory remarks and comments
pertaining to a program.
 Comments help programmers to communicate and understand the
program.
 They are not programming statements and hence are ignored by the
compiler.
 In Java programming language three different types of commenting
styles are supported. These are:
 Line Comment (//)
 Here comments are preceded by two forward slashes (//). When the
compiler sees //, it ignores all the text after // on the same line.
 Block Comment (/*… */)
 Here comments are enclosed between /* and */ on one or several
lines.
 javadoc Comments (/**…*/)
 These are special types of comments supported by Java and can be
extracted into an HTML file using the JDK’s javadoc command.
44
The package Statement
 In Java, packages are used to place and organize
classes.
 To do so, you need to add the following line as the first
non-comment and nonblank statement in the program.
package packageName;
 Note:
 If a class is defined without the package statement, it is
said to be placed in the default package.

45
Import Statements
 The import statement simply tells the compiler where to locate the classes
within the Java Application Program Interface (API).
 There are two types of import statements. These are:
 Specific import
 Specifies and imports a single class from a package. For example, the
following statement imports the class Date from the package, java.util.
import java.util.Date;
 Wildcard import
 Imports all the classes from a package. For example, the following
statement imports all the classes from the package, java.util.
import java.util.*;
 The information for the classes in an imported package is not read in at
compile time or runtime unless the class is used in the program.
 This implies that there is no performance difference between a specific
import and a wildcard import declaration.
 All the classes in the java.lang package are implicitly imported in every
java program.
46
Reserved words or keywords
 These words have a specific and predefined meaning to the
compiler and cannot be used for any other purposes in the
program.
 Are reserved for use by Java and are always spelled with all
lowercase letters.

47
Identifiers
 Identifiers are the names of things that appear in the
program.
 Simply saying, you use identifiers for naming variables,
constants, methods, classes, and packages.
 In Java programming language, all identifiers must obey the
following rules:
 An identifier is a sequence of characters that consists of
letters, digits, underscores (_), and dollar signs ($).
 An identifier must start with a letter, an underscore (_), or
a dollar sign ($). It cannot start with a digit.
 An identifier cannot be a reserved word.
 An identifier cannot be true, false, or null.
 An identifier can be of any length.
 Note: The Java language is a “case sensitive” language.
48
Variables
 A variable designates a location in memory (Random Access
Memory) for storing data to be used in a program and
computational results of the program.
 They are called variables because their values can be changed
later in the program.
 A variable has a name that can be used to access the memory
location it is designated.
Variable Declaration
 A variable must be declared before it can be assigned a value.
 A variable declared in a method must be assigned a value
before it can be used in the program.
 Variable declaration tells the compiler the following two main
points:
 Name of the variable and the type of data it can store.
 To allocate appropriate memory space for the variable based
49on its data type.
Cont’d…
 The syntax for declaring a variable is: datatype variableName;
 Some examples of variable declarations
char grade; //declares grade to be a character variable
int age; //declares age to be an integer variable
double salary; //declares salary to be a double variable
 Two or more variables of the same data type can be declared together
in one statement by separating each variable by comma.
 For example, int a, b, c; //declares a, b, and c as int variables
Variable Initialization
 A variable can be declared and initialized (or assigned an initial value)
in a single statement.
 Consider, for instance, the following code:
int count = 1;
 This is equivalent to the following two separate statements:
int count;
50 count = 1;
Variable Scope
 Scope refers to the parts of the code in which the variable name can
be used without prefixing it with the class or object name.
 The scope is determined by where in the class definition a variable is
declared.
 Generally, Java variables have either class scope or local scope.
 There are three types of variables in java which are local variable,
instance variable and static variable (class variable).
 Local Variable:
 A variable declared inside the body of the method is called local variable.
 You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists.
 A local variable cannot be defined with "static" keyword.
 Instance Variable:
 A variable declared inside the class but outside the body of the method, is
called instance variable.
 It is not declared as static. It is called instance variable because its value is
instance specific and is not shared among instances.
51
Cont’d …
 Static variable:
 A variable which is declared as static is called static variable.
 It cannot be local.
 You can create a single copy of static variable and share among all the
instances of the class.
 Memory allocation for static variable happens only once when the class
is loaded in the memory.
 Static variables are also known as class variables.
NB:
 Class variables (static) are used to store data that is common to all objects of the class.
 Instance variables are used to store data that persists through the lifetime of an object.
 Local variables are often used as temporary storage locations while a method or
constructor completes its task.
 Example:
class A{ int data=50;//instance variable
static int m=100;//static variable
void method()
{ int n=90;//local variable }
}//end of class
52
Constants (or Read-Only Objects)
 The value of a variable may change during the execution of a
program, but a constant represents a permanent data that
never changes throughout the program.
 A constant must be declared and initialized in the same
statement.
 The word final is a java keyword for declaring and creating a
constant or read-only variable.
 A descriptive name for a constant makes your program easy to
read.
Syntax:
final datatype CONSTANTNAME = VALUE;
 For example:
final double PI = 3.14;
Benefits of Constants
 You do not have to repeatedly type the same value.
 If you have to change the constant value, you need to change it
only in a single location within the source code.

53
Data Types
 Every variable must have a data type – the data type determines the
values that a variable can contain and also what operations can be
performed on it.
 Java has two types of data type – primitive and reference.
Primitive Data Types
 A variable of primitive type contains a single value of the appropriate
size and format for its type: a number, a character, or a Boolean value.
 For example, an integer value is 32 bits of data in a format known as
two's complement;
 the value of a char is 16 bits of data formatted as a Unicode
character, and so on.
 The primitive types can be divided into numeric and non-numeric
types.
 Numeric types can further be divided into integer and real number (or
floating-point) types.
 Integer types hold whole numbers, positive and negative.
 Real
54 number types can hold decimal values e.g. 1.234, -6.754.
Cont’d…
▪ There are around 8 primitive data types in java.
▪ These are
▪ byte

▪ short
▪ int
▪ long
▪ float
▪ double
▪ boolean
▪ char
55
The Character Data Type
 The character data type, char, is used to represent a single character.
 For example, consider the following code:
char letter = ‘A’;
char digitChar = ‘5’;
Escape Sequences

System.out.println("Welcome to \"Java\" Programming!");


The output of the above statement is: Welcome to “Java" Programming!
56
The Boolean Data Type
 A variable that holds a Boolean value (true or false) is
known as a Boolean variable.
 The boolean data type is used to represent a Boolean
value and to declare a Boolean variable.
 A Boolean variable can hold one of the two values: true
and false.
 For example, the following statement declares a Boolean
variable, isValid, and assigns the Boolean literal, true, to
the variable.
boolean isValid = true;

57
Numeric Data Types
 Numeric data types are used to represent numeric
literals: integers and floating-point numbers.

58
Floating-Point Data Types
 Java uses two types for floating-point numbers: float and double.
 The double type is twice as big as float. So, the double is known as double
precision, float as single precision.
 Normally, you should use the double type, because it is more accurate than
the float type.
 Caution
 When a variable is assigned a value that is too large (in size) to be stored, it causes
overflow. For example, executing the following statement causes overflow, because the
largest value that can be stored in a variable of the int type is 2147483647.
2147483648 is too large.
int value = 2147483647 + 1; // value will be: -2147483648
 Java does not report warnings or errors on overflow. So be careful when
working with numbers close to the maximum or minimum range of a given
type.
Real number / Float IEEE 754 floating point; 32 bits
floating-point +/- 1.4E-45 to +/- 3.4028235E+38
types Double IEEE 754 floating point; 64 bits
+/- 4.9E-324 to +/- 1.7976931348623157E+308
59
Exercise
 What data types would you use to store the following
types of information?:
1)Population of Ethiopia
2)Approximation of π
3)Open/closed status of a file
4)Your name
5)First letter of your name
6)$237.66
 Declare variables of primitive data types
 Check their MIN_VALUE and MAX_VALUE with wrapper class
 Test Final variables and Variable Scopes
 Declare appropriate data types for your varaibles

60
Referenced Data Types
 Arrays, strings and classes are reference data types in Java.
 While a variable that has a primitive data type holds exactly one value, a variable
that has a reference data type is a reference to the value or set of values
represented by the variable.
 A variable of reference type has as its value an address, or a pointer to the
values or set of values that the variable represents.
Classes
 When a class is defined, it can then be used as a data type.
 The variable declaration for a reference data type is the same as for a primitive
data type. For example, if a program has a class named Customer, a new
variable, myCustomer1, to hold an object of type Customer can be declared like
this:
Customer myCustomer1;
 However, to assign a reference to the variable, the new keyword must be used –
new creates a new object from the specified class.
Customer myCustomer1 = new Customer();
 This is the same as the following lines.
Customer myCustomer1;
61 MyCustomer1 = new Customer();
Cont’d…
Strings
 The char type only represents one character.
 To represent a string of characters, use the data type called String.
Example: String message = “Welcome to Java”
 String is actually a predefined class in Java library just like the System class.
 The plus sign (+) is the concatenation operator if one of the operand is a
string.
Example: String message = “Welcome” + “to” + “Java”
 If one of the operand is a non-string (e.g. a number), the non-string value is
converted into a string and concatenated with the other string.
Example: String s = “Chapter” + 2; // s becomes Chapter2
 The shorthand += operator can be also used for string concatenation.
 For example:
String message = “ Welcome to Java”;
message += “ and Java is fun”; // the message is “Welcome to Java and Java is fun ”
 If neither of the operand is a string , the plus sign (+) is the addition operator
that adds two numbers.
62
Cont’d …
Arrays
 Array is a data structure that represents a collection of the same types of data,
but it is often more useful to think of an array as a collection of variables of the
same type.
 An array is also a reference type, a structure that can hold multiple values –
but all the values must be of the same type.
 That type can be a primitive data type or an object type, or it can be other
arrays.
 In Java, an array is actually an object – but one that has specialized
syntax and behavior.
Declaration
 byte[] arrayOfBytes; //array of values of type byte
 byte[][] arrayOfArrayOfBytes ; //an array of arrays of byte[] type
 Customer[] arrayOfCustomers; //array of objects of the class Customer
 The C++ syntax for declaring a variable of array type is also supported by
Java i.e.
 Byte arrayOfBytes[]; //array of values of type byte
 However, this syntax can be confusing, so it should be avoided in Java.
63
Cont’d …
 Because an array is actually an object in Java, the new keyword must be used
to create the array (new is used to create any object).
 The size of the array i.e. how many elements it can hold must be specified.
For example:
byte[] arrayOfBytes = new byte[1024];
 When the array is created in this way, each of the values in the array is
initialized to the corresponding default value for the data type of the value.
 In Java, arrays have a 0-based index, that is, the first element is at index 0.
 For example, to declare an array named 'responses', with two elements whose
values are 'Yes' and 'No':
String[] responses = new String[2];
responses[0] = "Yes";
responses[1] = "No";
 to read the elements
System.out.println ("The answer should be" + responses[0] + " or " + responses[1] + "!");
64
Cont’d …
 If the size of an array is n, then the highest index for it is (n-1).
 If the code tries to read an element past the end of the array e.g. to
read index [5] in an array of size 5, the interpreter throws an
ArrayIndexOutOfBoundsException at runtime.
 Throwing an exception is part of the runtime error handling of Java.
 The size, or length, of an array can be accessed in code by reading the
value of the length property of the array object. E.g.
int sizeOfResponsesArray = responses.length;
 This is commonly used to loop through all the values in an array e.g.
int[] valuesArray; //assume this array is created and initialised somewhere else

int totalValue = 0; //store the sum of the array elements


for (int i = 0; i < valuesArray.length; i++)
totalValue += values[i];

65
Cont’d …
Assigning Values to Arrays
 The null literal can be used to indicate that an object that is of a reference data
type does not yet exist i.e. to initialise an object to be empty or null.
 E.g.: char[] password = null; //sets the password array of characters to be null
 An array can also be initialised by the following syntax, where the array object is
created and the elements initialised in one statement.
 The element values are separated by commas.
 The new keyword is not used – but the object is implicitly created.
int[] someNumbers = {1, 2, 3, 4}
 The length of this array is now 4 – again, this is implicit from the specified
elements.
 The statement above could also be written as:
int[] someNumbers = new int[4];
someNumbers[0] = 1;
someNumbers[1] = 2;
someNumbers[2] = 3;
someNumbers[3] = 4;
66
Cont’d…

67
Literals
 A literal is a constant value that appears directly in a program.
Character Literals
 A character literal is a single character enclosed is single
quotation marks (‘ ‘).
Constant Character
‘A’ Uppercase A
‘a’ Lowercase a
‘‘ Blank
‘.’ Dot
‘0’ Digit 0
‘?’ Question mark

Boolean Literals
 A Boolean expression can have two values that are identified by
the words true and false.
68
Cont’d …
Integral Literals
 An integer literal is an integral numeric value that can be assigned to an integer
variable as long as it can fit into the variable.
 A compile error will occur if the literal is too large for the variable to hold.
 The statement byte b = 128, for example, will cause a compile error.
 An integer literal is assumed to be of the int type, whose value is between -
2147483648 and 2147483647.
 To denote an integer literal of the long type, append the letter L or l to it (e.g.,
2147483648L).
 Note: By default, integral numeric constants are represented as simple decimal
numbers, but they can also be specified as an octal or hexadecimal literal.
 a decimal constant (base 10) begins with a decimal number other than zero,
such as 109 or 987650.
 an octal constant (base 8) begins with a leading 0, for example 077 or
01234567.
 a hexadecimal constant (base 16) begins with the character pair 0x or 0X,
for example 0x2A0 or 0X4b1C.
69
Cont’d …
Floating-Point Literals
 Floating-point literals are written with a decimal point.
 By default, a floating-point literal is treated as a double type value.
 For example, 5.0 is considered a double value, not a float value.
 You can make a number a float by appending the letter f or F, and you can
make a number a double by appending the letter d or D.
 For example, you can use 100.2f or 100.2F for a float number, and 100.2d
or 100.2D for a double number.
 Scientific Notation
 Floating-point numbers are usually represented as decimals, a decimal point
being used to distinguish the fraction part from the integer part. However,
exponential (or scientific) notations are also permissible to specify floating-
point numeric literals.
 For example, 1.23456e+2, is equivalent to 1.23456 X 102 = 123.456, and
1.23456e-2 is equivalent to 1.23456 X 10-2, = 0.0123456. E (or e)
represents an exponent and can be in either lowercase or uppercase.
 Note: A decimal point (.) or E (e) must always be used to distinguish floating-
point constants from integer constants.
70
Cont’d …
String Literals
 A string literal consists of a sequence of zero or more
characters enclosed in double quotes.
Note:
 A string literal must be enclosed in quotation marks.
 A character literal is a single character enclosed in single
quotation marks.
 So "A" is a string, and 'A' is a character.

71
Operators
The Assignment Operator (=)
 A simple assignment uses the assignment operator (=) to assign a
value into a variable.
 In expressions of this type the variable must be placed on the left
and the value to be assigned on the right side of the assignment
operator.
boolean isPrime = false;
char grade = ‘A’;
int age = 23;
float salary = 4250.50;
 Multiple assignments, which are always evaluated from right to left,
are also possible.
 For example, the following statement assigns the value 3 to j first
and then to i.
int i = j = 3;
72
Cont’d…
Arithmetic Operators
 Arithmetic operators are used to perform calculations.
Binary Arithmetic Operators

• Divisions performed with integral operands will produce integral


results; for example, 7 / 2 computes to 3.
• If at least one of the operands is a floating-point number, the result
will also be a floating-point number; e.g., the division 7.0 / 2
produces an exact result of 3.5.
73
Cont’d …
Unary Arithmetic Operators
 There are four unary arithmetic operators:
 the sign operators (+ and -),
 the increment operator (++), and the decrement operator (--).
Sign Operators (Unary Minus - and Unary Plus + )
 The sign operator (-) returns the value of the operand but inverts its sign.
Example: int n = -10;
System.out.println(-n); //Prints the value 10
 The sign operator (+) performs no useful operation, simply returning the
value of the operand.
Increment (++) / Decrement (- -) Operators
 These are unary arithmetic operators which are used for incrementing and
decrementing the value of a variable by 1.
int i = 3, j = 3;
i++; // i becomes 4
j--; // j becomes 2
74
Cont’d …
 The ++ and -- operators can be used in prefix or suffix mode.
 If the operator is before (prefixed to) the variable, the variable is incremented
or decremented by 1, then the new value of the variable is returned.

In this case, a is incremented by 1 first, and the new value of a is returned and used in the
multiplication. Thus a becomes 6 and b becomes 60.

In this case, the original old value of a is returned and used in the multiplication first and then
the value of a is incremented by 1. Thus a becomes 6 and b becomes 50.

Note: The increment and decrement operators can also be used on char variables to get the
next or preceding Unicode character. For example, the following statements display the
character b.
char ch = 'a' ;
System.out.println(++ch);

75
Cont’d …
Compound Assignment (Shorthand Operators)
 In addition to the simple assignment operator (=) there are
also compound assignment (shorthand) operators that
simultaneously perform an arithmetic and an assignment
operations.

 The += is called the addition assignment operator.

76
Cont’d …
Comparison (Relational) Operators
 Each comparison in Java is a boolean type expression with a value of
true or false, where true means that the comparison is correct and
false means that the comparison is incorrect.

Note: You can also compare characters. Comparing characters is the same
as comparing their Unicode values. For example, 'a' is larger than 'A'
because the Unicode of 'a' is larger than the Unicode of 'A'.
77
Cont’d …
Logical Operators
 Logical operators, also known as Boolean operators, operate on Boolean values
to create a new Boolean value.
Operator Name Usage
&& Conditional op1 && op2: Returns true if op1 and op2 are both true – only
AND evaluates op2 if op1 is true
|| Conditional op1 | | op2: Returns true if op1 or op2 is true – only evaluates op2
OR if op1 is false
! Boolean NOT !op: Returns true if op is false i.e. changes the boolean value of the
operand
& Boolean AND op1 & op2: Like && but always evaluates both operands
| Boolean OR op1 | op2: Like || but always evaluates both operands, even if the
first one is true
^ Boolean XOR op1 ^op2: Exclusive OR – returns true only if exactly one of the
operands is true. Returns false if both are true or both are false

78
Cont’d …
Conditional Operator (?:)
 It is the Java’s only ternary operator - that means it takes three
operands.
 The first operand is Boolean expression; either the second or
the third operand is executed based on the value of the first
operand.
Example: System.out.println(Grade>=60?Passed”:”Failed”);
prints “Passed” if grade >=60, else prints “Failed”.

79
Other Operators
instanceof
 The instanceof operator is a special operator that is used to
check if a given object is an instance of a particular class.
 It returns true if the object is an instance of the class and
false if not.
 For example:
 person instanceof student //returns true if the object person
belongs to the class Student
 "a string" instanceof String //returns true because all strings
are instances of the String class
 "a string" instanceof Object //returns true because Strings
are also instances of the Object superclass
 null instanceof String //returns false because null is never an
instance of anything

80
Cont’d …
Object Member Access (.)
 The dot (.) operator is used to access the data and methods of an
object.
 The data fields and methods of an object are also known as members of
the object.
 For example:
Person aPerson = new Person();
String theName = new String();
theName = aPerson.name //evaluates to the value of the name
data field of the Person object
Method Invocation (( ))
 A method can be accessed using the dot operator, and it is invoked by
using the ( ) operator after the method name.
 Any arguments or parameters to the method are placed inside the
brackets.
 For example:
Person aPerson = new Person();
aPerson.increaseSalary(100); //invokes the method
increaseSalary, passing 100 as the paramter)

81
Cont’d …
Object Creation (new)
 As already seen, new is used to create a new object or array.
 The new keyword is followed by the class name and a list of
arguments to be passed to the object constructor.
 The arguments are placed inside brackets.
 For example, if the constructor for the Person class takes the
name and father's name as arguments:
Person aPerson = new Person("Firstname", "Fathersname");

82
Operator Precedence
 Operator precedence determines the order of evaluation of an
expression with multiple operands, i.e. how operators and operands
are grouped.
 Example: 2+7*3 //Adds 2 to 21

• If operators with the same


precedence are next to each
other, their associativity
determines the order of
evaluation.
• All binary operators except
assignment operators are left
associative.
• For example, since + and –
are of the same precedence
and are left associative, the
expression
a–b+c–d
is equivalent to
((a – b) + c) - d
83
Type Conversion
 Java carries out implicit conversions between number types.
 For example, if a short literal value is assigned to an int data type, Java
automatically converts the value to int:
 int x = 32767; //32767 is a literal value of type short, but is converted to int
 This is called a widening conversion because the value is being converted to
a type that has a wider range of legal values.
 A narrowing conversion occurs when a value is converted to a type that is
not wider than it.
 Sometimes this type of conversion is not safe e.g. it is safe to convert the
integer value 13 to a byte, but not to convert 13000 to a byte, because the
byte type can only hold numbers between –128 and 127.
 Because of this, the Java compiler produces a compile error when the code
attempts a narrowing conversion.
 This happens even if the actual value being converted would fit into the
narrower range. For example: int i = 13;
byte b = i; //not allowed by the compiler because byte is a narrower
type (even though 13 is an allowed value for byte)

84
Cont’d …
 The error produced by the compiler for a narrowing conversion includes the
message 'possible loss of precision'.
 The above are examples of implicit conversion – Java carries out the conversion
automatically, if it is ok to do so.
 However, a conversion from one type to another can be forced using a cast.
 This can be used when a narrowing conversion would occur, and if the
programmer knows that data will not be lost.
Syntax: (type) expression
int i = 13;
byte b = (byte) i; //force the int value 13 to be converted to a byte
 For example:
int i;
i = (int) 13.456; //forces the double literal to the int value 13
 Casting can also be used with reference data types, but there are some
restrictions.
 As with primitive types, the Java interpreter automatically carries out widening
conversions. Narrowing conversions must be made explicit using a cast.

85
Cont’d …
 When converting reference data types, the following rules apply:
 An object can be converted to the type of its superclass, or any ancestor
class in its class hierarchy. This is a widening conversion.
 An object can be converted to the type of its own subclass. This is a
narrowing conversion, so it requires a cast.
 An object cannot be converted to an unrelated type i.e. to a class that the
object is not a subclass or superclass of.
 All Java classes automatically inherit from the Object superclass (this
gives them special methods such as toString(), clone() and equals()).
 For example, the String class is a subclass of Object.
 So a string value can be assigned to a variable of type Object.
 If assigning the value to a String variable, a cast is required.
Object o = "a string"; //a widening conversion
//later in the code, the value of o can be cast back to a String
String s = (String) o; //a narrowing conversion, so requires a cast

86
Cont’d …
Casting between char and Numeric Types
 A char can be cast into any numeric type, and vice versa. When an integer is
cast into a char, only its lower 16 bits of data are used; the other part is
ignored.
E.g char ch = (char) 0XAB0041; // the lower 16 bits hex code 0041 is// assigned to ch
System.out.println(ch); // ch is character A
 When a floating-point value is cast into a char, the floating-point value is first
cast into an int, which is then cast into a char.
char ch = (char) 65.25; // decimal 65 is assigned to ch
System.out.println(ch); // ch is character A
 When a char is cast into a numeric type, the character’s Unicode is cast into
the specified numeric type.
int i = (int) 'A' ; // the Unicode of character A is assigned to I
System.out.println(i); // i is 65
87
Cont’d …
 Implicit casting can be used if the result of a casting fits into the target
variable. Otherwise, explicit casting must be used. For example:
byte b = 'a' ; since the Unicode of 'a' is 97, which is within the range of a byte
int i = 'a' ;
 But the following casting is incorrect, because the Unicode \uFFF4 cannot fit
into a byte.
byte b = '\uFFF4' ;
 To force assignment, use explicit casting, as follows:
byte b = (byte) '\uFFF4' ;
 Any positive integer between 0 and FFFF in hexadecimal can be cast into a
character implicitly. Any number not in this range must be cast into a char
explicitly.
Note
 All numeric operators can be applied to char operands. A char operand is
automatically cast into a number if the other operand is a number or a
character. If the other operand is a string, the character is concatenated with
the string.
 For example, the following statements:
88
Cont’d …
int i = '2' + '3' ; // (int)'2' is 50 and (int)'3' is 51
System.out.println("i is " + i); // i is 101
int j = 2 + 'a' ; // (int)'a' is 97
System.out.println("j is " + j); // j is 99
System.out.println(j + " is the Unicode for character "+ (char)j); //c
System.out.println("Chapter " + '2' ); // Chapter2

Note
 The Unicode’s for lowercase letters are consecutive integers starting
from the Unicode for 'a' ,then for 'b' , 'c' , and 'z' .
 The same is true for the uppercase letters. Furthermore, the Unicode
for 'a' is greater than the Unicode for 'A' . So 'a' - 'A' is the same as
'b' - 'B' .
 For a lowercase letter ch, its corresponding uppercase letter is
(char)('A' + (ch - 'a')).
89
Cont’d …
Convert String to Integers
 For instance if you use input dialog box, the input returned from the
input dialog box is a string.
 If you enter a numeric value such as 123, it returns “123”.
 To obtain the input as a number, you have to convert a string into a
number.
 To convert a string into an int value, you can use the static parseInt
method in the Integer class as follows:
int intValue = Integer.parseInt(intString);
//Where intString is a numeric string such as “123”.
Converting String to Double
 To convert a string into a double value, you can use the static
parseDouble method in the Double class as follows:
double doubleValue =Double.parseDouble(doubleString);
//Where doubleString is a numeric string such as “123.45”.

90
Displaying Output on the Console
 Console refers to text entry and display device of a computer.
 Java uses System.out to refer to the standard output device.
 By default the output device is the display monitor.
 To perform console output, you simply use println or print methods to display a
primitive value or a string to the console.
 The print method is identical to the println method except that println moves
the cursor to the next line after displaying the string, but print does not advance
the cursor to the next line when completed.
 Caution
 A string constant cannot cross lines in the source code. Thus the following
statement would result in a compile error:
System.out.println("Welcome to Ethiopia,
the nation in our World with 13 months of sunshine!");
 To fix the error, break the string into separate substrings, and use the
concatenation operator (+) to combine them:
System.out.println("Welcome to Ethiopia, the only nation in” +
“our World with 13 months of sunshine!");

91
Reading Input from the Console
 Java uses System.in to refer to the standard input device.
 By default the input device is the keyboard.
 Console input is not directly supported in Java, but you can use the
Scanner class to create an object to read input from System.in, as
follows:
Scanner input = new Scanner(System.in);
 The syntax new Scanner(System.in) creates an object of the
Scanner type.
 The syntax Scanner input declares that input is a variable whose
type is Scanner.
 The whole line Scanner input = new Scanner(System.in) creates a
Scanner object and assigns its reference to the variable input.
 An object may invoke its methods.
 To invoke a method on an object is to ask the object to perform a task.

92
Cont’d …
 Methods for scanner object are as follows

import java.util.Scanner;
public class TestScanner {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int intValue = scanner.nextInt();
System.out.println("You entered the integer " + intValue);
System.out.print("Enter a double value: ");
double doubleValue = scanner.nextDouble();
System.out.println("You entered the double value “ + doubleValue);
System.out.print("Enter a string without space:");
String string = scanner.next(); System.out.println("You entered the string " + string); } }
93
Mathematical Functions
 In Java, mathematical functions such as square root and
trigonometric functions are implemented as methods on the Math
class (equivalent of the C <math.h> functions).
 This class is part of the built-in java.lang package – because it is a
built-in class, it does not have to be imported to use it.
 The Math class also provides constants for the mathematical values
PI and E.
 For example:
double x,y;
x = 9;
y= Math.sqrt(x); //computes the square root of x
 //use PI to compute the area of a circle
double radius;
radius = 6;
double circleArea = Math.PI * radius * radius;

94
Cont’d …
Method Description
sin (x) Trigonometry Sin
cos (x) Trigonometry Cos
tan (x) Trigonometry Tan
asin (x) Trigonometry aSin
acos (x) Trigonometry aCos
atan (x) Trigonometry aTan
pow (x, y) Returns x to the power of y (xy)
exp (x) Returns e to the power of x (ex)
Log (x) Returns the natural logarithm of x
sqrt (x) Returns the square root of x
ceil (x) Returns the smallest whole number greater than or equal to x (rounding up)
floor (x) Returns the greatest whole number less than or equal to x (rounding down)
rint (x) Truncated value of x
abs (a) Returns the absolute value of a
max (a,b) Returns the maximum value of a and b
min (a,b) Returns the minimum value of a and b
Constant Value & Description
PI Double, 3.141592653589793 (access using Math.PI)
E Double, 2.718281828459045 (access using Math.E)

95
Programming Errors
 Programming errors are unavoidable, even for
experienced programmers.
 Errors can be categorized into three types:
 Syntax errors,
 Runtime errors, and
 Logic errors.
Syntax errors
 Errors that occur during compilation are called syntax
errors or compile errors.
 Syntax errors result from errors in code construction,
such as mistyping a keyword, omitting some necessary
punctuation, or using an opening brace without a
corresponding closing brace.
 These errors are usually easy to detect, because the
compiler tells you where they are and what caused them.
96
Cont’d …

Runtime Errors
 Runtime errors are errors that cause a program to terminate abnormally.
 They occur while a program is running if the environment detects an operation
that is impossible to carry out. Input errors typically cause runtime errors.
 An input error occurs when the user enters an unexpected input value that
the program cannot handle.
 For instance, if the program expects to read in a number, but instead the user
enters a string, this causes data-type errors to occur in the program.
 To prevent input errors, the program should prompt the user to enter values of
the correct type.
 It may display a message such as “Please enter an integer” before reading
an integer from the keyboard.
 Another common source of runtime errors is division by zero.
97
Cont’d …
Logic Errors
 Logic errors occur when a program does not perform the way it was
intended to.
 Errors of this kind occur for many different reasons.
 For example, suppose you wrote the following program to add
number1 to number2 and store the result back into number2.
public class ShowLogicError {
public static void main(String[] args) {
int number1 = 3;
int number2 = 3;
number2 += number1 + number2;
System.out.println(“number2 is “ + number2);} }
 The above program does not have any syntax errors or runtime errors,
but it does not print the correct result for number2.

98
Debugging
 In general, syntax errors are easy to find and easy to correct, because the
compiler gives indications as to where the errors came from and why they
are wrong.
 Runtime errors are not difficult to find, either, since the reasons and
locations of the errors are displayed on the console when the program
aborts.
 Finding logic errors, on the other hand, can be very challenging.
 Logic errors are called bugs. The process of finding and correcting errors is
called debugging.
 A common approach is to use a combination of methods to narrow down to
the part of the program where the bug is located.
 You can hand-trace the program (i.e., catch errors by reading the
program), or you can insert print statements in order to show the values of
the variables or the execution flow of the program.
 This approach might work for a short, simple program.
 But for a large, complex program, the most effective approach is to use a
debugger utility.

99
Chapter 3

Decision and Repetition Statements

100
Statements
 A statement is a complete unit of execution.
 Any expression that has a side-effect, i.e. it changes the state of the program
in some way, can be used as a statement simply by putting a semi-colon after
it.
 These are assignments, increments and decrements, method calls and object
creation. For example:
i = 10; //assignment
i++; //increment
System.out.println ("Value of i is: “+ i); //method call
Integer integerObject = new Integer(4); //object creation
 Variable declarations are also statements e.g.: float f = 1.234;
 A block is a group of 0 or more statements between curly braces ({}) and can
be used anywhere that a single statement is allowed.
 Blocks are used to group statements together e.g. the statements to execute
when the condition for an if statement is true.
101
Cont’d…
 A running program spends all of its time executing statements.
 The order in which statements are executed is called flow control
(or control flow).
 Control flow statements regulate the order in which statements get
executed.
 There are three basic types of program flows
 Sequential
 In Sequential execution statements in a program are executed
one after the other in sequence.
 Selection
 Selection or conditional execution executes part of the code
based on the condition.
 Iteration
 In iterative program flow statements inside looping statement
are executed repeatedly as long as a condition is true.
102
Conditional (Selection) Statements
 Like all high-level programming languages, Java provides
selection statements that let you choose actions with two
or more alternative courses.
 Selection statements use conditions.
 Conditions are comparisons or Boolean expressions.
 The result of a comparison and a Boolean or logical
expression is a Boolean value: true or false.
 Java has several types of selection statements:
 one-way if statements,
 two-way if statements,
 Nested if statements, multi-way if statements,
 switch statements, and
 conditional expressions.

103
Cont’d…
One-Way if Statement
 A one-way if statement executes an action if and only if the
condition is true.
 Syntax:
if (boolean-expression)
{statement(s);}
 The boolean-expression must be enclosed in parentheses and the
block braces can be omitted if they enclose a single statement.

104
Cont’d…
 The following program demonstrates and helps you understand the
use of a one-way if statement.
 The program reads an integer from the user and displays the
absolute value of the number.
import java.util.Scanner;
public class AbsoluteValue {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer number: ");
int number = input.nextInt();
if (number < 0)
number = -number;
System.out.println("Absolute value: " + number);
}}}

Absolute value of an integer can be computed using the method:


Math.abs(a)
105
Cont’d…
Two-Way if Statement
 The actions that a two-way if statement specifies differ based on
whether the condition is true or false.
 Syntax :
if (boolean-expression)
{ statement(s)-for-the-true-case; }
else { statement(s)-for-the-false-case; }
 If the boolean-expression evaluates to true, the statement(s) for the
true case are executed; otherwise, the statement(s) for the false case
are executed.

106
Cont’d…
 The following program demonstrates and helps you understand
the use of a two-way if statement.
 The program prompts a user to enter an integer and checks
whether the number is odd or even.
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number % 2 ==0)
System.out.println(number + " is even.");
else
System.out.println(number + " is odd.");
}
}
107
Cont’d…
Nested if Statements
 The nested if statement can be used to implement multiple alternatives.
if (i > k) {
if (j > k)
System.out.println("i and j are greater than k");
}
else
System.out.println("i is less than or equal to k");
 The if (j > k) statement is nested inside the if (i > k) statement.

108
Cont’d…
 The following code snippet depicts how nested if else statement is
used to calculate letter grade from a score out of 100
import java.util.Scanner;
class NestedIf
{ public static void main(String[] args)
{ System.out.println("Please enter students score out of 100");
Scanner input=new Scanner(System.in);
double mark=input.nextDouble();
if(mark>90)
System.out.println("Grade is A");
else if(mark>80)
System.out.println("Grade is B");
else if(mark>70)
System.out.println("Grade is C");
else if(mark>60)
System.out.println("Grade is D");
else if(mark>50)
System.out.println("Grade is Fx");
else
System.out.println("Grade is F");
}
} 109
Cont’d…
The switch Statement
 Just like the else-if chain, the switch statement allows you to choose
between multiple alternatives.
 The switch statement compares the value of one expression with
multiple constants.
 Syntax:
switch (switch-expression)
{
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}

110
Cont’d…
 The switch statement observes the following rules:
 The switch-expression must yield a value of char, byte, short, or int type
and must always be enclosed in parentheses.
 The value1… and valueN must have the same data type as the value of the
switch-expression.
 Note that value1… and valueN are constant expressions, meaning that they
cannot contain variables, such as 1 + x.
 When the value in a case statement matches the value of the switch-
expression, the statements starting from this case are executed until either a
break statement or the end of the switch statement is reached.
 The keyword break is optional. The break statement immediately ends the
switch statement.
 The default case, which is optional, can be used to perform actions when none
of the specified cases matches the switch-expression.
 The case statements are checked in sequential order, but the order of the
cases (including the default case) does not matter.
 However, it is good programming style to follow the logical sequence of the
cases and place the default case at the end.

111
Cont’d…
 The following program prompts a student to enter the grade he or she has
scored in a certain course and displays the corresponding remark using switch.
import java.io.*; case 'F':
class SwitchExample remark="Failed";
{public static void main(String[] args) break;
throws IOException default:
{ remark="Invalid grade";
System.out.println("enter grade"); }
char grade=(char)System.in.read(); System.out.println("Status= "+remark);
String remark; }

switch(grade) }
{ case 'A':
remark="Excellent";
break;
case 'B':
remark="Very Good";
break;
case 'C':
remark="Good";
break;
case 'D':
remark="Poor";
break;
112
Cont’d…
Caution
 Do not forget to use a break statement when one is needed.
 Once a case is matched, the statements starting from the
matched case are executed until a break statement or the end
of the switch statement is reached.
 This is referred to as fall-through behavior.
 For example, the following code prints character a three times if
ch is ‘a’:
switch (ch)
{
case 'a' : System.out.println(ch);
case 'b' : System.out.println(ch);
case 'c' : System.out.println(ch);
}
113
Loop Statements
 Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred
times. It would be tedious to have to write the following statement a hundred
times:

 So, how do you solve this problem?


 Java provides a powerful construct called a loop that controls how many times
an operation or a sequence of operations is performed in succession.
 Loops are constructs that control repeated executions of a block of
statements.
 The set of instructions to be iterated is called the loop body.
 The number of times a loop is repeated is defined by a controlling
expression.
 Java provides three types of loop statements: for loop, while loop, and do-
while loop.

114
The for Loop
 The for loop statement starts with the keyword for, followed by
a pair of parentheses enclosing the control structure of the
loop.
 This structure consists of initial-action, loop-continuation-
condition, and action-after-each-iteration.
 The initial-action, loop continuation-condition, and action-after-
each-iteration are separated by semicolons.
Syntax:
for (initial-action; loop-continuation-condition; action-after-each-iteration)
{
// Loop body;
Statement(s);
}
 The part of the loop that contains the statements to be
repeated is called the loop body.

115
Cont’d …
public class forloop
{
//sum of integers from 1to100
public static void main(String[] args)
{
int sum=0;
for(int i=1;i<=100;i++)
{
sum=sum+i;
}
System.out.println("Sum is: "+sum);
}
}

116
for each
 The basic for loop was extended in Java 5 to make iteration
over arrays and other collections more convenient.
 This newer for statement is called the enhanced for or for-
each (because it is called this in other programming
languages).
 The for-each loop is used to access each successive value in an
array or collection of values.
 It is easier to use than simple for loop because we don't need to
increment value and use subscript notation.
 It works on elements basis not index.
 It returns element one by one in the defined variable.
Syntax:
for(Type var:array or collection)
{ Body of loop }

117
Cont’d …
public class ForEachLoop
{
// sum of array elements
public static void main(String[] args)
{
int[] arr={12,34,56,78,90};
int sum=0;

for(int x : arr)
{
sum=sum+x;
}
System.out.println("sum of arrays"+sum);
}
}

118
The while Loop
 A for loop is used when the programmer knows how many
times the code block is to be executed.
 With a while loop, the number of times the loop is executed
can vary with each time the code is run.
Syntax:
while (loop-continuation-condition)
{
// Loop body
Statement(s);
}
 Note
 The loop-continuation-condition must always appear inside the
parentheses. The braces enclosing the loop body can be
omitted only if the loop body contains one or no statement.
119
Cont’d …
public class WhileLoop
{
public static void main(String[] args)
{
int sum=0, i=1;
while(i<=50)
{
sum+=i;
i++;
}
System.out.println("The sum is: "+sum);

}
}

120
The do-while Loop
 The do-while loop is a variation of the while loop.
 Syntax :
the loop-continuation-condition is evaluated. do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
 The loop body is executed first. Then
 If the evaluation is true, the loop body is executed again; if it is false,
the do-while loop terminates.
 The difference between a while loop and a do-while loop is the order
in which the loop-continuation-condition is evaluated and the loop
body executed.
 The body statement in the do-while is guaranteed to be executed at
least once – because the expression is evaluated at the end of the
loop.

121
Cont’d …
public class DoWhileLoop
{
public static void main(String[] args)
{
int sum=0; int i=1;
do
{
sum=sum+i;
i++;
}
while(i<=100);
System.out.println("Sum is: "+sum);
}
}

122
Other Statements
Break
 The break statement causes the interpreter to skip immediately
to the end of a containing statement – the flow of control then
transfers to the statement following the end of the statement.
 The containing statement can be a switch, for, while or do-
while.
For example – searching through an array to find a value:
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
int searchfor = 12; //value to search for
int i = 0;
boolean foundIt = false; //flag to indicate if value is found
for ( ; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break; //exit the for loop when the value has been found
}
}

123
Cont’d …
 The break statement can also be followed by a label name.
 A label name can be placed before any statement or statement block and is
followed by a colon.
 When a break is followed by a label name, the interpreter immediately exits
the named block.
 Taking the example above again – if the array is an array of arrays, then two
for loops are needed to search through all the arrays.
int[][] arrayOfInts = { { 32, 87, 3, 589 },{ 12, 1076, 2000, 8 }, {622, 127, 77, 955}};
int searchfor = 12;
int i = j=0;
boolean foundIt = false;
//label the outer for loop
search:
for ( ; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search; //exit both for loops }
}
}
124
Cont’d …
Continue
 The continue statement causes the interpreter to quit the
current iteration of a loop and start the next one.
 It can only be used in a while, do or for loop.
 Like the break statement, continue can also be labeled.
 When it is not labeled it quits the current iteration of the
innermost loop.
 If it is labeled, it quits the iteration of the labeled loop or, if it is
not a loop, just exits the statement.
 This may be used where some condition indicates that it is not
necessary to execute all of the code in the loop.
 For example, if iterating through an array of objects to carry
out some form of processing one each one, if an array element
is empty or has no value, then the iteration can be exited.

125
Cont’d …
for (int i = 0; i < dataArray.length; i++) Example using label
{ outer:
if ( dataArray[i] = = -1 ) for(int i=1; i<10;i++){
continue; //quit this iteration inner:
process(dataArray[i])' for(int j=1; j<10; j++) {
} if(i*j>50)
continue outer; }
}

 Note that the way in which a new iteration is started differs slightly for for,
while and do-while loops:
 In for loop, the interpreter jumps to the top of the loop – it evaluates the
update expression (here, an increment) and then evaluates the termination
expression.
 In a while loop, the interpreter returns to the top of the loop and evaluates
the loop condition expression again.
 In a do-while loop, the interpreter jumps to the bottom of the loop, to
evaluate the condition expression again.

126
Cont’d …
Return
 The return statement exits from the current method.
 If the method is declared to return a value, the return must be
followed by an expression to be returned.
 The data type of the expression must be the same as the
declared return type of the method.
 If a method is declared to return void, a return statement is not
required – the interpreter will execute the statements until it
reaches the end of the method.
 However, if it is necessary to return from the method before the
last statement, a return statement can be used.

127
Nested Loops
 Nested loops consist of an outer loop and one or more inner loops.
 Each time the outer loop is repeated; the inner loops are
reentered, and started anew.

public class TestNestedLoops


{
public static void main(String[] args)
{
int i, j;
for (i = 1; i <= 6; i++)
{
for (j = 1; j <= i; j++)
System.out.print(j +" ");
System.out.println();
}
}
}
128
Chapter 4
Objects and Classes in Java
Introduction
 In procedural programming, data and operations on the
data are separate.

 Object-oriented programming places data and the


operation that pertain to them within a single entity called
an Object.

 The object-oriented programming approach organizes


in a way that mirrors the real world, in which all objects
are associated with both attributes and activities.

 Object-oriented programming (OOP) involves programming


using objects.
130
Cont’d …
 Using objects improves software reusability and makes
program easier to develop and easier to maintain.

 Programming in java involves thinking in terms of


objects; a Java program can be viewed as a collection
of cooperating objects.

 An object represents an entity in the real world that


can be distinctly identified.

 For example, a student, a desk, a circle, a button, and


even a loan can all be viewed as objects.
131
Object
 An Object can be defined as an instance of a class.

 An object has a unique identity, state, and behaviors.

 The state defines the object, and the behavior defines what the
object does.

 The state of an object consists of a set of data fields (also


known as properties) with their current values.

 The behavior of an object is defined by a set of methods.


Example: A circle object has a data filed, radius, which is
the property that characterizes a circle.
✓ One behavior of a circle is that its area can be computed
using the method getArea().

132
Cont’d …
 If you create a software object that models our television.
 The object would have variables describing the television's
current state, such as
▪ Its status is on,
▪ the current channel setting is 8,
▪ the current volume setting is 23, and
▪ there is no input coming from the remote control.
 The object would also have methods that describe the
permissible actions, such as
▪ turn the television on or off,
▪ change the channel,
▪ change the volume, and
▪ accept input from the remote control.
133
 Objects of the same type are defined using a common class.
 In other words, a class is a blueprint, template, or prototype that
defines and describes the static attributes and dynamic
behaviors common to all objects of the same kind.
 Class is objects with the same attributes and behavior .
 A class can be visualized as a three-compartment box:
▪ Name (or identity): identifies the class.
▪ Variables (or attribute, state, field): contains the static attributes
of the class.
▪ Methods (or behaviour, function, operation): contains the dynamic
behaviours of the class.

134
Cont’d …
 The followings figure shows a few examples of classes:

135
Cont’d …
 An instance is a realization of a particular item of a class.
In other words, an instance is an instantiation of a class.

 All the instances of a class have similar properties, as


described in the class definition.

 For example, you can define a class called "Student" and


create two instances of the class "Student" for "Peter", and
"Paul“.

 The term "object" is often used loosely, which may refer to a


class or an instance.

136
Cont’d …
 The following figure shows two instances of the class Student.

 The above class diagrams are drawn according to the UML


(Unified Modeling Language) notations.
 A class is represented as a 3-compartment box, containing
name, variables, and method.
 Class name is shown in bold and centralized. Instance name is
shown as instanceName:Classname and underlined.
137
Cont’d …

Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

.⚫ Each object within a class retains its own states and


behaviors.
138
Cont’d …
 The relationship between classes and object is analogous to
the relationship between apple recipes and apple pie.
 A single class can be used to instantiate multiple objects.
This means that we can have many active objects or
instances of a class.
 A class usually represent a noun, such as a person, place or
(possibly quite abstract) thing - it is a model of a concept
within a computer program.
 A Java class uses variables to define data fields and methods
to define behaviors.
 Variables and methods are called members of the class.

139
Cont’d …
 Concepts that can be represented by a class:
 Tree
 Building
 Man
 Car
 Animal  Hotel
 Student  Computer Title Attributes
Author / Fields/
 Book  … PubDate Properties
ISBN

setTitle(…)
setAuthor (…)
setPubDate (…)
Methods/
setISBN (…)
Behavior
getTitle (…)
getAuthor (…)

140
Constructors
 Additionally, a class provides a special type of methods,
known as constructors, which are invoked to construct new
objects from the class.
 Constructor is a special method that gets invoked
“automatically” at the time of object creation.
 A constructor can perform any action, but constructors are
designed to perform initializing actions, such as initializing the
data field of objects.
 Constructor is normally used for initializing objects with
default values unless different values are supplied.
 When objects are created, the initial value of data fields is
unknown unless its users explicitly do so.
141
Cont’d …
 In many cases, it makes sense if this initialisation can be
carried out by default without the users explicitly initializing
them.
 For example,
 If you create an object of the class called “Counter”, it is
natural to assume that the counter record-keeping field is
initialized to zero unless otherwise specified differently.
 In Java, this can be achieved though a mechanism called
constructors.

142
Cont’d …
 Constructors has exactly the same name as the defining
class.
 Like regular methods, constructor can be overloaded.(i.e. A
class can have more than one constructor as long as they
have different signature (different input arguments syntax).
✓ This makes it easy to construct objects with different
initial data values.
 Default constructor
✓ If you don't define a constructor for a class, a default
parameterless constructor is automatically created by the
compiler.
✓ The default constructor calls the default parent
constructor (super()) and initializes all instance variables
to default value (zero for numeric types, null for object
references, and false for Booleans).

143
Cont’d …
Differences between methods and constructors.
 Constructors must have the same name as the class itself.
 Constructors do not have a return type—not even void.
 Constructors are invoked using the new operator when an
object is created.
Defining a Constructor
public class ClassName {

// Data Fields…

// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
144
Cont’d …
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Overloading
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
145
Cont’d …
 Defining a Constructor: Example
public class Counter {
int CounterIndex;

// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}

146
Cont’d …
class MyClass {
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
counter1.increase();
int b = counter1.getCounterIndex();
if ( a > b )
counter1.increase();
else
counter1.decrease();

System.out.println(counter1.getCounterIndex());
}
}

147
Cont’d …
A Counter with User Supplied Initial Value ?
 This can be done by adding another constructor method to the
class. public class Counter {
int CounterIndex;

// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
// A New User Class: Utilising both constructors
Counter counter1 = new Counter();
Counter counter2 = new Counter (10);
148
Cont’d …
 Adding a Multiple-Parameters Constructor to our Circle Class
public class Circle
{
public double x,y,r;
// Constructor
public Circle(double centreX, double centreY,double radius)
{
x = centreX;
y = centreY;
r = radius;
}
//Methods to return circumference and area
public double circumference()
{ return 2*3.14*r;
}
public double area()
{ return 3.14 * r * r;
}
} 149
Creating Objects Using Constructors
 Objects are created from classes using new operator
ClassName objectRefVar = new ClassName([parameters]);
OR
ClassName objectRefVar ;
objectRefVar = new ClassName([parameters]);
 The new operator creates an object of type ClassName.
 The variable objectRefVar references the object .
 An object can be created with out using reference variables .
 The object may be created using any of its constructors
 If it has constructors other than the default one
appropriate parameters must be provided to create
objects using them.
150
Cont’d …
Example:
/*Declare a reference variable and create an object using an
empty constructor */
Circle c1 = new Circle();
/*Declare a reference variable and create an object using
constructor with an argument */
Circle c2 = new Circle(5.0)
//Declare reference variables
Circle c3, c4 ;
/*Create objects and refer the objects by the reference
variables
c3 = new Circle();
c4 = new Circle(8.0);

151
Accessing Objects
 Once objects have been created, its data fields can be
accessed and its methods invoked using the dot operator(.),
also known as the object member access operator.
 Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius = 100;
 Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., double area = myCircle.getArea();
 This is why it is called "object-oriented" programming; the
object is the focus.
152
Cont’d …
Circle aCircle = new Circle();
aCircle.x = 10.0; // initialize center and radius
aCircle.y = 20.0
aCircle.r = 5.0;

aCircle = new Circle();


At creation time the center and radius are not
defined. These values are explicitly set later.

Constructors initialise Objects


Circle aCircle = new Circle(10.0, 20.0, 5.0);

aCircle = new Circle(10.5,20.0, 5.0);


aCircle is created with center(10,20) and radius 5

153
Cont’d …
 Sometimes want to initialize in a number of different ways, depending
on circumstance.
 This can be supported by having multiple constructors having different
input arguments.
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centerX, double centerY,double radius)
{
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }

//Methods to return circumference and area


public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
154
Cont’d …
 Initializing with constructors
public class TestCircles {

public static void main(String args[]){


Circle circleA = new Circle( 10.0, 12.0, 20.0);
Circle circleB = new Circle(10.0);
Circle circleC = new Circle();
}
}

circleA = new Circle(10, 12, 20) circleB = new Circle(10) circleC = new Circle()

Centre = (10,12) Centre = (0,0) Centre = (0,0)


Radius = 20 Radius=10 Radius = 1
155
Variables of Primitive Data Types Vs. Object Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c=new Circle() c reference c: Circle

radius = 1

Object type assignment c1 = c2


Primitive type assignment i = j Before: After:
Before: After:
c1 c1

i 1 i 2
c2 c2

i 2 j 2
c1: Circle C2: Circle c1: Circle C2: Circle
radius = 5 radius = 9 radius = 5 radius = 9

156
Garbage Collection
 The object becomes a candidate for automatic garbage
collection.
 Java automatically collects garbage periodically and
releases the memory used to be used in the future.
 That is the JVM will automatically collect the space if
the object is not referenced by any variable.
 As shown in the previous figure, after the assignment
statement c1 = c2, c1 points to the same object referenced
by c2.
 The object previously referenced by c1 is no longer
referenced.
 This object is known as garbage.
 Garbage is automatically collected by JVM.

157
Classes Declaration
 Class declaration has the following syntax
[ClassModifiers] class ClassName [pedigree]
{
//Class body;
}
 Class Body may contain
 Data fields:
[FieldModifier(s)] returnType varName ;

 Constructors:
[Modifiers] ClassName(…){…}

 Member Methods:
[MethodModifier(s)] returnType methodName(…){…}

And even other classes



 Pedigree - extends, implements( …will see it later)
158
Data fields
 Data Fields are variables declared directly inside a class (not
inside method or constructor of a class)
 Data fields can be variables of primitive types or reference
types.
public class Student {
 Example
String name;
int age;
boolean isSci;
char gender;
}

 The default value of a data field is null for a reference type, 0


for a numeric type, false for a boolean type, and '\u0000' for a
char type.
 Data fields can be initialized during their declaration.
 However, the most common way to initialize data fields is inside
constructors.
159
Cont’d …
 Java assigns no default value to a local variable inside a
method.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}

Compilation error: variables not initialized

160
Types of Variables
Local variable: Created inside a method or block of statement
E.g. public int getSum(int a, int b)
{
int sum=0;
sum=a+b; This method has local variables such as a, b, sum.
return sum; Their scope is limited to the method.
}

Instance variable: Created inside a class but outside any method.


Store different data for different objects.
E.g.
public class Sample1 {
int year; This method has two instance variables year and month.
int month;
public void setYear(int y)
O1
{ year=y;} Instance
… variable

} Each object has its own data for the instance variable O2
Instance
161 variable
Cont’d …
Static variable: Created inside a class but outside any method. Store
one data for all objects/instances.
E.g. public class Sample {
static int year;
This class has one static variable: year
int month;
public static void setYear(int y) {
year=y;}
Shared by
…} all objects/
instances
• Static/class variables store O1 O4
values for the variables in
common memory location. O5
• Because of this common O2 Static
variable
location, all objects of the
same class are affected if one O6
O stands for
object changes the value of a
Object
static variable. O3

162
Cont’d …
 We define class variables by including the static keyword
before the variable itself.
Example: class FamilyMember {
static String surname = "Johnson";
String name;
int age;
... }

 Instances of the class FamilyMember each have their own


values for name and age.

 But the class variable surname has only one value for all family
members.

 Change surname, and all the instances of FamilyMember are


affected.
163
Static/Class methods
 Class methods, like class variables, apply to the class as a
whole and not to its instances.

 Class methods are commonly used for general utility


methods that may not operate directly on an instance of
that class, but fit with that class conceptually.

 For example, the class method Math.max() takes two


arguments and returns the larger of the two.

 You don't need to create a new instance of Math; just call


the method anywhere you need it, like this:

int LargerOne = Math.max(x, y);

164
Cont’d …
 Good practice in java is that, static methods should be
invoked with using the class name though it can be invoked
using an object.
ClassName.methodName(arguments)

OR

objectName.methodName(arguments)

 General use for java static methods is to access static fields.

165
Cont’d …
 Constants in class are shared by all objects of the class.
Thus, constants should be declared final static.
Example: The constant PI in the Math class is defined as:
final static double PI = 3.14159265
 Static variables and methods can be used from instance or
static method in the class.
 Instance variables and methods can only be used from
instance methods, not from static methods.
 Static variables and methods belong to the class as a whole
and not to particular objects.

166
Cont’d …
Example:
public class Foo{
int i=5;
Static int k = 2;
public static void main(String[] args)
{ int j = i; // wrong i is instance variable
m1(); //wrong m1() is an instance method
}
public void m1()
{
//Correct since instance and static variables and can be used in an instance method.
i = i + k + m2(int i,int j);
}
public static int m2(int I, int j)
{ return (int)(Math.pow(i,j)); }
}167
Modifiers in Java
 Java provides a number of access modifiers to help you set the
level of access you want for classes as well as the fields,
methods and constructors in your classes.
 Access modifiers are keywords that help set the visibility and
accessibility of a class, its member variables, and methods.
 Determine whether a field or method in a class, can be used or
invoked by another method in another class or subclass.

Could one class Class Name2


Class Name1 directly access
Attribute area another class’s Attribute area
methods or
attributes?
Method area Method area

Encapsulation
168
Cont’d …
 Access Modifiers
▪ private
▪ protected
▪ no modifier (also sometimes referred as ‘package-
private’ or ‘default’ or ‘friendly’ access. )
▪ public

 Modifiers are applied by prefixing the appropriate keyword


for the modifier to the declaration of the class, variable,
method or constructor.
 Combinations of modifiers may be used in meaningful ways.
 The two levels are class level access modifiers and member
level access modifiers.

169
Cont’d …
1. Class level access modifiers (java classes only)
 Only two access modifiers is allowed, public and no modifier
 If a class is ‘public’, then it CAN be accessed from
ANYWHERE.
 If a class has ‘no modifer’, then it CAN ONLY be accessed
from ’same package’.

2. Member level access modifiers (variables and


methods)
 All the four public, private, protected and no modifer is
allowed.

170
Cont’d …
public access modifier
 The class, data, or method is visible to any class in any package.
 Fields, methods and constructors declared public (least
restrictive) within a public class are visible to any class in the
Java program, whether these classes are in the same package or
in another package.
private access modifier
 The private (most restrictive) fields or methods can be
accessed only by the declaring class.
 Fields, methods or constructors declared private are strictly
controlled, which means they cannot be accesses by anywhere
outside the enclosing class.
 A standard design strategy is to make all fields private and
provide public getter and setter methods for them to read and
modify.
171
Cont’d …
protected access modifier
 The protected fields or methods cannot be used for classes in
different package.
 Fields, methods and constructors declared protected in a
superclass can be accessed only by subclasses in other
packages.
 Classes in the same package can also access protected fields,
methods and constructors as well, even if they are not a
subclass of the protected member’s class.
No modifier (default access modifier)
 Java provides a default specifier which is used when no
access modifier is present.
 Any class, field, method or constructor that has no declared
access modifier is accessible only by classes in the same
package.
172
Cont’d …
 For better understanding, member level access is formulated as a
table:

Same Other
Access Same Class Subclass
Package packages
Modifiers
public Y Y Y Y

protected Y Y Y N
no access
Y Y N N
modifier
private Y N N N

173
Cont’d …
Modifier Used on Meaning

class Contains unimplemented methods and cannot be


instantiated.
Abstract interface All interfaces are abstract. Optional in declarations

method No body, only signature. The enclosing class is


abstract
class Cannot be subclassed

method Cannot be overridden and dynamically looked up


Final
field Cannot change its value. static final fields are
compile-time constants.
variable Cannot change its value.
native method Platform-dependent. No body, only signature

174
Cont’d …
class Accessible only in its package
None
(package) interface Accessible only in its package
member Accessible only in its package
class Make an inner class top-level class.

method A class method, invoked through the class


name.
static field A class field, invoked through the class
name one instance, regardless of class
instances created.
initializer Run when the class is loaded, rather than
when an instance is created.
private member Accessible only in its class(which defines it).

175
Cont’d …
class Accessible anywhere

public interface Accessible anywhere

member Accessible anywhere its class is.

protected member Accessible only within its package and its


subclasses
class All methods in the class are implicitly
strictfp.

method All floating-point computation done is


strictfp strictly conforms to the IEEE 754 standard.
All values including intermediate results
must be expressed as IEEE float or double
values. It is rarely used.

176
Cont’d …
method For a static method, a lock for the class is
synchronized acquired before executing the method.
For a non-static method, a lock for the
specific object instance is acquired.

transient field Not be serialized with the object, used with


object serializations.

volatile field Accessible by unsynchronized threads, very


rarely used.

•The table(matrix) in the next slide shows java modifiers indicating


summary of which modifier to which element can be applied.

177
Cont’d …

178
Cont’d …
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }

package p1; package p2;


class C1 { public class C2 { public class C3 {
... can access C1 cannot access C1;
} } can access C2;
}
179
This Keyword
 Within an instance method or a constructor, this is a reference
to the current object (the object whose method or constructor
is being called)
 Use this to refer to the object that invokes the instance
method.

180
Cont’d …
 The most common reason for using the this keyword is
because a field is shadowed by a method or constructor
parameter. (to avoid name conflicts.)
 Use this to refer to an instance data field. For example,
the Point class was written like this.
public class Point
{
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b)
{ x = a;
y = b; }
}
181
Cont’d …
but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor public
Point(int x, int y)
{ this.x = x;
this.y = y;
} As we can see in the program that we have
} declare the name of instance variable and local
variables same. Now to avoid the confliction
182 between them we use this keyword.
Example
Class
Name

Data Filelds

Constructors

Initializing attributes

183
Cont’d …
 From within a constructor, you can also use the this keyword to call
another constructor in the same class. Doing so is called an explicit
constructor invocation.
 Use this to invoke an overloaded constructor of the same class.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle()
{ this(0, 0, 0, 0); }
public Rectangle(int width, int height)
{ this(0, 0, width, height); }
public Rectangle(int x, int y, int width, int height)
{ this.x = x;
this.y = y;
this.width = width;
184 this.height = height; } }
Cont’d …
 The no-argument constructor calls the four-argument
constructor with four 0 values.

 The two-argument constructor calls the four-argument


constructor with two 0 values.

 As before, the compiler determines which constructor to call,


based on the number and the type of arguments.

 If present, the invocation of another constructor must


be the first line in the constructor.

185
Cont’d …

186
Getters and Setters Method
 A class’s private fields can be manipulated only by
methods of that class.
 So a client of an object—that is, any class that calls the
object’s methods—calls the class’s public methods to
manipulate the private fields of an object of the class.
 Classes often provide public methods to allow clients of
the class to set (i.e., assign values to) or get (i.e., obtain
the values of) private instance variables.
 The names of these methods need not begin with set or
get, but this naming convention is highly recommended in
Java.
187
Cont’d …
public class Circle {
private double x,y,r;
public double getX() { return x;}
public double getY() { return y;}
public double getR() { return r;}
public void setX(double x_in) { x = x_in;}
public void serY(double y_in) { y = y_in;}
public void setR(double r_in) { r = r_in;}
//Methods to return circumference and area
}
 Better way of initialising or access data members x, y, r
 To initialise/Update a value: aCircle.setX( 10 )
 To access a value: aCircle.getX()
 These methods are informally called as Accessors or Setters/Getters
Methods.

188
Chapter 5
OOP Concepts

189
Introduction
 The three fundamental object oriented programming
principles are:

 Encapsulation (data hiding) and Data abstraction

 Inheritance

 Polymorphism

 Main purpose of these principles is to manage


software system complexity by improving software
quality factors.

190
Encapsulation
Encapsulation refers to the combining of fields and
methods together in a class such that the methods
operate on the data, as opposed to users of the class
accessing the fields directly. Class

 It is a the technique which


involves making the fields in a
class private and providing
access to the fields via public Fields/Data

methods.

191
Cont’d …
 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.
 The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
code of others who use our code.

192
Cont’d …
public class EncapTest{ public void setAge( int newAge)
private String name; { age = newAge;
private String idNum; }
private int age; public void setName(String newName)
public int getAge() {
{ name = newName;
return age; }
} public void setIdNum( String newId)
public String getName() {
{ idNum = newId;
return name; }
} }
public String getIdNum()
{
return idNum;
}

193
Cont’d …
 The public methods are the access points to this class’s
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.
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge());
} Out Put:
} Name : James Age : 20
194
Data Abstraction
 Classes normally hide the
details of their
implementation from their
clients. This is called
information hiding.
 The client cares about what
functionality a class offers, not
about how that functionality is
implemented. This concept is
referred to as data abstraction.

195
Inheritance
 Object-Oriented Programming (OOP): allows you to
derive new classes from existing classes. This is called
inheritance.
 In other words, Inheritance is a way to form new
classes using classes that have already been defined.
 A class C1 extended from another class C2 is called a
subclass, and C2 is called a superclass.
 A superclass is also referred to as a supertype, a parent
class, or a base class and subclass as subtype, a child
class, an extended class, or derived class.

196
Cont’d…
 A subclass
✓ May inherit accessible data fields and methods from its
superclass (the immediate parent and all its Ancestors).
✓ May add new data fields and methods.
✓ May also override an inherited method by
providing its own version, or hide an inherited variable by
defining a variable of the same.
▪ Sometimes it is necessary for the subclass to modify
the implementation of a method defined in the
superclass.
▪ This is referred to as method overriding.
197
Cont’d…
 Inheritance is employed to help reuse existing code with
little or no modification.
 The inheritance relationship of subclasses and super
classes gives rise to a hierarchy.
 With the use of inheritance the information is made
manageable in a hierarchical order.

Inheritance Hierarchy for Shapes


198
Cont’d…
 Elements to be inherited from parent class are
protected and public members.
 Private members of the superclass are not
inherited by the subclass and can only be indirectly
accessed.
 Members that have default accessibility in the
superclass are also not inherited by subclasses in
other packages.
 These members are only accessible by their
simple names in subclasses within the same
package as the superclass.
199
Cont’d…
Elements to be inherited form parent class:

➢ Protected Members Attributes

Methods

Attributes
➢ Public Members
Methods

 An instance method can be overridden only if it is


accessible.
 Thus a private method cannot be overridden, because it is
not accessible outside its own class.
 If a method defined in a subclass is private in its
superclass, the two methods are completely unrelated.
200
Cont’d…
Applications of inheritance
 Specialization
 The new class or object has data or behavior aspects
that are not part of the inherited class.
 Overriding
 Permit a class or object to replace the implementation of
an aspect—typically a behavior—that it has inherited
 Code re-use
 Re-use of code which already existed in another class.

201
Cont’d…
 In Java inheritance is represented by the key word extends.
Syntax
modifier class SubclassName extends SuperclassName
{ //body }
Example
public class Mammal extends Animal
{ //body }

 The inheritance relationship is transitive:


 if class x extends class y, then a class z, which extends class
x, will also inherit from class y.
public class Animal{ …}
public class Mammal extends Animal{…}
public class Reptile extends Animal{…}
public class Dog extends Mammal{…}
202
Cont’d…
 Now based on the above example, In Object Oriented
terms following are true:
✓ Animal is the superclass of Mammal and Reptile classes.
✓ Mammal and Reptile are subclasses of Animal class.
✓ Dog is the subclass of both Mammal and Animal classes.
 A very important fact to remember is that Java only
supports only single inheritance. This means that a class
cannot extend more than one class.
 Therefore the following is illegal:
public class Dog extends Animal, Mammal{…}

203
Cont’d…
Types of Inheritance

Multiple and Hybrid inheritance is not supported in Java through class.


204
Cont’d…
public class Student
{
protected String name;

public Student()
{ name = “”; }
public Student(String s)
{ name = s; }
public String getName()
{
return name;
}
}
Note: Object is the super class of all Java Classes.
205
Cont’d…
 The instanceof operator compares an object to a specified type.

 You can use it to test if an object is an instance of a class, an


instance of a subclass, or an instance of a class that implements
a particular interface.

public class Dog extends Mammal{


public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
} Output: true true true
}
206
Cont’d…
class Animal
{ public int numberOfLegs;
public void talk()
{ System.out.println("Hello"); }
}
class Dog extends Animal
{ public int numberOfFleas;
public Dog()
{ numberOfLegs = 4;
numberOfFleas = 10; }
public void bark() {
System.out.println("Woof woof"); }
public void scratch() {
if (numberOfFleas > 0) numberOfFleas--; }}
207
Cont’d…
Dog d=new Dog();

d.bark();

d.scratch();

System.out.println(d.numberOfFleas);

 Because the Dog class inherits from the Animal class, we


can also use the d reference to access the methods and
properties of the Animal class. Use the code below.
d.talk();
System.out.println(d.numberOfLegs);

208
Super Keyword
 When extending a class you can reuse the immediate
superclass constructor and overridden superclass
methods by using the reserved word super.

 The keyword super refers to the superclass of the class


in which super appears. This keyword can be used in
three ways:
▪ To call a superclass method
▪ To call a superclass constructor
▪ To access a hidden data fields

209
Cont’d…
 Unlike data fields and methods, a superclass's constructors are
not inherited in the subclass.
 They can only be invoked from the subclasses' constructors,
using the keyword super.
 If the keyword super is not explicitly used, the superclass‘s
no-arg constructor is automatically invoked.
 You must use the keyword super to call the superclass
constructor.
 Invoking a superclass constructor’s name in a subclass causes a
syntax error.
 Java requires that the statement that uses the keyword super
appear first in the constructor.
210
Cont’d…
Example
class A{
public int a, b, c;
public A(int p, int q, int r)
{
a=p;
b=q;
c=r;
}
public void Show()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}// end of class A
211
Cont’d…
public class B extends A{
public int d;
public B(int l, int m, int n, int p){
super(l, m, n);
d=p;
}
public void Show(){
super.Show()
System.out.println("d = " + d);
}
public static void main(String args[])
{ Output
B b = new B(4,3,8,7); a=4
b.Show(); b=3
} c=8
}//end of class B d=7
212
Constructor Chaining
➢ A constructor may invoke an overloaded constructor or its
superclass’s constructor.
➢ If none of them is invoked explicitly, the compiler puts super()
as the first statement in the constructor. For example,

public A() { is equivalent to public A() {


} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

▪ Constructing an instance of a class invokes all the super


classes' constructors along the inheritance chain. This is called
Constructor Chaining.
213
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
//*********************************************************************
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
//************************************************************************
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}

214
animation
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
} Start from the
public Faculty() { main method
System.out.println("(4) Faculty's no-arg constructor is
invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is
invoked");
}
public Employee(String s) {
System.out.println(s); }
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
215
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
} Invoke Faculty
public Faculty() { constructor
System.out.println("(4) Faculty's no-arg constructor is
invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is
invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
216
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
Invoke Employee’s no-
class Employee extends Person { arg constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
217
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
} Invoke Employee(String)
class Employee extends Person {
constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
218
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
} Invoke Employee(String)
class Employee extends Person {
constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
219
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
} Invoke Person()
class Person {
constructor
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

220
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

221
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
Execute println

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
222
}
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
223
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person { Execute println
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
224
Inheritance Example

225
Inheritance Example …

226
Inheritance Example …

227
Inheritance Example …

228
Cont’d…
 You can also use super to refer to a hidden field.

 Within a class, a field that has the same name as a field in


the superclass hides the superclass's field, even if their
types are different.

 Within the subclass, the field in the superclass cannot be


referenced by its simple name. Instead, the field must
be accessed through super.

 Generally speaking, we don't recommend hiding fields


as it makes code difficult to read.

229
Final Classes and Methods
 We may want to prevent classes from being extended. In such
case , use the final modifier to indicate that a class is final and
cannot be a parent class.
 You might wish to make a method final if the method has an
implementation that should not be changed.
 All methods in a final class are implicitly final.
 A final class cannot be extended. This is done for reasons of
security and efficiency. Accordingly, many of the Java standard
library classes are final.
Example: java.lang.System, java.lang.Math and java.lang.String.
 You cannot override final methods, methods in final classes,
private methods or static methods.

230
Abstract Classes and Methods
 Abstract classes are like regular classes with data and
methods, but we cannot create instance of abstract classes
using the new operator.
 An abstract class is one that cannot be instantiated.
 Classes that can be instantiated are known as concrete
classes.
 If a class is abstract and cannot be instantiated, the class does
not have much use unless it is subclassed. This is typically
how abstract classes come about during the design phase.
 Use the abstract keyword to declare a class abstract. The
keyword appears in the class declaration somewhere before the
class keyword.
231
Example
public abstract class Employee
{ private String name, address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{ System.out.println("Inside Employee computePay");
return 0.0;
}
232
Cont’d…
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing a check to " + name + " "+ address);
}
public String toString()
{ return name + " " + address + " " + number; }
public String getName() { return name;}
public String getAddress() { return address; }
public void setAddress(String newAddress){ address = newAddress;}
public int getNumber(){ return number;}
}// end of class Employee

 When you would compile, using instances of Employee class, above


class then you would get following error:
Employee is abstract; cannot be instantiated
233
Cont’d…
public class Salary extends Employee
{ private double salary; //Annual salary
public Salary (String name, String address, int number, double salary)
{ super(name, address, number);
setSalary(salary); }
public void mailCheck()
{ System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() + " with
salary " + salary);
}
public double getSalary() { return salary; }
public void setSalary(double newSalary)
{ if(newSalary >= 0.0)
{ salary = newSalary; } }
public double computePay()
{ System.out.println("Computing salary pay for " +
getName()); return salary/52; }}

234
Cont’d…
 Here we cannot instantiate a new Employee, but if we instantiate
a new Salary object, the Salary object will inherit the three fields
and seven methods from Employee.
public class AbstractDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd ", "Ambehta, UP“, 3, 3600.00);
Employee e = new Salary("John ", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
} 235
Cont’d…
 This would produce following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.

236
Cont’d…
 If you want a class to contain a particular method
but you want the actual implementation of that
method to be determined by child classes, you can
declare the method in the parent class as abstract.
 The abstract keyword is also used to declare a
method as abstract.
 An abstract methods consist of a method
signature, but no method body - its signature is
followed by a semicolon, not curly braces as usual.

237
Cont’d…
An Abstract Class Example
 In an object-oriented drawing application, you can draw circles,
rectangles, lines, Bezier curves, and many other graphic objects.
 These objects all have certain states (for example: position,
orientation, line color, fill color) and behaviors (for example:
moveTo, rotate, resize, draw) in common.
 Some of these states and behaviors are the same for all graphic
objects—for example: position, fill color, and moveTo.
 Others require different implementations—for example, resize or
draw.
➢ All GraphicObjects must know how to draw or resize
themselves; they just differ in how they do it.
 This is a perfect situation for an abstract superclass.

238
Cont’d…
 The GraphicObject class can look something like this:
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY){...}
abstract void draw();
abstract void resize();
}
 Each non-abstract subclass of GraphicObject, such as Circle and
Rectangle, must provide implementations for the draw and resize
methods:
class Circle extends GraphicObject {
void draw(){... }
void resize(){...}
}
class Rectangle extends GraphicObject {
void draw(){...}
void resize(){...}
}
239
Cont’d…
 Abstract classes contain mixture of non-abstract and abstract
methods.
 If a class has at least one abstract method, then the class must
be declared abstract.
 static, private, and final methods cannot be abstract, since
these types of methods cannot be overridden by a subclass.
 Similarly, a final class cannot contain any abstract methods.
 Declaring a method as abstract has two results:
 The class must also be declared abstract. If a class contains an
abstract method, the class must be abstract as well.
 When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class.
However, if it does not, the subclass must also be declared abstract.
240
Cont’d…
public abstract class Employee{
private String name, address;
private int number;
public abstract double computePay();
…//remainder of the class definition
}
public class Salary extends Employee{
private double salary; //Annual salary
public double computePay(){
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
…//remainder of the class definition
}
241
Interfaces
 Interfaces are similar to abstract classes but all methods
are abstract and all data fields are static final.

 That is an interface is a collection of abstract methods


and static final variables.

 An interface is not a class. Writing an interface is similar to


writing a class, but they are two different concepts.

 A class describes the attributes and behaviors of an


object. An interface contains behaviors that a class
implements.

242
Cont’d…
 Interfaces have the following properties:
 An interface is implicitly abstract. You do not need to use the
abstract keyword when declaring an interface.
 Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
 Methods in an interface are implicitly public.
 Interfaces can be inherited (i.e. you can have a sub-interface). As with
classes the extends keyword is used for inheritance.
 A class implements an interface, thereby inheriting the abstract
methods of the interface.
 Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.
 A concrete class may implement one or several interfaces, supplying
the code for all the methods.
243
Cont’d…
 An interface is similar to a class in the following ways:

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension,
with the name of the interface matching the name of the
file.
 The bytecode of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding
bytecode file must be in a directory structure that
matches the package name.

244
Cont’d…
 However, an interface is different from a class in several
ways, including:

 You cannot instantiate an interface.

 An interface does not contain any constructors.

 All of the methods in an interface are abstract.

 An interface cannot contain instance fields.

 An interface is not extended by a class; it is implemented by


a class.

 An interface can extend multiple interfaces.

245
Declaring Interface
 The interface keyword is used to declare an
interface.
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

246
Implementing Interface
 A class uses the implements keyword to implement an interface.
 The implements keyword appears in the class declaration following the extends portion of
the declaration.
interface Animal {
public void eat();
public void travel();
}
public class Mammal implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels"); }
public int noOfLegs(){
return 0; }
public static void main(String args[]){
Mammal m = new Mammal();
m.eat();
m.travel(); Output:
} Mammal eats
} Mammal travels
247
Extending Interfaces
 An interface can extend another interface, similarly to the way
that a class can extend another class.
 The extends keyword is used to extend an interface, and the
child interface inherits the methods of the parent interface.
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
248
Cont’d…
public interface Hockey extends Sports{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
 The Hockey interface has four methods, but it inherits
two from Sports; thus, a class that implements
Hockey needs to implement all six methods.
 Similarly, a class that implements Football needs to define the
three methods from Football and the two methods from Sports.
 Note that an interface can extend more than one parent
interface
public interface Hockey extends Sports, Event
249
Cont’d…

subclass superclass
or extends or
derived class base class

subinterface extends superinterface

class implements interface

250
Cont’d…
 In Java, a subclass can extend only one superclass.
 In Java, a subinterface can extend several superinterface.
 In Java, a class can implement several interfaces — this is Java’s
form of multiple inheritance.
 An abstract class can have code for some of its methods; other
methods are declared abstract and left with no code.
 An interface only lists methods but does not have any code.
 A concrete class can redefine some of the methods defined
higher in the hierarchy.
 Inheritance plays a dual role:
 A subclass reuses the code from the superclass.
 A subclass (or a class that implements an interface) inherits the data
type of the superclass (or the interface) as its own secondary type.
251
Abstract Vs. Inheritance
 Unlike interfaces, abstract classes can contain fields that are not
static and final, and they can contain implemented methods.
 If an abstract class contains only abstract method declarations,
it should be declared as an interface instead.
 Multiple interfaces can be implemented by classes anywhere in
the class hierarchy, whether or not they are related to one
another in any way.
 By comparison, abstract classes are most commonly subclassed
to share pieces of implementation.
 A single abstract class is subclassed by similar classes that have
a lot in common (the implemented parts of the abstract class),
but also have some differences (the abstract methods).
252
Polymorphism
 The inheritance relationship enables a subclass to inherit
features from its superclass with additional new features.
 A subclass is a specialization of its superclass.
 Every instance of a subclass is an instance of its superclass,
but not vice versa.
 A subclass possesses all the attributes and operations of its
superclass (because a subclass inherited all attributes and
operations from its superclass).
 This means that a subclass object can do whatever its
superclass can do.

253
Cont’d…
 Polymorphism (from the Greek, meaning “many forms”) is
the ability of an object to take on many forms.

 All interaction with an object occurs through object


reference variables.

 An object reference variable holds the reference (address,


the location) of an object.

 An object reference can refer to an object of its class, or


to an object of any class derived from it by inheritance.

254
Cont’d…
 For example, if the Holiday class is used to derive a child class
called Christmas, then a Holiday reference could actually be
used to point to a Christmas object.
 For example,

Holiday
Holiday day;
day = new Holiday();
Christmas …
day = new Christmas();

The assignment of an object of a derived class to


a reference variable of the base class can be
considered as a widening conversion.
255
Cont’d…
class Holiday
{
public void celebrate()
{…}
}
//************************

class Christmas extends Holiday


{
public void celebrate()
{…}
public void listenToChristmasSongs()
{…}
}
Can we do the following statements?
Holiday day;
day = new Christmas(); day.celebrate();
day.listenToChristmasSongs();
256
Cont’d…
 The most common use of polymorphism in OOP occurs
when a parent class reference is used to refer to a child
class object.
 A reference variable can be of only one type. Once
declared the type of a reference variable cannot be
changed.
 The reference variable can be reassigned to other objects
provided that it is not declared final.
 The type of the reference variable would determine the
methods that it can invoke on the object.
 A reference variable can refer to any object of its declared
type or any subtype of its declared type.
257
Polymorphism Example
public class Shape{
public double computeArea(){ return -1; }
public double computeCircumfrence(){ return -1; }
}
public class Circle extends Shape{
private double radius;
public Circle(double r){ this.radius = r; }
public double computeArea(){
return Math.PI*this.radius * this.radius;
}
public double computeCircumfrence(){
return 2*Math.PI*this.radius;
}
}
258
Example …
public class Rectangle extends Shape{
private double width;
private double height;
public Rectangle(double w, double h){
this.width = 0;
this.height = 0;
}
public double computeArea(){
return this.width * this.height;
}
public double computeCircum(){
return 2*(this.width *this.height);
}
}
259
Example …
public class ShapeTest{
public static void main(String args[]){
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(4.0);
shapes[1] = new Rectangle(5, 3);
shapes[2] = new Circle(1.8);
double totalArea = 0;
for(int i = 0;i<shapes.length;i++){
totalArea+=shapes[i].computeArea(); }
System.out.println(“Total area = “ +totalArea); }
}
Out Put: Total area = 60.44424265506762
 A reference variable of type Shape is used to refer objects of types of its
subclasses (Circle and rectangle)
 What is the output of the above code if you comment out computeArea()
method in Circle and Rectangle classes? Out Put: Total area = -3.0
260
Cont’d…
 When a superclass variable contains a reference to a
subclass object, and that reference is used to call a
method, the subclass version of the method is called. (See
the example on shapes).
 Suppose an object o is an instance of class c1,c2, ….cn-1
and cn, where c1 is subclass of c2, c2 is subclass of
c3,….and cn-1 is a subclass of cn.
 That is cn is the most general class and c1 is the most
specific class. In java cn is the Object class.
 If o invokes a method m ,the JVM searches the
implementation for m in c1,c2,…cn-1 and cn in this order,
until it is found.
261
Cont’d…
 The output illustrates that the appropriate methods for
each class are indeed invoked based on the type of the
object to which shapes refers. This is called dynamic
binding or late binding.
 However, if a program needs to perform a subclass-specific
operation on a subclass object referenced by a superclass
variable, the program must first cast the superclass
reference to a subclass reference through a technique
known as downcasting.
 This enables the program to invoke subclass methods that
are not in the superclass.
262
Cont’d…
 Substituting a subclass instance for its superclass is called
"upcasting".
 Upcasting is always safe because a subclass instance possesses
all the properties of its superclass and can do whatever its
superclass can do.
 You can revert a substituted reference back to the original
subclass. This is called "downcasting".
 For example,
Shape shape = new Circle(5.0);// upcast is safe
Circle aCircle = (Circle)shape; //downcast
//downcast needs the casting operator

263
Cont’d…
 For Example if a Rectangle class had getDiagonal() method and if
we want to use this method we must first downcast it.
if(shapes[1] instanceOf Rectangle)
Rectangle r = (Rectangle)shapes[1];
 We cannot treat a superclass object as a subclass object because a
superclass object is not an object of any of its subclasses.
 Assigning a superclass variable to a subclass variable (without an
explicit cast) is a compilation error.
 Downcasting requires explicit type casting operator in the form of
prefix operator (new‐type).
 Downcasting is not always safe, and throws a runtime
ClassCastException if the instance to be downcasted does not
belong to the correct subclass.
 A subclass object can be substituted for its superclass, but the
reverse is not always true.
264
Cont’d…
 It is possible to display each shape’s type as a string.
for(int i = 0;i<shapes.length;i++){
System.out.printf( “Shape %d is a %s\n", i,
shapes[ i].getClass().getName());
}
 The output is
Shape 0 is a Circle
Shape 1 is a Rectangle
Shape 2 is a Circle

265
Cont’d…
 Polymorphism can also be achieved through method
overriding and method overloading.
 Overridden methods
 Are methods that are redefined within an inherited or
subclass. They have the same signature and the subclass
definition is used.
 The implementation in the subclass overrides (replaces)
the implementation in the superclass.
 In other words an instance method in a subclass with the
same signature (name, plus the number and the type of its
parameters) and return type as an instance method in the
superclass overrides the superclass's method.
266
Method Overriding Example
class Rectangle
{
private int x, y, w, h;
public String toString()
{
return “x = “ + x + “, y = “ + y +“, w = “ + w + “,h = “ + h;
}
}
class DecoratedRectangle extends Rectangle
{
private int borderWidth;
public String toString()
{
return super.toString() + “,borderWidth =“ + borderWidth;
}
}
267
Method Overriding Rules
 The argument list should be exactly the same as that of the
overridden method.
 The return type should be the same or a subtype of the
return type declared in the original overridden method in
the super class.
 The access level cannot be more restrictive than the
overridden method's access level.
For example: if the super class method is declared public
then the overriding method in the subclass cannot be either
private or protected.

268
Cont’d…
 However the access level can be less restrictive than the
overridden method's access level.
 Instance methods can be overridden only if they are inherited
by the subclass.
 Constructors cannot be overridden.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be
re-declared. If a method cannot be inherited then it cannot be
overridden.
 A subclass within the same package as superclass can
override any superclass method that is not declared private or
final.
 A subclass in a different package can only override the non-
final methods declared public or protected.
269
Cont’d…
 Method Overloading
 Overloaded methods are methods with the same name
signature but either a different number of parameters or
different types in the parameter list.
 Compiler automatically select the most appropriate method
based on the parameter supplied.
Example
public class MultiplyNumbers {
public int Multiply(int a, int b)
{
return a * b;
}
public int Multiply(int a, int b, int c)
{
return a*b*c;
}
}
270
Package
 A Package (named collections of classes) can be defined as a
grouping of related types(classes and interfaces) providing
access protection and name space management.
 Packages are used in Java in-order to prevent naming conflicts,
to control access, to make searching/locating and usage of
classes, interfaces, enumerations and annotations easier etc.
 Java has numerous built in packages: java.io, java.lang,
java.util …
 Programmers can define their own packages to bundle group of
classes/interfaces etc.
 It is a good practice to group related classes implemented by
you so that a programmers can easily determine that the
classes, interfaces, enumerations, annotations are related.
271
Creating package
 When creating a package, you should choose a name for
the package and put a package statement with that
name at the top of every source file that contains the
classes and interfaces 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.

272
Cont’d …
 It is common practice to use lowercased names of packages
to avoid any conflicts with the names of classes, interfaces.
 If a class wants to use another class in the same package,
the package name does not need to be used.
 Classes in the same package find each other without any
special syntax.
 A class file can contain any number of import statements.
 The import statements must appear after the package
statement and before the class declaration.
 Let us look at an example that creates a package called
animals.
273
Cont’d …
package animals;
interface Animal
{ public void eat();
public void travel();}
package animals;
public class MammalInt implements Animal{
public void eat(){ System.out.println("Mammal eats");}
public void travel(){ System.out.println("Mammal travels");}
public int noOfLegs(){ return 0; }
public static void main(String args[]){
{ MammalInt m = new MammalInt();
m.eat();
m.travel(); }
}
274
Cont’d …
 Here a class named Boss is added to the payroll package
that already contains Employee.
 The Boss can then refer to the Employee class without
using the payroll prefix, as demonstrated by the following
Boss class.
package payroll;
public class Boss{
public void payEmployee(Employee e)
{ e.mailCheck();
}
}

275
Cont’d …
 If Boss was not in the payroll package, then use one of the
following techniques for referring to a class in a different
package.
 The fully qualified name of the class can be used.
For example: payroll.Employee
 The package can be imported using the import keyword
and the wild card (*).
For example: import payroll.*;
 The class itself can be imported using the import
keyword.
For example: import payroll.Employee;

276
Passing Objects
 Passing by value for primitive type value
 The value is passed to the parameter
 Passing by value for reference type value
 The value is the reference to the object
 Example
public class TestPassObject {
public static void main(String[] args) {
int radius =1;
Circle3 myCircle = new Circle3(1);
int n = 5;
printAreas(myCircle, n);
System.out.println("\n" + "Radius is+myCircle.getRadius());
System.out.println("n is " + n); } }
277
Cont’d …
public static void printAreas(Circle3 c, int times) {
System.out.println("Radius \t\tArea");
while (times >= 1) {
System.out.println(c.getRadius() + "\t\t" +
c.getArea());
c.setRadius(c.getRadius() + 1);
times--;
}
}
}
 A reference type of Circle3 called c is passed to a
function printAreas()

278
Cont’d …
public class BirthDate{
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay){
year = newYear;
month = newMonth;
day = newDay;
}
public void setYear(int newYear)
{
year = newYear;
}
}
279
Cont’d …
public class Student {
private int id;
private BirthDate birthDate;
public Student(int ssn,int year, int month, int day)
{ id = ssn;
birthDate = new BirthDate(year, month, day);
}
public int getId() { return id;} BirthDate is returned
public BirthDate getBirthDate() { return birthDate;}
}

public class Test {


public static void main(String[]args{
Student student = new
Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}}
280
Chapter 6

Exception Handling

281
Introduction
 There are three categories of errors: syntax errors,
runtime errors, and logic errors.
 Syntax errors:- arise because the rules of the language
have not been followed. They are detected by the
compiler.
 Runtime errors:- occur while the program is running if
the environment detects an operation that is impossible
to carry out.
 Logic errors:- occur when a program doesn't perform
the way it was intended to.
 This chapter introduces using exception handling to deal
with runtime error.
282
Cont’d…
 An exception is a problem that arises during the execution of a
program. It is a representation of an error condition or a
situation that is not the expected result of a method/program.
 An exception can occur for various reasons:
 Attempting to divide by zero (arithmetic exception)
 Reading a decimal value when an integer is expected (number
format exception)
 Attempting to write to a file that doesn't exist (I/O exception).
 Access an element past the end of an array.
(ArrayIndexOutOfBoundsException)
 or referring to a nonexistent character in a string
(StringIndexOutOfBounds exception).
 Invoke a method on a reference variable with null value.
(NullPionterException)
 A network connection has been lost in the middle of
communications, or the JVM has run out of memory.
283
Cont’d…
 Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have
failed in some manner.
 No matter how well-designed a program is, there is always the
chance that some kind of error will arise during its execution.
 A program that does not provide code for catching and handling
exceptions will terminate abnormally, and may cause serious
problems.
 A well-designed program should include code to guard against
errors and other exceptional conditions when they arise.
 This code should be incorporated into the program from the very
first stages of its development. That way it can help identify
problems during development.
 In Java, the preferred way of handling such conditions is to use
exception handling - a divide-and-conquer approach that
separates a program's normal code from its error-handling code.
284
Java’s Exception Hierarchy
 The Java class library contains a number of predefined exceptions.
 All exception classes are subtypes of the java.lang.Exception class.
 The exception class is a subclass of the Throwable class. Other than
the exception class there is another subclass called Error which is
derived from the Throwable class.
 The Throwable class is contained in the java.lang package and
subclass of Throwable are contained in various packages.
 Example: Errors related to GUI components are included in the
java.awt
 Errors are not normally trapped from the Java programs. These
conditions normally happen in case of severe failures, which are not
handled by the java programs.
 Errors are generated to indicate errors generated by the runtime
environment.
 Example : JVM is out of Memory. Normally programs cannot recover
from errors.
285
Java’s Exception Classes

ClassNotFoundExceptio
n

IOException
ArithmeticExceptio
n
Exception AWTException
NullPointerExceptio
n
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError

Error
AWTError

Several more classes

286
Some Common Exceptions

287
Cont’d…

288
Categories of Exception
 To understand how exception handling works in Java, you need
to understand the three categories of exceptions:
 Checked Exceptions:
 A checked exception is one that can be analyzed (can’t be
ignored) by the Java compiler.
 That is when the compiler encounters one of these exceptions
it checks whether the program either handles or declares the
exception.
 A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the
programmer.
 For example, if a file is to be opened, but the file cannot be
found, an exception occurs.
289
Cont’d…
 Runtime Exceptions
 Runtime exception is an exception that occurs that probably
could have been avoided by the programmer.
 As opposed to checked exceptions, runtime exceptions are
ignored at the time of compilation (Unchecked).
 Runtime Exception is caused by programming errors, such
as bad casting, accessing an out-of-bounds array, and numeric
errors.
 Errors:
 These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer.
 Errors are typically ignored in your code because you can
rarely do anything about an error.
 For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation (Unchecked).
290
Cont’d…
• Errors are thrown by JVM and represented in the Error class. The Error
class describes internal system errors. Such errors rarely occur. If one
does, there is little you can do beyond notifying the user and trying to
terminate the program gracefully.
• Runtime Exception, Error and their subclasses are known as
unchecked exceptions.
• All other exceptions are known as checked exceptions, meaning that
the compiler forces the programmer to check and deal with the
exceptions.

291
Exception Handling
 Exception handling is the technique of catching the
exceptions that might be thrown some time in the future
during runtime.
 Exceptions can be handled in traditional way of handling
errors within a program with Java's default exception-
handling mechanism or using Exception class defined in
Java API.

292
Cont’d…
 Traditional way of Handling Errors
 Consider the following example

public double avgFirstN(int N)


{
int sum = 0;
for(int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0?
}

293
Cont’d…
public double avgFirstN(int N) {
int sum = 0;
if (N <= 0) {
System.out.println("ERROR avgFirstN: N <= 0. Program terminating.");
System.exit(0);
} The error-handling code is built
for (int k = 1; k <= N; k++) right into the algorithm
sum += k;
return sum/N; // What if N is 0?
} // avgFirstN()

 This method has several problems


 programmer must remember to always check the return
value and take appropriate action. This requires much
code (methods are harder to read) and something may get
overlooked.
294
Cont’d…
How do you handle exceptions?

 Java exception handling is managed via five keywords:


try, catch, throw, throws, and finally.

 Java exception handling is a mechanism for handling


exception by detecting and responding to exceptions in
a systematic, uniform and reliable manner.

 Exception handling is accomplished through the “try –


catch” mechanism, or by a “throws or throw” clause
in the method declaration.
295
Cont’d…

method1() { declare exception


method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}

Try-Catch Mechanism
 Wherever your code may trigger an exception, the normal code logic
is placed inside a block of code starting with the “try” keyword:
 After the try block, the code to handle the exception should it arise is
placed in a block of code starting with the “catch” keyword.
 You might like to think of these as "try to do this task" and if
there is an exception "catch the exception and do something
about it".
 A try/catch block is placed around the code that might generate
an exception.
296
Cont’d…
 Code within a try/catch block is referred to as protected
code.
 You may also write an optional “finally” block. This block
contains code that is ALWAYS executed, either after the
“try” block code, or after the “catch” block code.
 Finally blocks can be used for operations that must
happen no matter what (i.e. cleanup operations such as
closing a file)
 Generally, the try statement contains and guards a block
of statements.

297
Cont’d…
 Syntax of try catch
try {
codes that may throw exception(s)
}
catch (exception_type1 identifier){
//how do you want to deal with this
exception
}
catch (exception_type2 identifier){
//how do you want to deal with this
exception
}
// you can use multiple catches to handle
different exceptions

298
Cont’d…
 A catch statement involves declaring the type of
exception you are trying to catch.
 If an exception occurs in protected code, the catch block
(or blocks) that follows the try is checked.
 If the type of exception that occurred is listed in a catch
block, the exception is passed to the catch block much as
an argument is passed into a method parameter.
 Only one catch block, that is the first applicable one, will
be executed.
 If no exceptions arise during the execution of the try
block, the catch blocks are skipped.
299
Cont’d…
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
If an exception occurs on this line,
the rest of the lines in the method // Display the result
are skipped and the program is System.out.println(
terminated. "The number entered is " + number);
}}
Terminated.

300
Cont’d…
import java.util.*;
public class HandleExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
If an exception occurs on this line,
the rest of lines in the try block are // Display the result
skipped and the control is
System.out.println(
transferred to the catch block.
"The number entered is " + number);
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
scanner.nextLine(); // discard input
}
} while (continueInput);
}}

301
Cont’d…
Example:
java import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try
{
int a[] = new int[2];
System.out.println("Access element three :"+ a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
302
Coding Exception
Example

Output: Exception thrown :


java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
303
Cont’d…
 Suppose the main method invokes method1, method1
invokes method2, method2 invokes method3, and an
exception occurs in method3 .

main method { method1 { method2 { An


... ... ...
try { try {
exception
try {
... ... ... is thrown
invoke method1; invoke method2; invoke method3; in method3
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }

304
Cont’d…
 If method3 cannot handle the exception, method3 is
aborted and the control is returned to method2.
 If the exception type is Excetion3, it caught by the catch
block for handling exception ex3 in method2. Statement5
is skipped, and statement6 is executed.
 If exception type is not Exception1, Exception2, or
Exception3, the exception is not caught and the program
terminates. Statement1 and Statement2 are not executed.

305
Cont’d…
 A catch block will catch exceptions of the class specified,
including any exceptions that are subclasses of the one
specified. The order in which exceptions are specified in catch
blocks is important.
 A compilation error will result if a catch block for a superclass
type appears before a catch block for a subclass type .
 A more specific catch block must precede a more general one in the
source. Failure to meet this ordering requirement causes a compiler
error.
try { ..….. try {
} ..…..
catch(Exception ex){ }
……. catch(RuntimeException ex){
} ……
catch (RuntimeException ex){ }
…….. catch (Exception ex ) {
……..
}
}
(a) Wrong order (b) Correct Order

306
Cont’d…
The finally Keyword
 The finally keyword is used to create a block of code that
follows a try block.
 A finally block of code always executes, whether or not an
exception has occurred.
 Using a finally block allows you to run any cleanup-type
statements that you want to execute, no matter what
happens in the protected code.
 A finally block appears at the end of the catch blocks and
has the following syntax:

307
Cont’d…
try
{ codes that may throw exception(s) }
catch (exception_type1 identifier)
{ //how do you want to deal with this exception}
catch (exception_type2 identifier)
{ //how do you want to deal with this exception}
// you can use multiple catches to handle different exceptions
finally
{ // code that must be executed under successful or unsuccessful
conditions
}
 The finally block always executed regardless an exception or
not except the following conditions:
 The death of the thread
 The use of System.exit( )
 Turning off the power to the CPU
 An exception arising in the finally block itself

308
Cont’d…
Example:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally {
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
} }}

Output:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
309
Cont’d…
Note the followings:

 A catch clause cannot exist without a try statement.

 It is not compulsory to have finally clauses when


ever a try/catch block is present.

 The try block cannot be present without either catch


clause or finally clause.

 Any code cannot be present in between the try,


catch, finally blocks.

310
Cont’d…
The throws/throw Keywords:
 In any method that might throw an exception, you may
declare the method as “throws” that exception, and thus
avoid handling the exception yourself.
 The throws keyword appears at the end of a method's
signature.
public void myMethod()throws IOException
Example
public void myMethod throws IOException {
normal code with some I/O
}
 Every method must declare the types of checked
exceptions it might throw using throws keyword.

311
Cont’d…
 A method can declare that it throws more than one
exception, in which case the exceptions are declared in
a list separated by commas.

public void myMethod() throws Exception1,


Exception2, …. ExceptionN

 Java forces you to deal with checked exceptions.


 If a method declares a checked exception (i.e., an
exception other than Error or RuntimeException), you must
invoke it in a try-catch block or declare to throw the
exception in the calling method.

312
Cont’d…
Example: Suppose that method p1 invokes method p2 and
p2 may throw a checked exception (e.g., IOException).

void p1() {
try
void p1() throws IOException
{
{
p2();
p2();
}
}
catch (IOException ex)
{
...
}
}

313
Cont’d…
 When the program detects an error, the program can
create an instance of an appropriate exception type and
throw it by using the throw keyword.
 Here is an example,
throw new TheException();

TheException ex = new TheException();


throw ex;
Example;
public void openFile(String fileName) throws IOException
{ open the file using the input file name;
if (can not open file) throw new IOException();
read the file,
}

314
Cont’d…
 In general, each exception class in the java API has
at least two constructor: a no-arg constructor, and a
constructor with a String arguments that describes the
exception.
 This argument is called the exception message, which can
be obtained using getMessage().
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
315
Cont’d…
Getting Information from Exception

 An Exception object contains valuable information about


the exception. You may use the following instance
methods in the java.lang.Throwable class to get
information regarding the exception.

public String getMessage()

 Returns the message of this object or null if there is no


detail message.

316
Cont’d…
public String toString()
 Returns the concatenation of three strings:
The full name of the exception class
+
“:” (colon and space)
+
The getMessage() method.
public void printStackTrace()
 Prints the Throwable object and its call stack trace
information on the console.

317
Declaring your own Exception
 You can create your own exceptions in Java. Keep the
following points in mind when writing your own exception
classes:
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is
automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
 If you want to write a runtime exception, you need to
extend the RuntimeException class.
 You can define our own Exception class as below:
class MyException extends Exception{ …}
318
Cont’d…
 You just need to extend the Exception class to create your own
Exception class. These are considered to be checked
exceptions.
 The following InsufficientFundsException class is a user-
defined exception that extends the Exception class, making it
a checked exception.
import java.io.*;
public class InsufficientFundsException extends Exception{
private double amount;
public InsufficientFundsException(double amount){
this.amount = amount;
}
public double getAmount(){
return amount;
}
}
319
Cont’d…
 To demonstrate using our user-defined exception, the following
CheckingAccount class contains a withdraw() method that
throws an InsufficientFundsException.
import java.io.*;
public class CheckingAccount{
private double balance;
private int number;
public CheckingAccount(int number)
{ this.number = number; }
public void deposit(double amount)
{ balance += amount; }
public double getBalance()
{ return balance; }
public int getNumber()
{ return number; }
320
Cont’d…
public void withdraw(double amount) throws
InsufficientFundsException {
if(amount <= balance) {
balance-= amount;
}
else{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
}
 The following BankDemo program demonstrates invoking the
deposit() and withdraw() methods of CheckingAccount.
321
Cont’d…
public class BankDemo{
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e) {
System.out.println("Sorry, but you are short $“ +
e.getAmount());
e.printStackTrace();
}
}
}
322
Cont’d…
 Compile all the above three files and run BankDemo, this
would produce following result.
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

323
Cont’d…
 Instead of using Java's e.getMessage() method to print errors
during the debugging process, you can get more information
about the error process if you print a stack trace from the
exception.
 The snippet of source code shown below shows how to print the
stack trace.
try {
// try to open the non-existent file
} catch (IOException e) {
// you handle the exception here
e.printStackTrace();
}
• As a final point - don't forget the e.getMessage() method -
because the error message is not automatically printed to the
screen.
324
Chapter 7
Java Applet

325
Overview of Java Applet
 An applet is a small Java program that is embedded and
ran in some other Java interpreter program such as

 a Java technology-enabled browser

 Sun’s applet viewer program called appletviewer

 An applet can be a fully functional Java application


because it has the entire Java API at its disposal.

 Applet is a special type of program that is embedded in


the webpage to generate the dynamic content. It runs
inside the browser and works at client side.

326
Cont’d…
 Advantage of Applet
 There are many advantages of applet. They are as
follows:
 It works at client side so less response time.
 Secured.
 It can be executed by browsers running under many
plate-forms, including Linux, Windows, Mac OS etc.
 Drawback of Applet
 Plugin is required at client browser to execute applet.

327
Applet Vs. Application
 There are some important differences between an applet and a
standalone Java application, including the following:
 An applet is a Java class that extends the java.applet.Applet
class.
 A main() method is not invoked on an applet, and an applet
class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the
code for the applet is downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-
in of the Web browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet
class and invokes various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web
browser.
328
Applet Life Cycle
 The following methods in the Applet class gives you the
framework on which you build any serious applet:
 init
 This method is intended for whatever initialization is needed
for your applet. This method is invoked when the applet is
first loaded.
 It should be used to carry out tasks that need to happen once
during the lifetime of the applet e.g.load an image, set up the
screen display for the applet.
 start
 This method is automatically called after the browser calls the
init method.
 It is also called whenever the user returns to the page
containing the applet after having gone off to other pages.
329
Cont’d…
 Stop
 This method is automatically called when the user moves off
the page on which the applet sits.
 It can, therefore, be called repeatedly in the same applet.
 destroy
 This method is only called when the browser shuts down
normally.
 Because applets are meant to live on an HTML page, you
should not normally leave resources behind after a user
leaves the page that contains the applet.
 Paint
 Invoked immediately after the start() method, and also any
time the applet needs to repaint itself in the browser.
 The paint() method is actually inherited from the java.awt.

330
A "Hello, World" Applet
 Following is a simple applet named HelloWorldApplet.java:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{ public void paint (Graphics g)
{ g.drawString ("Hello World", 25, 50);
} }
 These import statements bring the classes into the scope of our
applet class:
 java.applet.Applet
 java.awt.Graphics
 Without those import statements, the Java compiler would not
recognize the classes Applet and Graphics, which the applet
class refers to.
331
The Applet Class
 Every applet is an extension of the java.applet.Applet class.
 The base Applet class provides methods that a derived Applet
class may call to obtain information and services from the
browser context.
 These include methods that do the following:
 Get applet parameters
 Get the network location of the HTML file that contains the
applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
332
Cont’d…
 Additionally, the Applet class provides an interface by which the
viewer or browser obtains information about the applet and
controls the applet's execution. The viewer may:
 Request information about the author, version, and copyright
of the applet
 Request a description of the parameters the applet recognizes
 Initialize the applet
 Destroy the applet
 Start the applet's execution
 Stop the applet's execution
 The Applet class provides default implementations of each of
these methods. Those implementations may be overridden as
necessary.
 The "Hello, World" applet is complete as it stands. The only
method overridden is the paint method.
333
Invoking an Applet
 An applet may be invoked by embedding directives in an HTML
file and viewing the file through an applet viewer or Java-
enabled browser.
 The <applet> tag is the basis for embedding an applet in an
HTML file. Following is an example that invokes the "Hello,
World" applet.
<html>
<title>The Hello, World Applet
</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World" message would
appear here.
</applet>
<hr>
</html>

334
Cont’d…
 Note − You can refer to HTML Applet Tag to understand more
about calling applet from HTML.
 The code attribute of the <applet> tag is required. It specifies
the Applet class to run. Width and height are also required to
specify the initial size of the panel in which an applet runs. The
applet directive must be closed with an </applet> tag.
 Non-Java-enabled browsers do not process <applet> and
</applet>.
 Therefore, anything that appears between the tags, not related
to the applet, is visible in non-Java-enabled browsers.

335
Cont’d…
 The viewer or browser looks for the compiled Java code at the
location of the document. To specify otherwise, use the
codebase attribute of the <applet> tag as shown −
 <applet codebase = "https://amrood.com/applets" code =
"HelloWorldApplet.class"width = "320" height = "120">

 If an applet resides in a package other than the default, the


holding package must be specified in the code attribute using
the period character (.) to separate package/class components.
For example:
 <applet = "mypackage.subpackage.TestApplet.class" width = "320"
height = "120">

336
Cont’d
 Swing:
 The Swing package is a part of the Java Foundation Classes
(JFC) in the Java platform.
 JFC is designed to help programmers build GUI’s for
applications.
 It includes components such as buttons, windows and tables
for use in interfaces. The Swing classes are in the javax.swing
package.
 Applets can be created using Swing classes.
 AWT (Abstract Window Toolkit):
 Prior to Swing, AWT provided components for user interfaces.
 The AWT classes are in the java.awt package.
337
Cont’d…
 The Applet class inherits from AWT classes – as shown in the
inheritance hierarchy below (java.lang.Object is the top-level super
class).
 Applets can also make use of the Swing classes, but only by extending
the Japplet subclass of the Applet class.

338
Applet Animation Example
Write the following Applet code and save with SimpleAnimation.java
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class SimpleAnimation extends Applet{
public void paint(Graphics g){
int a=150, b=150, c=10,d=10;
g.setColor(Color.red);
for(int i=0;i<15;i++){
try{ Thread.sleep(1000);
}catch(InterruptedException ex){}
g.drawOval(a,b,c,d);
a-=10;
b-=10;
c+=8;
d+=8;} } }

339
Cont’d…
Then Write the following HTML code and saved with Example.html
<html>
<body>
<applet code="SimpleAnimation.class"width="500" height="500" >
</applet>
To Compile and run use the following command
</body> 1. Compile: javac SimpleAnimation.java
</html> 2. Run: appletviewer Example.html

Output

340

You might also like