0% found this document useful (0 votes)
68 views79 pages

CMP 301 (NEW) Object Oriented Programming Langauage I

Computer Science related courses PDF documents

Uploaded by

7fkvm22rbs
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)
68 views79 pages

CMP 301 (NEW) Object Oriented Programming Langauage I

Computer Science related courses PDF documents

Uploaded by

7fkvm22rbs
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/ 79

CMP301: OBJECT-ORIENTED PROGRAMMING LANGAUGE (3 UNITS)

COURSE CONTENTS
Basic OOP Concepts: classes, objects, inheritance, polymorphism, Data abstraction, tools for
developing, compiling, interpreting and debugging, java programs, java syntax and data
objects, operators. Central flow constructs, objects and classes programming, arrays, methods,
exception, applets and the abstract, OLE, persistence, window toolkit, laboratory exercises in
an OOP language.
OBJECTIVES:
1. To teach the student the concepts of object oriented and procedure programming.
2. To differentiate between the basic OOP concepts of classes, objects, methods,
encapsulation, inheritance, polymorphism, data abstraction and method overloading.
3. To implement the basic concepts of OOP.
4. To design applications using JAVA syntax and data objects.
5. To teach student to implement arrays, exception handling, GUI and Windows.
LEARNING OUTCOMES
The students should be able to:
1. Differentiate the principles of object-oriented programming and procedural
programming.
2. Outline the essential features and elements of the Java programming language.
3. Explain programming fundamentals, including statement and control flow and
recursion.
4. Codes basic programs in Java programming language.
5. Uses objects and classes.
6. Lists the object-oriented programming concepts.
7. Codes object-oriented programs.
8. Explains and handles exceptions.
9. Writes multithreaded Java programs.
10. Understands the concepts of database and database management systems.
11. Uses generic classes and methods.

TEXT BOOK(S):
1. Object Oriented Programming and Java by Danny Poo, Derek Kiong and Swarnalatha Ashok
2. Java How To Program (9ed.) Deitel.

Course Writer/Developer: Dr. F.E. AYO, Department of Computer Sciences, Olabisi


Onabanjo University, Ago-Iwoye, Ogun State.

E-mail: [email protected]
1.0 BASIC OOP CONCEPTS
Object Oriented Programming (OOP) allows us to decompose a problem into a number of
entities called objects and then builds data and methods around these entities.
DEFINIION: OOP is a programming paradigm based upon objects (having both data and
methods) that aims to incorporate the advantages of modularity and reusability. Objects, which
are usually instances of classes, are used to interact with one another to design applications and
computer programs.
The important characteristics of OOP are:
i. Bottom–up approach in program design
ii. Programs organized around objects, grouped in classes
iii. Focus on data with methods to operate upon object’s data
iv. Interaction between objects through methods
v. Better abstraction (modelling data and methods together)
vi. Better maintainability (more comprehensible, less fragile)
vii. Better reusability design through creation of new classes by adding features to existing
classes.
Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi,
C#, Perl, Python, Ruby, and PHP etc.
Procedure Oriented Programming (POP)
In this approach, the problem is always considered as a sequence of tasks to be done. A number
of functions are written to accomplish these tasks. Here primary focus is on functions and little
attention on data.
There are many high-level languages like COBOL, FORTRAN, PASCAL, and C used for
conventional programming commonly known as POP.
Difference between POP and OOP
POP OOP
1. Program is divided into small parts called Program is divided into parts called objects.
functions.
2. Importance is not given to data but to Importance is given to the data rather than
functions as well as sequence of actions to procedures or functions because it works
be done. as a real world.
3. Follows Top Down approach. OOP follows Bottom Up approach.
4. It does not have any access specifier. OOP has access specifiers named Public,
Private, Protected, etc.
5. Data can move freely from function to Objects can move and communicate with
function in the system. each other through member functions.
6. To add new data and function in POP is OOP provides an easy way to add new data
not so easy. and function.
7. Most function uses Global data for sharing In OOP, data cannot move easily from
that can be accessed freely from function function to function, it can be kept public or
to function in the system. private so we can control the access of data.
8. It does not have any proper way for hiding OOP provides Data Hiding so provides
data so it is less secure. more security.
9. Overloading is not possible. In OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading.
10. Examples of POP are : C, VB, Examples of OOP are : C++, JAVA,
FORTRAN, Pascal, etc. VB.NET, C#.NET, Python, etc.

1.1 Benefits of OOPs


1. Reusability: In OOP programs, functions and modules that are written by a user can be
reused by other users without any modification.
2. Inheritance: Through this we can eliminate redundant code and extend the use of
existing classes.
3. Data Hiding: The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secure programs.
4. Reduced complexity of a problem: The given problem can be viewed as a collection
of different objects. Each object is responsible for a specific task. The problem is solved
by interfacing the objects. This technique reduces the complexity of the program
design.
5. Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing
code as new objects can be created with small differences to existing ones. Software
complexity can be easily managed.
6. Message Passing: The technique of message communication between objects makes
the interface with external systems easier.
7. Modifiability: it is easy to make minor changes in the data representation or the
procedures in an OOP. Changes inside a class do not affect any other part of a program,
since the only public interface that the external world has to a class is through the use
of methods
2.0 BASIC STRUCTURE OF JAVA LANGUAGE
2.1 Java Overview
Java is a simple and yet powerful OOP language and it is in many respects similar to C. Java
originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was
developed to provide a platform-independent programming language.
JAVA is the world’s most widely used computer programming language. Like any
programming language, the Java language has its own structure, syntax rules, and programming
paradigm. The Java language's programming paradigm is based on the concept of OOP, which
the language's features support.
The Java language is a C-language derivative, so its syntax rules look much like C's. For
example, code blocks are modularized into methods and delimited by braces ({ and }), and
variables are declared before they are used.
Structurally, the Java language starts with packages. A package is the Java language's
namespace mechanism. Within packages are classes, and within classes are methods, variables,
constants, and more.
2.2 Java Environment Setup
Before we proceed further, it is important that we set up the Java environment correctly. This
section guides you on how to download and set up Java on your machine. Please follow the
following steps to set up the environment.
• Download a version of Java Development Kit (JDK) based on your operating system.
• Run the .exe to install Java on your machine.
• Download and install an editor.
• Create a java program.
The first step in creating a Java program is by writing your programs in a text editor- Integrated
Development Environment (IDE). Examples of text editors you can use are notepad,
NetBeans and Eclipse, etc. This file is stored in a disk file with the extension .java.
After creating and saving your Java program, compile the program by using the Java Compiler.
The output of this process is a file of Java bytecodes with the file extension .class. The .class
file is then interpreted by the Java interpreter known as Java virtual Machine (JVM) that
converts the bytecodes into the machine language of the particular computer.
Java popular editors:
To write your Java programs, you will need a text editor. There are even more sophisticated
IDEs available in the market. But for now, you can consider one of the following:
• Notepad– On Windows machine, you can use any simple text editor like Notepad.
• BlueJ – www.bluej.org (freeware)
• NetBeans – www.netbeans.org (freeware/open-source)
• JCreator – www.jcreator.com (freeware version available, pro version purchase
required)
• Eclipse – www.eclipse.org (freeware/open-source)
• IntelliJ IDEA – www.jetbrains.com (trial/purchase required)
• JBuilder – www.borland.com (trial/purchase required)
2.3 Basic Syntax
Let us look at a simple code that would print the words Welcome to Java Programming!.
1 // Fig. 2.1: Welcome1.java
2 // Text-printing program.
3
4 public class Welcome1
5{
6 // main method begins execution of Java application
7 public static void main( String[] args )
8 {
9 System.out.println( "Welcome to Java Programming!" );
10 } // end method main
11 } // end class Welcome1

Fig. 2.1 | Text-printing program.

Commenting Your Programs


We insert comments to document programs and improve their readability. The Java compiler
ignores comments, so they do not cause the computer to perform any action when the program
is run.
By convention, we begin every program with a comment indicating the figure number and file
name. The comment in line 1 begins with //, indicating that it is an end-of-line comment—it
terminates at the end of the line on which the // appears.
// Fig. 2.1: Welcome1.java

Declaring a Class
Line 4 begins a class declaration for class Welcome1. Every Java program consists of at least
one class that you (the programmer) define. The class keyword introduces a class declaration
and is immediately followed by the class name (Welcome1). Keywords (sometimes called
reserved words) are reserved for use by Java and are always spelled with all lowercase letters.
public class Welcome1

Class Names and Identifiers


By convention, class names begin with a capital letter and capitalize the first letter of each word
they include (e.g., SampleClassName). A class name is an identifier—a series of characters
consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit
and does not contain spaces. Some valid identifiers are Welcome1, $value, _value,
m_inputField1 and button7. The name 7button is not a valid identifier because it begins with a
digit, and the name input field is not a valid identifier because it contains a space. Normally,
an identifier that does not begin with a capital letter is not a class name. Java is case sensitive—
uppercase and lowercase letters are distinct—so value and Value are different (but both valid)
identifiers.
A left brace (as in line 5), {, begins the body of every class declaration. A corresponding right
brace (at line 11), }, must end each class declaration. Lines 6–10 are indented.
Declaring a Method
Line 6
// main method begins execution of Java application
is an end-of-line comment indicating the purpose of lines 7–10 of the program. Line 7
public static void main( String[] args )
is the starting point of every Java application. The parentheses after the identifier main indicate
that it’s a program building block called a method. Java class declarations normally contain
one or more methods. For a Java application, one of the methods must be called main and must
be defined as shown in line 7; otherwise, the Java Virtual Machine (JVM) will not execute the
application. Methods perform tasks and can return information when they complete their tasks.
Keyword void indicates that this method will not return any information. Later, we’ll see how
a method can return information. For now, simply mimic main’s first line in your Java
applications. In line 7, the String[] args in parentheses is a required part of the method main’s
declaration.
The left brace in line 8 begins the body of the method declaration. A corresponding right brace
must end it (line 10). Line 9 in the method body is indented between the braces.

Performing Output with System.out.println


Line 9 instructs the computer to perform an action—namely, to print the string of characters
contained between the double quotation marks (but not the quotation marks themselves). A
string is sometimes called a character string or a string literal. White-space characters in strings
are not ignored by the compiler. Strings cannot span multiple lines of code, but as you’ll see
later, this does not restrict you from using long strings in your code.
System.out.println( "Welcome to Java Programming!" );
The System.out object is known as the standard output object. It allows a Java applications to
display information in the command window from which it executes.
Method System.out.println displays (or prints) a line of text in the command window. The
string in the parentheses in line 9 is the argument to the method. When System.out.println
completes its task, it positions the output cursor (the location where the next character will be
displayed) at the beginning of the next line in the command window. This is similar to what
happens when you press the Enter key while typing in a text editor—the cursor appears at the
beginning of the next line in the document.
The entire line 9, including System.out.println, the argument "Welcome to Java Programming!"
in the parentheses and the semicolon (;), is called a statement. A method typically contains one
or more statements that perform its task. Most statements end with a semicolon. When the
statement in line 9 executes, it displays Welcome to Java Programming! in the command
window
About Java programs, it is very important to keep in mind the following points.
• Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
• Class Names - For all class names, the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case. Example class MyFirstJavaClass.
• Method Names - All method names should start with a Lower-Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case. Example public void myMethodName().
• Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match your program will not compile). Example: Assume 'MyFirstJavaProgram'
is the class name, then the file should be saved as'MyFirstJavaProgram.java'
• public static void main(String args[]) - Java program processing starts from the
main() method, which is a mandatory part of every Java program.

2.4 Java Identifiers


All Java components require names. Names used for classes, variables and methods are called
identifiers. In Java, there are several points to remember about identifiers. They are as follows:
• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
• After the first character, identifiers can have any combination of characters.
• A keyword cannot be used as an identifier.
• Most importantly identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value
• Examples of illegal identifiers: 123abc, -salary
2.5 Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There
are two categories of modifiers:
• Access Modifiers: default, public, protected, private
• Non-access Modifiers: final, abstract, strictfp
2.6 Java Keywords
Keywords are reserved words in Java. The following list shows the reserved words in Java.
These reserved words may not be used as constant or variable or any other identifier names.
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw Throws
transient try void volatile while

2.7 Comments in Java


Comments are notes written to a code for documentation purposes. Those text are not part of
the program and does not affect the flow of the program.
Java supports three types of comments: C++-style single line comments, C-style multiline
comments and special javadoc comments.
1. C++-Style single line comments. The single line comments starts with //. All the text
after // are treated as comments. For example,
// This is a C++ style or single line comments
2. C-Style multiline comments. The multiline comments starts with a /* and ends with a
*/. All text in between the two delimiters are treated as comments. Unlike C++ style
comments, it can span multiple lines. For example,
/* this is an example of a
C style or multiline comments */
3. Special Javadoc Comments. The special Javadoc comments are used for generating an
HTML documentation for your Java programs. You can create javadoc comments by
starting the line with /** and ending it with */. Like C-style comments, it can also span
lines. It can also contain certain tags to add more information to your comments. For
example,
/**
This is an example of special java doc comments used for \n
generating an html documentation. It uses tags like:
@author Florence Balagtas @version 1.2
*/

2.8 Basic Data Types


Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory. Based on the data type of a variable,
the operating system allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store integers, decimals, or
characters in these variables. There are two data types available in Java:
• Primitive Data Types
• Reference/Object Data Type
Primitive Data Types
There are eight primitive data types supported by Java. Primitive data types are predefined by
the language and named by a keyword.
1. Byte. Byte data type is an 8-bit signed two's complement integer.
2. Short. Short data type is a 16-bit signed two's complement integer.
3. Int. Int data type is a 32-bit signed two's complement integer.
4. Long. Long data type is a 64-bit signed two's complement integer.
5. Float. Float data type is a single-precision 32-bit IEEE 754 floating point.
6. Double. double data type is a double-precision 64-bit IEEE 754 floating point.
7. Boolean. boolean data type represents one bit of information.
8. Char. char data type is a single 16-bit Unicode character.
Reference Data Types
Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed. For
example, Employee, Puppy, etc.
• Class objects and various types of array variables come under reference data type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of the declared type or any
compatible type.
• Example: Animal animal = new Animal("giraffe");

2.9 Variable Types


A variable provides us with named storage that our programs can manipulate. Each variable in
Java has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable. You must declare all variables before they can be used. The basic
examples of a variable declaration are shown here:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
There are three kinds of variables in Java:
• Local variables
• Instance variables
• Class/static variables
Local variables:
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables so local variables should be declared and
an initial value should be assigned before the first use.
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to
this method only.
public class Test{
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
This would produce the following result:
Puppy age is: 7
Example:
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
Instance variables:
• Instance variables are declared in a class, but outside a method, constructor or any
block.
• When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
• Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access
modifiers.
• Instance variables have default values. For numbers the default value is 0, for Booleans
it is false and for object references it is null. Values can be assigned during the
declaration or within the constructor.
• Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods and different class (when instance variables are given
accessibility) should be called using the fully qualified name.
ObjectReference.VariableName.
Example:
import java.io.*;
public class Employee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This would produce the following result:
name : Ransika
salary :1000.0
Class/static variables:
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never
change from their initial value.
• Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
• Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally values can be assigned in special
static initializer blocks.
• Static variables can be accessed by calling with the class
name.ClassName.VariableName.
• When declaring class variables as public static final, then variables names (constants)
are all in upper case. If the static variables are not public and final the naming syntax is
the same as instance and local variables.
Example:
import java.io.*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}
This would produce the following result:
Development average salary:1000
Note: If the variables are access from an outside class the constant should be accessed as
Employee.DEPARTMENT

2.10 Basic Operators


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
• Arithmetic Operators-Arithmetic operators are used in mathematical expressions in the
same way that they are used in algebra. Examples include: +, -, *, /, %, ++, --
• Relational Operators- This include: ==, !=, >, <, >=, <=
• Bitwise Operators-Java defines several bitwise operators, which can be applied to the
integer types, long, int, short, char, and byte. Bitwise operator works on bits and
performs bit-by-bit operation. Examples include & Binary AND, | Binary OR, ^ Binary
XOR,~ Binary NOT, etc.
• Logical Operators- Examples are &&, ||, !, etc.
• Assignment Operators-The following assignment operators are supported by Java
language:
Operator Description Example
Simple assignment operator, Assigns values from right C = A + B will assign
=
side operands to left side operand value of A + B into C
Add AND assignment operator, It adds right operand to C += A is equivalent
+=
the left operand and assign the result to left operand to C = C + A
Subtract AND assignment operator, It subtracts right
C -= A is equivalent
-= operand from the left operand and assign the result to left
to C = C - A
operand
Multiply AND assignment operator, It multiplies right
C *= A is equivalent
*= operand with the left operand and assign the result to left
to C = C * A
operand
Divide AND assignment operator, It divides left operand C /= A is equivalent
/=
with the right operand and assign the result to left operand to C = C / A
Modulus AND assignment operator, It takes modulus C %= A is equivalent
%=
using two operands and assign the result to left operand to C = C % A

• Misc Operators-There are few other operators supported by Java Language.


Conditional Operator (?:):
Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator is
to decide which value should be assigned to the variable. The operator is written as:
variable x =(expression)? value iftrue: value iffalse
Following is the example:
public class Test{
public static void main(String args[]){
int a , b;
a =10;
b =(a ==1)?20:30;
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}

This would produce the following result:


Value of b is:30
Value of b is:20

instanceof Operator:
This operator is used only for object reference variables. The operator checks whether
the object is of a particular type(class type or interface type).
instanceof operator is written as:
(Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A
check for the class/interface type on the right side, then the result will be true. Following
is the example:
String name = “James”;
boolean result = name instanceof String; // This will return true since name is type of
String.
This operator will still return true if the object being compared is the assignment
compatible with the type on the right. Following is one more
Example:
Class Vehicle{
}
public class Car extends Vehicle{
public static void main(String args[]){
Vehicle ab =new Car();
boolean result = ab instanceof Car;
System.out.println(result);
}
}
This would produce the following result:
True

3.0 CONTROL STRUCTURE


Normally, statements in a program are executed one after the other in the order in which they’re
written. This process is called sequential execution. Various Java statements, which we’ll soon
discuss, enable you to specify that the next statement to execute is not necessarily the next one
in sequence. This is called transfer of control.
Advantages of control structure in OOP
1. Shorter development times
2. More frequent on-time delivery of systems
3. More frequent within-budget completion of software projects.
All programs could be written in terms of only three control structures:
• the sequence structure
• the selection structure and
• the repetition structure.
The sequence structure
The sequence structure is built into Java. Unless directed otherwise, the computer executes
Java statements one after the other in the order in which they’re written—that is, in sequence.
The activity diagram in Fig. 3.1 illustrates a typical sequence structure in which two
calculations are performed in order. Java lets you have as many actions as you want in a
sequence structure.

Fig. 3.1 | Sequence structure activity diagram.

The selection structure


Java has three types of selection statements.
• The if-single selection statement either performs (selects) an action, if a condition is
true, or skips it, if the condition is false. In Fig. 3.2, if the grade is greater than or equal
to 60, the program prints “Passed,” then transitions to the activity’s final state. If the
grade is less than 60, the program immediately transitions to the final state without
displaying a message.

Example:
Class SingleSelection{
public static void main(String args[]){
int grade;
if(grade>=60)
System.out.println(“passed”);
}
}

Fig. 3.2 | if single-selection statement UML activity diagram.

• The if…else double selection statement performs an action if a condition is true and
performs a different action if the condition is false. Figure 3.3 illustrates the flow of
control in the if…else statement.
Class DoubleSelection{
public static void main(String args[]){
int grade;
if(grade>=60){
System.out.println(“passed”);
}else{
System.out.println(“failed”);
}
}
}

Fig. 3.3 | if…else double-selection statement UML activity diagram.


• The switch multiple selection statement performs one of many different actions,
depending on the value of an expression.
Example:
Class Switch{
public static void main(String args[]){
int grade;
switch (grade){
case 1:
if(grade>=70)
System.out.println(“A”);
break;
case 2:
if(grade>=60)
System.out.println(“B”);
break;
case 3:
if(grade>=50)
System.out.println(“C”);
break;
case 4:
if(grade>=45)
System.out.println(“D”);
break;
default:
System.out.println( "F" );
break;

}// end switch

}
}

Figure 3.4 shows the UML activity diagram for the general switch statement. Most switch
statements use a break in each case to terminate the switch statement after processing the case.
Figure 3.4 emphasizes this by including break statements in the activity diagram. The diagram
makes it clear that the break statement at the end of a case causes control to exit the switch
statement immediately. The break statement is not required for the switch’s last case (or the
optional default case, when it appears last), because execution continues with the next
statement after the switch.
Fig. 3.4 | switch multiple-selection statement UML activity diagram with break statements.

The repetition structure


Java provides three repetition statements (also called looping statements) that enable programs
to perform statements repeatedly as long as a condition (called the loop-continuation condition)
remains true. The repetition statements are
• the while
• do…while and
• for statements

The while repetition statement


A repetition (or looping) statement allows you to specify that a program should repeat an action
while some condition remains true. The while statement performs the action (or group of
actions) in their bodies zero or more times—if the loop-continuation condition is initially false,
the action (or group of actions) will not execute. The UML activity diagram in Fig. 3.5
illustrates the flow of control in the preceding while statement.
Fig. 3.5 | while repetition statement UML activity diagram.
Example:
1 // Example: Calculate.java using while statement
2 // Calculate the sum of the integers from 1 to 10
3 public class Calculate
4 {
5 public static void main( String[] args )
6 {
7 int sum;
8 int x;
9 x = 1; // initialize x to 1 for counting
10 sum = 0; // initialize sum to 0 for totaling
11 while ( x <= 10 ) // while x is less than or equal to 10
12 {
13 sum += x; // add x to sum
14 ++x; // increment x
15 } // end while
16 System.out.printf( "The sum is: %d\n", sum );
17 } // end main
18 } // end class Calculate
Output:
The sum is: 55
The do…while repetition statement
The do…while repetition statement is similar to the while statement. In the while, the program
tests the loop-continuation condition at the beginning of the loop, before executing the loop’s
body; if the condition is false, the body never executes. The do…while statement tests the loop-
continuation condition after executing the loop’s body; therefore, the body always executes at
least once. When a do…while statement terminates, execution continues with the next
statement in sequence. Figure 3.6 contains the UML activity diagram for the do…while
statement.

Fig. 3.6 | do…while repetition statement UML activity diagram.


Example:
1 // Example: Calculate.java using do----while
2 // Calculate the sum of the integers from 1 to 10
3 public class Calculate
4 {
5 public static void main( String[] args )
6 {
7 int sum;
8 int x;
9 x = 1; // initialize x to 1 for counting
10 sum = 0; // initialize sum to 0 for totaling
11 do
12 {
13 sum += x; // add x to sum
14 ++x; // increment x
15 }while ( x <= 10 ) // while x is less than or equal to 10
16 System.out.printf( "The sum is: %d\n", sum );
17 } // end main
18 } // end class Calculate

The for repetition statement


The while statement can be used to implement any counter-controlled loop. Java also provides
the for repetition statement, which specifies the counter-controlled-repetition details in a single
line of code. Figure 3.7 takes a closer look at the for statement.
General Format of a for Statement The general format of the for statement is
for ( initialization; loopContinuationCondition; increment )
statement
where the initialization expression names the loop’s control variable and optionally provides
its initial value, loopContinuationCondition determines whether the loop should continue
executing and increment modifies the control variable’s value (possibly an increment or
decrement), so that the loop-continuation condition eventually becomes false. The two
semicolons in the for header are required. If the loop-continuation condition is initially false,
the program does notexecute the for statement’s body. Instead, execution proceeds with the
statement following the for. Figure 3.8 shows the activity diagram of the for statement.

Fig. 3.7 | for statement header components.


Fig. 3.8 | UML activity diagram for the for statement
Example:
1 // Example: Calculate.java using for---loop
2 // Calculate the sum of the integers from 1 to 10
3 public class Calculate
4 {
5 public static void main( String[] args )
6 {
7 sum = 0;
8 for(int x =1; x <= 10; ++x){
9 sum += x; // add x to sum
10 }// end for loop
11 System.out.printf( "The sum is: %d\n", sum );
12 } // end main
13 } // end class Calculate

3.1 ENHANCED FOR STATEMENT


The enhanced for statement iterates through the elements of an array without using a counter,
thus avoiding the possibility of “stepping outside” the array. The syntax of an enhanced for
statement is:
for ( parameter : arrayName )
statement;
Example:
1 //EnhancedForTest.java
2 // Using the enhanced for statement to total integers in an array.
3 public class EnhancedForTest
4{
5 public static void main( String[] args )
6 {
7 int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
8 int total = 0;
9 // add each element's value to total
10 for ( int number : array )
11 total += number;
12 System.out.printf( "Total of array elements: %d\n", total );
13 } // end main
14 } // end class EnhancedForTest
Output:
Total of array elements: 849

3.2 BREAK AND CONTINUE STATEMENTS


In addition to selection and repetition statements, Java provides statements break and continue
to alter the flow of control. This unit discusses how to use break in repetition statements.
Break Statement
The break statement, when executed in a while, for, do…while or switch, causes immediate
exit from that statement. Execution continues with the first statement after the control
statement. Common uses of the break statement are to escape early from a loop or to skip the
remainder of a switch statement.
Example:
1 // BreakTest.java
2 // break statement exiting a for loop statement.
3 public class BreakTest
4{
5 public static void main( String[] args )
6{
7 int count; // control variable also used after loop terminates
8 for ( count = 1; count <= 10; count++ ) // loop 10 times
9{
10 if ( count == 5 ) // if count is 5,
11 break;
14 System.out.printf( "%d ", count );
15 } // end for
16 System.out.printf( "\nBroke out of loop at count = %d\n", count );
18 } // end main
19 } // end class BreakTest

Output:
1234
Broke out of loop

Continue statement
The continue statement, when executed in a while, for or do…while, skips the remaining
statements in the loop body and proceeds with the next iteration of the loop. In while and
do…while statements, the program evaluates the loop-continuation test immediately after the
continue statement executes. In a for statement, the increment expression executes, then the
program evaluates the loop-continuation test.
Example:
1 // ContinueTest.java
2 // continue statement terminating an iteration of a for statement.
3 public class ContinueTest
4{
5 public static void main( String[] args )
6{
7 for ( int count = 1; count <= 10; count++ ) // loop 10 times
8{
9 if ( count == 5 ) // if count is 5,
10 continue;
11 System.out.printf( "%d ", count );
12 } // end for
13 System.out.println( "\nUsed continue to skip printing 5" );
14 } // end main
15 } // end class ContinueTest
Output:
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5

4.0 PRINCIPLES OR FEATURES OF OOP


1. Objects, instance variables, classes and methods
• Object - An object is an instance of a class. Objects have states and behaviors.
Example: A dog has states - color, name, breed as well as behavior such as wagging
their tail, barking, eating.
• Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
• Class- A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
• Methods - A method is basically a behavior. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions
are executed.

2. Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private and providing access
to the fields via public methods. If a field is declared private, it cannot be accessed by
anyone outside the class, thereby hiding the fields within the class. For this reason,
encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is
tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code.
Example: Let us look at an example that depicts encapsulation:
/* File name: EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
Public String getName(){
return name;
}
Public String getIdNum(){
return idNum;
}
Public void setName(String newName){
name = newName;
}
Public void setIdNum(String newIdNum){
idNum = newIdNum;
}
Public void setAge(int newAge){
age = newAge;
}
/* Run EncapTest.java */
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());
}
}
This would produce the following result:
Name:JamesAge:20
The public methods are the access points to this class' fields from the outside java world.
Normally, these methods are referred as getters and setters. Therefore, any class that wants
to access the variables should access them through these getters and setters. The variables
of the EncapTest class can be access as below:
3. Data abstraction
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one
that cannot be instantiated. All other functionality of the class still exists, and its fields,
methods, and constructors are all accessed in the same manner. You just cannot create an
instance of the abstract class. If a class is abstract and cannot be instantiated, the class does
not have much use unless it is subclass. This is typically how abstract classes come about
during the design phase. A parent class contains the common functionality of a collection
of child classes, but the parent class itself is too abstract to be used on its own.
An abstract class’s purpose is to provide an appropriate superclass from which other classes
can inherit and thus share a common design. When we think of a class, we assume that
programs will create objects of that type. Sometimes it’s useful to declare classes—called
abstract classes—for which you never intend to create objects. Because they’re used only
as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These
classes cannot be used to instantiate objects, because, as we’ll soon see, abstract classes are
incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes,
from which you can instantiate objects.
Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.
Abstract Methods:
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 method
consists of a method signature, but no method body. Abstract method would have no
definition, and its signature is followed by a semicolon, not curly braces as follows:
/* File name : Employee.java */
public abstract class Employee {
private String name;
private String 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;
}
public void mailCheck() {
System.out.println("Mailing a check to "+this.name +" "+this.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;
}
}
Notice that nothing is different in this Employee class. The class is now abstract, but it still
has three fields, seven methods, and one constructor. Now if you would try as follows:
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String[] args) {
/* Following is not allowed and would raise error */
Employee e =new Employee("George W.","Houston, TX",43);
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
Extending Abstract Class:
We can extend Employee class in normal way as follows:
/* File name : Salary.java */
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;
}
}
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.
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String[] args) {
Salary s =new Salary("Mohd Mohtashim","Ambehta, UP", 3,3600.00);
Employee e =new Salary("John Adams","Boston, MA", 2,2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
This would produce the following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference –
Within mailCheck of Salary class
Mailing check to MohdMohtashim with salary 3600.0
Call mailCheck using Employee reference—
Within mailCheck of Salary class
Mailing check to JohnAdams with salary 2400.

4. Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP, occurs when a parent class reference is used to refer to a child class
object. Any Java object that can pass more than one IS-A test is considered to be
polymorphic.
In Java, all Java objects are polymorphic since any object will pass the IS-A test for their
own type and for the class Object. It is important to know that the only possible way to
access an object is through a reference variable. 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. A reference variable can be declared as a class or interface type.
Let us look at an example.
public interface Vegetarian{
}
public class Animal{
}
public class Deer extends Animal implements Vegetarian{
}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above example:
• A Deer IS-A Animal
• A Deer IS-A Vegetarian
• A Deer IS-A Deer
• A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following
declarations are legal:
Deer d =new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d,a,v,o refer to the same Deer object in the heap
Example:
public class Employee {
private String name;
private String 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 void mailCheck() {
System.out.println("Mailing a check to "+this.name +" "+this.address);
}
public String toString() {
return name +" "+ address +" "+ number;
}
publicString getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
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;
}
}
public static void main(String[] args) {
Salary s =new Salary("Mohd Mohtashim","Ambehta, UP", 3,3600.00);
Employee e =new Salary("John Adams","Boston, MA", 2,2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
5. Method overloading
When a class has two or more methods by same name but different parameters, it is known
as method overloading. It is different from overriding. In overriding a method has same
method name, type, number of parameters etc. if number of parameters are same, then type
of parameters should be different.
Lets consider the example shown before for finding minimum numbers of integer type. If,
lets say we want to find minimum number of double type. Then the concept of Overloading
will be introduced to create two or more methods with the same name but different
parameters.
public class ExampleOverloading{
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2) min = n2;
else min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2) min = n2;
else min = n1;
return min;
}
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
}
This would produce the following result:
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given same name
but with different parameters.
6. Inheritance
Inheritance can be defined as the process where one object acquires the properties of
another. With the use of inheritance, the information is made manageable in a hierarchical
order. When we talk about inheritance, the most commonly used keyword would be
extends and implements. These words would determine whether one object IS-A type of
another. By using these keywords, we can make one object acquire the properties of another
object.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.
IS-A Relationship:
IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output
Programmer salary is: 40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:

public class Animal{


}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
Now, based on the above example, In Object Oriented terms the following are true:
• Animal is the superclass of Mammal class.
• Animal is the superclass of Reptile class.
• Mammal and Reptile are subclasses of Animal class.
• Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say:
• Mammal IS-A Animal
• Reptile IS-A Animal
• Dog IS-A Mammal
• Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of
the superclass except for the private properties of the superclass. We can assure that
Mammal is actually an Animal with the use of the instance operator.
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);
}
}
This would produce the following result:
true
true
true
Since we have a good understanding of the extends keyword, let us look into how the
implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inheritance from interfaces. Interfaces can
never be extended by the classes.
Example:
public interface Animal{
}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}
The instanceof Keyword:
Let us use the instanceof operator to check determine whether Mammal is actually an
Animal, and dog is actually an Animal
Example:
interfaceAnimal{
}
class Mammal implements Animal{
}
public class Dog extends Mammal{
public static void main(String args[]){
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);
}
}
This would produce the following result:
true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class
HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
public class Vehicle{
}
public class Speed{
}
public class Van extends Vehicle{
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not
have to put the entire code that belongs to speed inside the Van class which makes it
possible to reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the
real work. To achieve this, the Van class hides the implementation details from the users
of the Van class. So basically what happens is the users would ask the Van class to do a
certain action and the Van class will either do the work by itself or ask another class to
perform the action. 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 following
is illegal:
public class extends Animal, Mammal{
}
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.
Has-A-Relationship (Aggregation in Java)
If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
Consider a situation, Employee object contains many information such as id, name, emailId
etc. It contains one more object named address, which contains its own information such
as city, state, country, zipcode etc. as given below.
class Employee{
int id;
String name;
Address address; //Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-
A address.
Why use Aggregation?
• For Code Reusability.
In this example, we have created the reference of Operation class in the Circle class.
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op; //aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
7. Packages
A java package is a group of similar types of classes, interfaces and subpackages. Package
in java can be categorized in two form, built-in package and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here,
we will have the detailed learning of creating and using user-defined packages.
Advantages of Java Package
1. Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2. Java package provides access protection.
3. Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
> javac -d directory javafilename
For example
>javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages. The import keyword is used to make the classes and interface of
another package accessible to the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has defined a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related classes
in io package, Server and ServerSocket classes in net packages and so on.
8. Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods
only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
• It is used to achieve fully abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public
and abstract.
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
• Class extends class
• Class implements interface
• Interface extends interface
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided
in the A class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output: Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome

What is marker or tagged interface?


An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information
to the JVM so that JVM may perform some useful operation.
//How Serializable interface is written?
public interface Serializable{
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

5.0 EXCEPTION HANDLING


The exception handling in java is one of the powerful mechanisms to handle the runtime errors
so that normal flow of the application can be maintained. In this section, we will learn about
java exception, its type and the difference between checked and unchecked exceptions.
What is exception?
An exception is an indication of a problem that occurs during a program’s execution. Exception
handling enables you to create applications that can resolve (or handle) exceptions. In many
cases, handling an exception allows a program to continute executing as if no problem had
been encountered. The features presented in this session help you write robust and fault-tolerant
programs that can deal with problems and continue executing or terminate gracefully.
5.1 Divide by zero without Exception Handling
Figure 5.1 prompts the user for two integers and passes them to method quotient, which
calculates the integer quotient and returns an int result. In this example, you’ll see that
exceptions are thrown (i.e., the exception occurs) when a method detects a problem and is
unable to handle it.
1 // Fig. 5.1: DivideByZeroNoExceptionHandling.java
2 // Integer division without exception handling.
3 import java.util.Scanner;
4
5 public class DivideByZeroNoExceptionHandling
6{
7 // demonstrates throwing an exception when a divide-by-zero occurs
8 public static int quotient( int numerator, int denominator )
9 {
10 return numerator / denominator; // possible division by zero
11 } // end method quotient
12
13 public static void main( String[] args )
14 {
15 Scanner scanner = new Scanner( System.in ); // scanner for input
16
17 System.out.print( "Please enter an integer numerator: " );
18 int numerator = scanner.nextInt();
19 System.out.print( "Please enter an integer denominator: " );
20 int denominator = scanner.nextInt();
21
22 int result = quotient( numerator, denominator );
23 System.out.printf(
24 "\nResult: %d / %d = %d\n", numerator, denominator, result );
25 } // end main
26 } // end class DivideByZeroNoExceptionHandling

The first sample execution in Fig. 5.1 shows a successful division. In the second execution, the
user enters the value 0 as the denominator. Several lines of information are displayed in
response to this invalid input. This information is known as a stack trace, which includes the
name of the exception (java.lang.ArithmeticException) in a descriptive message that indicates
the problem that occurred and the method-call stack (i.e., the call chain) at the time it occurred.
The stack trace includes the path of execution that led to the exception method by method. This
helps you debug the program. The first line specifies that an ArithmeticException has occurred.
The text after the name of the exception (“/ by zero”) indicates that this exception occurred as
a result of an attempt to divide by zero. Java does not allow division by zero in integer
arithmetic. When this occurs, Java throws an ArithmeticException. ArithmeticExceptions can
arise from a number of different problems in arithmetic, so the extra data (“/ by zero”) provides
more specific information. Java does allow division by zero with floating-point values. Such a
calculation results in the value positive or negative infinity, which is represented in Java as a
floating-point value (but displays as the string Infinity or -Infinity). If 0.0 is divided by 0.0, the
result is NaN (not a number), which is also represented in Java as a floating-point value (but
displays as NaN).

Fig. 5.1 | Integer division without exception handling.

Starting from the last line of the stack trace, we see that the exception was detected in line 22
of method main. Each line of the stack trace contains the class name and method
(DivideByZeroNoExceptionHandling.main) followed by the file name and line number
(DivideByZeroNoExceptionHandling.java:22). Moving up the stack trace, we see that the
exception occurs in line 10, in method quotient. The top row of the call chain indicates the
throw point—the initial point at which the exception occurs. The throw point of this exception
is in line 10 of method quotient.
In the third execution, the user enters the string "hello" as the denominator. Notice again that a
stack trace is displayed. This informs us that an InputMismatchException has occurred
(package java.util). Our prior examples that read numeric values from the user assumed that
the user would input a proper integer value. However, users sometimes make mistakes and
input noninteger values. An InputMismatchException occurs when Scanner method nextInt
receives a string that does not represent a valid integer. Starting from the end of the stack trace,
we see that the exception was detected in line 20 of method main. Moving up the stack trace,
we see that the exception occurred in method nextInt. Notice that in place of the file name and
line number, we’re provided with the text Unknown Source. This means that the so-called
debugging symbols that provide the file name and line number information for that method’s
class were not available to the JVM—this is typically the case for the classes of the Java API.
Many IDEs have access to the Java API source code and will display file names and line
numbers in stack traces.
In the sample executions of Fig. 5.1 when exceptions occur and stack traces are displayed, the
program also exits. This does not always occur in Java—sometimes a program may continue
even though an exception has occurred and a stack trace has been printed. In such cases, the
application may produce unexpected results. For example, a graphical user interface (GUI)
application will often continue executing. The next section demonstrates how to handle these
exceptions.
In Fig. 5.1 both types of exceptions were detected in method main. In the next example, we’ll
see how to handle these exceptions to enable the program to run to normal completion.
5.2 Handling ArithmeticExceptions and InputMismatchExceptions
The application in Fig. 5.2, which is based on Fig. 5.1, uses exception handling to process any
ArithmeticExceptions and InputMistmatchExceptions that arise. The application still prompts
the user for two integers and passes them to method quotient, which calculates the quotient and
returns an int result. This version of the application uses exception handling so that if the user
makes a mistake, the program catches and handles (i.e., deals with) the exception—in this case,
allowing the user to enter the input again.
1 // Fig. 5.2: DivideByZeroWithExceptionHandling.java
2 // Handling ArithmeticExceptions and InputMismatchExceptions.
3 import java.util.InputMismatchException;
4 import java.util.Scanner;
5
6 public class DivideByZeroWithExceptionHandling
7{
8 // demonstrates throwing an exception when a divide-by-zero occurs
9 public static int quotient( int numerator, int denominator )
10 throws ArithmeticException
11 {
12 return numerator / denominator; // possible division by zero
13 } // end method quotient
14
15 public static void main( String[] args )
16 {
17 Scanner scanner = new Scanner( System.in ); // scanner for input
18 boolean continueLoop = true; // determines if more input is needed
19
20 do
21 {
22 try // read two numbers and calculate quotient
23 {
24 System.out.print( "Please enter an integer numerator: " );
25 int numerator = scanner.nextInt();
26 System.out.print( "Please enter an integer denominator: " );
27 int denominator = scanner.nextInt();
28
29 int result = quotient( numerator, denominator );
30 System.out.printf( "\nResult: %d / %d = %d\n", numerator,
31 denominator, result );
32 continueLoop = false; // input successful; end looping
33 } // end try
34 catch ( InputMismatchException inputMismatchException )
35 {
36 System.err.printf( "\nException: %s\n",
37 inputMismatchException );
38 scanner.nextLine(); // discard input so user can try again
39 System.out.println(
40 "You must enter integers. Please try again.\n" );
41 } // end catch
42 catch ( ArithmeticException arithmeticException )
43 {
44 System.err.printf( "\nException: %s\n", arithmeticException );
45 System.out.println(
46 "Zero is an invalid denominator. Please try again.\n" );
47 } // end catch
48 } while ( continueLoop ); // end do...while
49 } // end main
50 } // end class DivideByZeroWithExceptionHandling
Fig. 5.2 | Handling ArithmeticExceptions and InputMismatchExceptions.

The first sample execution in Fig. 5.2 is a successful one that does not encounter any problems.
In the second execution the user enters a zero denominator, and an ArithmeticException
exception occurs. In the third execution the user enters the string "hello" as the denominator,
and an InputMismatchException occurs. For each exception, the user is informed of the mistake
and asked to try again, then is prompted for two new integers. In each sample execution, the
program runs successfully to completion.
Class InputMismatchException is imported in line 3. Class ArithmeticException does not need
to be imported because it’s in package java.lang. Line 18 creates the boolean variable
continueLoop, which is true if the user has not yet entered valid input. Lines 20–48 repeatedly
ask users for input until a valid input is received.
5.2.1 Enclosing Code in a try Block
Lines 22–33 contain a try block, which encloses the code that might throw an exception and
the code that should not execute if an exception occurs (i.e., if an exception occurs, the
remaining code in the try block will be skipped). A try block consists of the keyword try
followed by a block of code enclosed in curly braces. [Note: The term “try block” sometimes
refers only to the block of code that follows the try keyword (not including the try keyword
itself). For simplicity, we use the term “try block” to refer to the block of code that follows the
try keyword, as well as the try keyword]. The statements that read the integers from the
keyboard (lines 25 and 27) each use method nextInt to read an int value. Method nextInt throws
an InputMismatchException if the value read in is not an integer.
The division that can cause an ArithmeticException is not performed in the try block. Rather,
the call to method quotient (line 29) invokes the code that attempts the division (line 12); the
JVM throws an ArithmeticException object when the denominator is zero.
5.2.2 Catching Exceptions
The try block in this example is followed by two catch blocks—one that handles an
InputMismatchException (lines 34–41) and one that handles an ArithmeticException (lines 42–
47). A catch block (also called a catch clause or exception handler) catches (i.e., receives) and
handles an exception. A catch block begins with the keyword catch and is followed by a
parameter in parentheses (called the exception parameter, discussed shortly) and a block of
code enclosed in curly braces. [Note: The term “catch clause” is sometimes used to refer to the
keyword catch followed by a block of code, whereas the term “catch block” refers to only the
block of code following the catch keyword, but not including it. For simplicity, we use the term
“catch block” to refer to the block of code following the catch keyword, as well as the keyword
itself].
At least one catch block or a finally block must immediately follow the try block. Each catch
block specifies in parentheses an exception parameter that identifies the exception type the
handler can process. When an exception occurs in a try block, the catch block that executes is
the first one whose type matches the type of the exception that occurred (i.e., the type in the
catch block matches the thrown exception type exactly or is a superclass of it). The exception
parameter’s name enables the catch block to interact with a caught exception object—e.g., to
implicitly invoke the caught exception’s toString method (as in lines 37 and 44), which displays
basic information about the exception. Notice that we use the System.err (standard error
stream) object to output error messages. By default, System.err’s print methods, like those of
System.out, display data to the command prompt.
Line 38 of the first catch block calls Scanner method nextLine. Because an
InputMismatchException occurred, the call to method nextInt never successfully read in the
user’s data—so we read that input with a call to method nextLine. We do not do anything with
the input at this point, because we know that it’s invalid. Each catch block displays an error
message and asks the user to try again. After either catch block terminates, the user is prompted
for input.
An uncaught exception is one for which there are no matching catch blocks. You saw uncaught
exceptions in the second and third outputs of Fig. 5.1. Recall that when exceptions occurred in
that example, the application terminated early (after displaying the exception’s stack trace).
This does not always occur as a result of uncaught exceptions. Java uses a “multithreaded”
model of program execution—each thread is a parallel activity. One program can have many
threads. If a program has only one thread, an uncaught exception will cause the program to
terminate. If a program has multiple threads, an uncaught exception will terminate only the
thread where the exception occurred. In such programs, however, certain threads may rely on
others, and if one thread terminates due to an uncaught exception, there may be adverse effects
to the rest of the program.
5.2.3 Termination Model of Exception Handling
If an exception occurs in a try block (such as an InputMismatchException being thrown as a
result of the code at line 25 of Fig. 5.2), the try block terminates immediately and program
control transfers to the first of the following catch blocks in which the exception parameter’s
type matches the thrown exception’s type. In Fig. 5.2, the first catch block catches
InputMismatchExceptions (which occur if invalid input is entered) and the second catch block
catches ArithmeticExceptions (which occur if an attempt is made to divide by zero). After the
exception is handled, program control does not return to the throw point, because the try block
has expired (and its local variables have been lost). Rather, control resumes after the last catch
block. This is known as the termination model of exception handling. Some languages use the
resumption model of exception handling, in which, after an exception is handled, control
resumes just after the throw point.
Notice that we name our exception parameters (inputMismatchException and
arithmeticException) based on their type. Java programmers often simply use the letter e as the
name of their exception parameters.
After executing a catch block, this program’s flow of control proceeds to the first statement
after the last catch block (line 48 in this case). The condition in the do…while statement is true
(variable continueLoop contains its initial value of true), so control returns to the beginning of
the loop and the user is once again prompted for input. This control statement will loop until
valid input is entered. At that point, program control reaches line 32, which assigns false to
variable continueLoop. The try block then terminates. If no exceptions are thrown in the try
block, the catch blocks are skipped and control continues with the first statement after the catch
blocks. Now the condition for the do…while loop is false, and method main ends.
The try block and its corresponding catch and/or finally blocks form a try statement. Do not
confuse the terms “try block” and “try statement”—the latter includes the try block as well as
the following catch blocks and/or finally block.
As with any other block of code, when a try block terminates, local variables declared in the
block go out of scope and are no longer accessible; thus, the local variables of a try block are
not accessible in the corresponding catch blocks. When a catch block terminates, local variables
declared within the catch block (including the exception parameter of that catch block) also go
out of scope and are destroyed. Any remaining catch blocks in the try statement are ignored,
and execution resumes at the first line of code after the try…catch sequence—this will be a
finally block, if one is present.
5.2.4 Using the throws Clause
Now let’s examine method quotient (Fig. 5.2, lines 9–13). The portion of the method
declaration located at line 10 is known as a throws clause. It specifies the exceptions the method
throws. This clause appears after the method’s parameter list and before the method’s body. It
contains a comma-separated list of the exceptions that the method will throw if various
problems occur. Such exceptions may be thrown by statements in the method’s body or by
methods called from the body. A method can throw exceptions of the classes listed in its throws
clause or of their subclasses. We’ve added the throws clause to this application to indicate to
the rest of the program that this method may throw an ArithmeticException. Clients of method
quotient are thus informed that the method may throw an ArithmeticException.
When line 12 executes, if the denominator is zero, the JVM throws an ArithmeticException
object. This object will be caught by the catch block at lines 42–47, which displays basic
information about the exception by implicitly invoking the exception’s toString method, then
asks the user to try again.
If the denominator is not zero, method quotient performs the division and returns the result to
the point of invocation of method quotient in the try block (line 29). Lines 30–31 display the
result of the calculation and line 32 sets continueLoop to false. In this case, the try block
completes successfully, so the program skips the catch blocks and fails the condition at line 48,
and method main completes execution normally.
When quotient throws an ArithmeticException, quotient terminates and does not return a value,
and quotient’s local variables go out of scope (and are destroyed). If quotient contained local
variables that were references to objects and there were no other references to those objects,
the objects would be marked for garbage collection. Also, when an exception occurs, the try
block from which quotient was called terminates before lines 30–32 can execute. Here, too, if
local variables were created in the try block prior to the exception’s being thrown, these
variables would go out of scope.
If an InputMismatchException is generated by lines 25 or 27, the try block terminates and
execution continues with the catch block at lines 34–41. In this case, method quotient is not
called. Then method main continues after the last catch block (line 48).
5.3 When to use Exception Handling
Exception handling is designed to process synchronous errors, which occur when a statement
executes. Common examples:
• are out-of-range array indices
• arithmetic overflow (i.e., a value outside the representable range of values)
• division by zero
• invalid method parameters
• thread interruption and
• unsuccessful memory allocation (due to lack of memory).
Exception handling is not designed to process problems associated with asynchronous events
(e.g., disk I/O completions, network message arrivals, mouse clicks and keystrokes), which
occur in parallel with, and independent of, the program’s flow of control.
5.4 Java Exception Hierarchy
All Java exception classes inherit directly or indirectly from class Exception, forming an
inheritance hierarchy. You can extend this hierarchy with your own exception classes.
Figure 5.3 shows a small portion of the inheritance hierarchy for class Throwable (a subclass
of Object), which is the superclass of class Exception. Only Throwable objects can be used
with the exception-handling mechanism. Class Throwable has two subclasses: Exception and
Error. Class Exception and its subclasses—for instance, RuntimeException (package java.lang)
and IOException (package java.io)—represent exceptional situations that can occur in a Java
program and that can be caught by the application. Class Error and its subclasses represent
abnormal situations that happen in the JVM. Most Errors happen infrequently and should not
be caught by applications—it’s usually not possible for applications to recover from Errors.
Fig. 5.3 | Portion of class Throwable’s inheritance hierarchy.

5.5 Types of Exception


There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
5.5.1 Checked vs. Unchecked Exceptions
Java distinguishes between checked exceptions and unchecked exceptions. This distinction is
important, because the Java compiler enforces a catch-or-declare requirement for checked
exceptions. An exception’s type determines whether it’s checked or unchecked. All exception
types that are direct or indirect subclasses of class RuntimeException (package java.lang) are
unchecked exceptions. These are typically caused by defects in your program’s code. Examples
of unchecked exceptions include ArrayIndexOutOfBoundsExceptions and
ArithmeticExceptions (shown in Fig. 5.3). All classes that inherit from class Exception but not
class RuntimeException are considered to be checked exceptions. Such exceptions are typically
caused by conditions that are not under the control of the program—for example, in file
processing, the program can’t open a file because the file does not exist. Classes that inherit
from class Error are considered to be unchecked.
5.5.2 Difference between checked and unchecked exceptions
1. Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g., IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2. Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3. Error
Error is irrecoverable e.g., OutOfMemoryError, VirtualMachineError, AssertionError
etc.

5.5.3 Common scenarios where exceptions may occur


There are some scenarios where unchecked exceptions can occur. They are as follows:
1. Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
2. Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs
as NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
3. Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur as NumberFormatException.
Suppose we have a string variable that have characters, converting this variable into
digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4. Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result as
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
5.5.4 Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
5.5.4.1 Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used within
the method. Java try block must be followed by either catch or finally block. Syntax of java
try-catch:
try{
//code that may throw exception
}catch(Exception_class_Name ref){
}

Java catch block is used to handle the Exception. It must be used after the try block only. You
can use multiple catch block with a single try.

5.5.4.2 Finally Block


Programs that obtain certain types of resources must return them to the system explicitly to
avoid so-called resource leaks. In programming languages such as C and C++, the most
common kind of resource leak is a memory leak. Java performs automatic garbage collection
of memory no longer used by programs, thus avoiding most memory leaks. However, other
types of resource leaks can occur. For example, files, database connections and network
connections that are not closed properly after they’re no longer needed might not be available
for use in other programs.
The finally block (which consists of the finally keyword, followed by code enclosed in curly
braces), sometimes referred to as the finally clause, is optional. If it’s present, it’s placed after
the last catch block. If there are no catch blocks, the finally block immediately follows the try
block.
The finally block will execute whether or not an exception is thrown in the corresponding try
block. The finally block also will execute if a try block exits by using a return, break or continue
statement or simply by reaching its closing right brace. The finally block will not execute if the
application exits early from a try block by calling method System.exit. This method
immediately terminates an application.
Because a finally block almost always executes, it typically contains resource-release code.
Suppose a resource is allocated in a try block. If no exception occurs, the catch blocks are
skipped and control proceeds to the finally block, which frees the resource. Control then
proceeds to the first statement after the finally block. If an exception occurs in the try block,
the try block terminates. If the program catches the exception in one of the corresponding catch
blocks, it processes the exception, then the finally block releases the resource and control
proceeds to the first statement after the finally block. If the program doesn’t catch the
exception, the finally block still releases the resource and an attempt is made to catch the
exception in a calling method.
If an exception that occurs in a try block cannot be caught by one of that try block’s catch
handlers, the program skips the rest of the try block and control proceeds to the finally block.
Then the program passes the exception to the next outer try block—normally in the calling
method—where an associated catch block might catch it. This process can occur through many
levels of try blocks. Also, the exception could go uncaught.
If a catch block throws an exception, the finally block still executes. Then the exception is
passed to the next outer try block—again, normally in the calling method.
Syntax of try-finally block
try{
//code that may throw exception
}finally{
}
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
Finally block in java can be used to put "cleanup" code such as closing a file, closing connection
etc.
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output: finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule 3: For each try block there can be zero or more catch blocks, but only one finally block.

Figure 5.4 demonstrates that the finally block executes even if an exception is not thrown in
the corresponding try block. The program contains static methods main (lines 6–18),
throwException (lines 21–44) and doesNotThrowException (lines 47–64). Methods
throwException and doesNotThrowException are declared static, so main can call them
directly without instantiating a UsingExceptions object.
1 // Fig. 5.4: UsingExceptions.java
2 // try...catch...finally exception handling mechanism.
3
4 public class UsingExceptions
5{
6 public static void main( String[] args )
7 {
8 try
9 {
10 throwException(); // call method throwException
11 } // end try
12 catch ( Exception exception ) // exception thrown by throwException
13 {
14 System.err.println( "Exception handled in main" );
15 } // end catch
16
17 doesNotThrowException();
18 } // end main
19
20 // demonstrate try...catch...finally
21 public static void throwException() throws Exception
22 {
23 try // throw an exception and immediately catch it
24 {
25 System.out.println( "Method throwException" );
26 throw new Exception(); // generate exception
27 } // end try
28 catch ( Exception exception ) // catch exception thrown in try
29 {
30 System.err.println(
31 "Exception handled in method throwException" );
32 throw exception; // rethrow for further processing
33
34 // code here would not be reached; would cause compilation errors
35
36 } // end catch
37 finally // executes regardless of what occurs in try...catch
38 {
39 System.err.println( "Finally executed in throwException" );
40 } // end finally
41
42 // code here would not be reached; would cause compilation errors
43
44 } // end method throwException
45
46 // demonstrate finally when no exception occurs
47 public static void doesNotThrowException()
48 {
49 try // try block does not throw an exception
50 {
51 System.out.println( "Method doesNotThrowException" );
52 } // end try
53 catch ( Exception exception ) // does not execute
54 {
55 System.err.println( exception );
56 } // end catch
57 finally // executes regardless of what occurs in try...catch
58 {
59 System.err.println(
60 "Finally executed in doesNotThrowException" );
61 } // end finally
62
63 System.out.println( "End of method doesNotThrowException" );
64 } // end method doesNotThrowException
65 } // end class UsingExceptions

Fig. 5.4 | try…catch…finally exception-handling mechanism.

System.out and System.err are streams—sequences of bytes. While System.out (known as the
standard output stream) displays a program’s output, System.err (known as the standard error
stream) displays a program’s errors. Output from these streams can be redirected (i.e., sent to
somewhere other than the command prompt, such as to a file). Using two different streams
enables you to easily separate error messages from other output. For instance, data output from
System.err could be sent to a log file, while data output from System.out can be displayed on
the screen.
Java throw exception
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception. We will see custom exceptions
later.
The syntax of java throw keyword is given below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error”);
//java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing checkup before the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared?
Ans) checked exception only, because:
• unchecked Exception: under your control so correct your code.
• error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
1. Checked Exception can be propagated (forwarded in call stack).
2. It provides information to the caller of the method about the exception.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error"); //checked exception
}
void n() throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled");
}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
There are two cases:
1. Case1: You caught the exception i.e. handle the exception using try/catch.
2. Case2: You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
Case2: You declare the exception
1. A) In case you declare the exception, if exception does not occur, the code will be
executed fine.
2. B) In case you declare the exception if exception occurs, an exception will be thrown
at runtime because throws does not handle the exception.
A) Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{ //declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output: device operation performed
normal flow...

B) Program if exception occurs


import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output: Runtime Exception
Difference between throw and throws in Java
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No. throw Throws
1. Java throw keyword is used to Java throws keyword is used to declare an
explicitly throw an exception. exception.
2. Checked exception cannot be Checked exception can be propagated with
propagated using throw only. throws.
3. Throw is followed by an instance. Checked exception can be propagated with
throws.
4. Throw is used within the method. Throws is used with the method signature.
5. You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,
SQLException.

Difference between final, finally and finalize


There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
No. final Finally finalize
1. Final is used to apply restrictions Finally is used to place Finalize is used to
on class, method and variable. important code, it will perform clean up
Final class can't be inherited, be executed whether processing just before
final method can't be overridden exception is handled or object is garbage
and final variable value can't not. collected.
be changed.
2. Final is a keyword. Finally is a block. Finalize is a method.

Java final example


class FinalExample{
public static void main(String[] args){
final int x=100;
x=200; //Compile Time Error
}
}
Java finally example
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){
System.out.println(e);
}
finally{
System.out.println("finally block is executed");
}
}
}
Java finalize example
class FinalizeExample{
public void finalize(){
System.out.println("finalize called");
}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}
}
6.0 ARRAYS
An array is a group of variables (called elements or components) containing values that all have
the same type. Arrays are objects, so they’re considered reference types.
The elements of an array can be either primitive types or reference types. To refer to a particular
element in an array, we specify the name of the reference to the array and the position number
of the element in the array. The position number of the element is called the element’s index
or subscript.
Figure 6.1 below shows a logical representation of an integer array called c.

Fig. 6.1 | A 12-element array


An index must be a nonnegative integer. A program can use an expression as an index.
For example, if we assume that variable a is 5 and variable b is 6, then the statement
c[ a + b ] += 2;
adds 2 to array element c[11]. An indexed array name is an array-access expression, which can
be used on the left side of an assignment to place a new value into an array element.
6.1 Declaring and Creating Arrays
Array objects occupy space in memory. Array objects are created with keyword new.
int[] c = new int[ 12 ];
Creating and Initializing an Array
Example 1
1 //InitArray.java
2 // Initializing the elements of an array to default values of zero.
3 public class InitArray
4{
5 public static void main( String[] args )
6 {
7 int[] array; // declare array named array
8 array = new int[ 10 ]; // create the array object
9 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
10 // output each array element's value
11 for ( int counter = 0; counter < array.length; counter++ )
12 System.out.printf( "%5d%8d\n", counter, array[ counter ] );
13 } // end main
14 } // end class InitArray
Output:
Index Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

Example 2
1 //InitArray.java
2 // Initializing the elements of an array with an array initializer.
3 public class InitArray
4{
5 public static void main( String[] args )
6 {
7 // initializer list specifies the value for each element
8 int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
9 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
10 // output each array element's value
11 for ( int counter = 0; counter < array.length; counter++ )
12 System.out.printf( "%5d%8d\n", counter, array[ counter ] );
13 } // end main
14 } // end class InitArray
Output:
Index Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37

6.2 Multidimensional Arrays


Multidimensional arrays with two dimensions are often used to represent tables of values
consisting of information arranged in rows and columns. To identify a particular table element,
we must specify two indices. By convention, the first identifies the element’s row and the
second its column. Arrays that require two indices to identify a particular element are called
two-dimensional arrays.
Multidimensional arrays can have more than two dimensions. In general, an array with m rows
and n columns is called an m-by-n array. Figure 6.2 illustrates a two-dimensional array named
a that contains three rows and four columns.

Fig. 6.2 | Two-dimensional array with three rows and four columns.
Two-Dimensional Arrays with Rows of Different Lengths:
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
Creating Two-Dimensional Arrays with Array-Creation Expressions:
int[][] b = new int[ 3 ][ 4 ];
A multidimensional array in which each row has a different number of columns can be created
as follows:
int[][] b = new int[ 2 ][ ]; // create 2 rows
b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0
b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1
Two-Dimensional Array Example: Displaying Element Values
Example:
1 //InitArray.java
2 // Initializing two-dimensional arrays.
3 public class InitArray
4{
5 // create and output two-dimensional arrays
6 public static void main( String[] args )
7 {
8 int[][] array1 = { { 1, 2, 3 }, { 4, 5, 6 } };
9 int[][] array2 = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
10 System.out.println( "\nValues in array2 by row are" );
11 outputArray( array2 ); // displays array2 by row
12 } // end main
13 // output rows and columns of a two-dimensional array
14 public static void outputArray( )
15 {
16 System.out.println( "Values in array1 by row are" );
17 outputArray( array1 ); // displays array1 by row
18 System.out.println( "\nValues in array2 by row are" );
19 outputArray( array2 ); // displays array2 by row
20 } // end main
21 // output rows and columns of a two-dimensional array
22 public static void outputArray( )
21 {
22 // loop through array's rows
23 for ( int row = 0; row < array.length; row++ )
24 {
25 // loop through columns of current row
26 for ( int column = 0; column < array[ row ].length; column++ )
27 System.out.printf( "%d ", array[ row ][ column ] );
28
29 System.out.println(); // start new line of output
30 } // end outer for
31 } // end method outputArray
32 } // end class InitArray
Output:
Values in array1 by row are
1 2 3
4 5 6
Values in array2 by row are
1 2
3
4 5 6

7.0 INPUT/OUTPUT
The input/output class in Java allow us to make our programs more interactive by getting some
input from the user. The methods of getting input include the following:
1. Scanner class
i. Add this at the top of your code:
import java.util.Scanner;
ii. Add this statement:
Scanner st = new Scanner(System.in);
iii. Declare a temporary variable to get the input, and invoke the nextInt(),
nextDouble(), methods as the case may be to get input from the keyboard.
int a = st.nextInt();
2. BufferedReader class
i. Add this at the top of your code:
import java.io.*;
ii. Add this statement:
BufferedReader br = new BufferedReader(new InputStreamReader( System.in) );
iii. Declare a temporary String variable to get the input, and invoke the readLine()
method to get input from the keyboard. You have to type it inside a try-catch block.
try{
String temp = br.readLine();
}catch( IOException e ){
System.out.println(“Error in getting input”);
}

3. JOptionPane
Another way to get input from the user is by using the JOptionPane class which is found in
the javax.swing package. JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something.
Example:
import javax.swing.JOptionPane;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
String name;
name = JOptionPane.showInputDialog("Please enter your name");
String msg = "Hello " + name + "!";
JOptionPane.showMessageDialog(null, msg);
}
}
This will output:
8.0 LABORATORY EXERCISES IN AN OOP LANGUAGE
1. Write a java program that can accept two matrices of any length of rows and columns
and perform arithmetic operations on them. The program should include a decision
menu that gives the user the chance to determine the number and type of arithmetic
operation (addition, subtraction and multiplication) to perform. [Hint: Use the switch
statement].
2. Write an application that reads array of integer numbers and perform different
operations on them. [Hint: addition, min, max, range, mode, median, mean, variance,
standard deviation, sorting, print even and odd numbers, etc.]
3. Define a Square class with the length of its side as an instance variable. Include an
appropriate constructor method and methods to enlarge an instance as well as compute
its area.
4. Using the Square class in Question 1, create ten randomly sized squares and find the
sum of their areas. (The method Math.random() returns a random number between 0.0
and 1.0 each time it is invoked).
5. Add the functionality for a Square object to draw itself via ASCII characters. For
example, a Square of length 4 can be drawn as:
****
* *
* *
****
Or:

XXXX
X++X
X++X
XXXX
The System.out.print() and System.out.println() methods may be useful.
6. Find a number with nine digits d1d2d3,…, d9 such that the sub-string number d1, …,
dn is divisible by n, 1<=n<=9. Note that each of the digits may be used once.
7. Design a simple calculator in Java using any relevant OOP features.
8. Write an application that reads five integers and determines and prints the largest and
smallest integers in the group. Use only the OOP techniques you learned in this course.
9. Write an application that reads two integers, determines whether the first is a multiple
of the second and prints the result. [Hint: Use the remainder operator.]
10. Explain why a class might provide a set method and a get method for an instance
variable.
11. Create a class called Employee that includes three instance variables—a first name
(type String), a last name (type String) and a monthly salary (double). Provide a
constructor that initializes the three instance variables. Provide a set and a get method
for each instance variable. If the monthly salary is not positive, do not set its value.
Write a test application named EmployeeTest that demonstrates class Employee’s
capabilities. Create two Employee objects and display each object’s yearly salary. Then
give each Employee a 10% raise and display each Employee’s yearly salary again.
12. Create a class called Date that includes three instance variables—a month (type int), a
day (type int) and a year (type int). Provide a constructor that initializes the three
instance variables and assumes that the values provided are correct. Provide a set and a
get method for each instance variable. Provide a method displayDate that displays the
month, day and year separated by forward slashes (/). Write a test application named
DateTest that demonstrates class Date’s capabilities.
13. Create a class called Invoice that a hardware store might use to represent an invoice for
an item sold at the store. An Invoice should include four pieces of information as
instance variables—a part number (type String), a part description (type String), a
quantity of the item being purchased (type int) and a price per item (double). Your class
should have a constructor that initializes the four instance variables. Provide a set and
a get method for each instance variable. In addition, provide a method named
getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by
the price per item), then returns the amount as a double value. If the quantity is not
positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0.
Write a test application named InvoiceTest that demonstrates class Invoice’s
capabilities.
14. Explain what happens when a Java program attempts to divide one integer by another.
What happens to the fractional part of the calculation? How can you avoid that
outcome?
15. Develop a Java application that determines the gross pay for each of three employees.
The company pays straight time for the first 40 hours worked by each employee and
time and a half for all hours worked in excess of 40. You’re given a list of the
employees, their number of hours worked last week and their hourly rates. Your
program should input this information for each employee, then determine and display
the employee’s gross pay. Use class Scanner to input the data.
16. Write an application that prompts the user to enter the size of the side of a square, then
displays a hollow square of that size made of asterisks. Your program should work for
squares of all side lengths between 1 and 20.
17. A palindrome is a sequence of characters that reads the same backward as forward. For
example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554
and 11611. Write an application that reads in a five-digit integer and determines
whether it’s a palindrome. If the number is not five digits long, display an error message
and allow the user to enter a new value.
18. Write an application that demonstrates drawing rectangles and ovals, using the
Graphics methods drawRect and drawOval, respectively. Your program graphical
interface should include option menu that require the user to input 1 to draw rectangles
and 2 to draw ovals.
19. A right triangle can have sides whose lengths are all integers. The set of three integer
values for the lengths of the sides of a right triangle is called a Pythagorean triple. The
lengths of the three sides must satisfy the relationship that the sum of the squares of two
of the sides is equal to the square of the hypotenuse. Write an application that displays
a table of the Pythagorean triples for side1, side2 and the hypotenuse, all no larger than
500. Use a triple-nested for loop that tries all possibilities. This method is an example
of “brute-force” computing. You’ll learn in more advanced computer science courses
that for many interesting problems there’s no known algorithmic approach other than
using sheer brute force.
20. Write a method isMultiple that determines, for a pair of integers, whether the second
integer is a multiple of the first. The method should take two integer arguments and
return true if the second is a multiple of the first and false otherwise. [Hint: Use the
remainder operator]. Incorporate this method into an application that inputs a series of
pairs of integers (one pair at a time) and determines whether the second value in each
pair is a multiple of the first.
21. Write a method isEven that uses the remainder operator (%) to determine whether an
integer is even. The method should take an integer argument and return true if the
integer is even and false otherwise. Incorporate this method into an application that
inputs a sequence of integers (one at a time) and determines whether each is even or
odd.
22. Use a one-dimensional array to solve the following problem: Write an application that
inputs five numbers, each between 10 and 100, inclusive. As each number is read,
display it only if it’s not a duplicate of a number already read. Provide for the “worst
case,” in which all five numbers are different. Use the smallest possible array to solve
this problem. Display the complete set of unique values input after the user enters each
new value.
23. Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram,
Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. Create and
use a Point class to represent the points in each shape. Make the hierarchy as deep (i.e.,
as many levels) as possible. Specify the instance variables and methods for each class.
The private instance variables of Quadrilateral should be the x-y coordinate pairs for
the four endpoints of the Quadrilateral. Write a program that instantiates objects of your
classes and outputs each object’s area (except Quadrilateral).

You might also like