0% found this document useful (0 votes)
17 views

CMP 301 Object Oriented Programming Langauage I

Object Oriented Programming

Uploaded by

gbengasa8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

CMP 301 Object Oriented Programming Langauage I

Object Oriented Programming

Uploaded by

gbengasa8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

LECTURE NOTE

CMP 301 OBJECT-ORIENTED PROGRAMMING LANGAUGE I (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, applets, 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.
 Prints to the screen in Java language.
 Makes relational operations in Java.
 Constructs loops in Java.
 Defines arrays in Java and uses them.
5. Uses objects and classes.
 Declares objects and classes.
 Distinguishes classes and objects.
 Declares and uses variables.
 Declares and uses methods and properties.
6. Lists the object-oriented programming concepts.
 Explains and uses encapsulation.
 Explains and uses inheritance.
 Explains and uses polymorphism.
7. Names special functions.
 Distinguishes constructors, default constructors, interfaces, abstract classes and
abstract methods.
 Recognizes operator overloading functions.
 Identifies base and derived classes.
8. Codes object-oriented programs.
 Implements constructors, default constructors, interfaces, abstract classes and
abstract methods.
 Overloads operators.
 Inherits a class from another class.
 Writes a complete program using object-oriented programming concepts.
9. Explains and handles exceptions.
 Describes exceptions.
 Throws exceptions
 Catches exceptions.
10. Writes multithreaded Java programs.
 Develops task classes by implementing the Runnable interface.
 Creates threads to run tasks using the Thread class.
 Controls threads using the methods in the Thread class.
 Executes tasks in a thread pool.
11. Understands the concepts of database and database management systems.
 Understands the relational data model: relational data structures, constraints,
and languages.
 Uses SQL to create and drop tables and to retrieve and modify data.
 Loads a driver, connects to a database, executes statements, and processes result
sets using JDBC.
12. Uses generic classes and methods.
 Declares generic classes.
 Uses generic classes.
 Declares generic methods.
 Uses generic 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 Mathematical Sciences, Computer


Science Unit, 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 Hello World.
public class MyFirstJavaProgram{
/* This is my first java program. * This will print 'Hello World' as the output */
public static void main(String[]args){
System.out.println("Hello World");
// prints Hello World
}
}
Let's look at how to save the file, compile and run the program. Please follow the steps given
below:
 Open notepad and add the code as above.
 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.
 Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code.
 If there are no errors in your code, the command prompt will take you to the next
line(Assumption : The path variable is set).
 Now, type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see ' Hello World ' printed on the window.
 C :> javac MyFirstJavaProgram.java C :> java MyFirstJavaProgram HelloWorld
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 is 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
performsbit-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 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.
Example:
Class SingleSelection{
public static void main(String args[]){
int grade;
if(grade>=60)
System.out.println(“passed”);
}
}
 The if…else double selection statement performs an action if a condition is true and
performs a different action if the condition is false.
Class DoubleSelection{
public static void main(String args[]){
int grade;
if(grade>=60){
System.out.println(“passed”);
}else{
System.out.println(“failed”);
}
}
}

 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

}
}
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 perform 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.
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.
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.
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;
}

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:
/* 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
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.
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 mechanism 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?
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
What is exception handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5,
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed. That is why we use exception handling in java.
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

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.
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
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Java try block
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.

Syntax of try-finally block


try{
//code that may throw exception
}finally{}

Problem without exception handling


Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0; //may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
Java catch multiple exceptions
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}
catch(Exception e){System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}
Output: task1 completed
rest of the code...
 Rule 1: At a time only one Exception occurred and at a time only one catch block is
executed.
 Rule 2: All catch blocks must be ordered from most specific to most general i.e. catch
for ArithmeticException must come before catch for Exception.
class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){
System.out.println("common task completed");
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error

Java Nested try block


The try block within a try block is known as nested try block in java.
Why use nested try block?
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Java nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);
}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
System.out.println("other statement);
}catch(Exception e){
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
....
Java finally block
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.
Why use java finally
o 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.
Java throw exception
Java throw keyword
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. o 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 {
31 } // end method outputArray
32 } // end class InitArray
Output:
Values in array1 by row are
123
456
Values in array2 by row are
12
3
456
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