0% found this document useful (0 votes)
256 views268 pages

Oops Final Contents

Uploaded by

akshaya vijay
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)
256 views268 pages

Oops Final Contents

Uploaded by

akshaya vijay
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/ 268

Object Oriented Programming 2019

CHAPTER 1

INTRODUCTION TO OOP AND JAVA FUNDAMENTALS

Object Oriented Programming - Abstraction – objects and classes -

Encapsulation- Inheritance - Polymorphism- OOP in Java – Characteristics of Java

– The Java Environment - Java Source File - Structure – Compilation. Fundamental

Programming Structures in Java – Defining classes in Java – constructors, methods

-access specifiers - static members -Comments, Data Types, Variables,

Operators, Control Flow, Arrays , Packages - JavaDoc comments.

DEPARTMENT OF CSE Page 1


Object Oriented Programming 2019

DEPARTMENT OF CSE Page 2


Object Oriented Programming 2019

INTRODUCTION TO OOP AND JAVA FUNDAMENTALS


1.1 OBJECT-ORIENTED PROGRAMMING
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which may contain data(attributes) and code (procedures or methods).
Object= data+ function
List of object-oriented programming languages
Ada 95 Fortran 2003
BETA Graphtalk
C++ IDLscript
C# J#
COBOL Java
Procedural Programming vs object-oriented programming
Procedural Programming object-oriented programming
The program is written is based on the The program is written is based on the objects.
procedures.
Low efficicency High efficicency
POP follows Top Down approach. OOP follows Bottom Up approach.
To add new data and function in POP is not so OOP provides an easy way to add new data
easy. and function.
Example of POP are : C, VB, FORTRAN, Example of OOP are : C++, JAVA, VB.NET,
Pascal. C#.NET
OOP Concepts / Features of OOP/ Characteristics of OOPS
Features of OOPs are following:
1. Object
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Message Passing
8. Dynamic binding

DEPARTMENT OF CSE Page 3


Object Oriented Programming 2019

1.1.1 OBJECT AND CLASSES


Object
An object is an instance of a class. Objects have states and behaviors.
Example: Dog
states: color, name, breed
behaviors : wagging the tail, barking, eating.
Class
A class can be defined as a template/blueprint that describes the behavior/state of objects. Class
is a set of objects that share the common structure and behavior.

Example:
1) Class : student
Object: kavitha, Ahila
2) Class : Department
Object: EEE, ECE, CSE
Classes in Java
public class student
{
int rollno;
int age;
void input()
{
Variables in class }
● }
Local variables
Variables defined inside methods, constructors or blocks are called local variables.
● Instance variables
Instance variables are variables within a class but outside any method.
● Class variables
Class variables are variables declared within a class, outside any method, with the static keyword.

DEPARTMENT OF CSE Page 4


Object Oriented Programming 2019

Objects
Class
1. For a single class, we can create many 1. For many objects, We can create one
objects. single class.
2. We cannot assign values to class 2. We can assign values to objects
3. Memory is not allocated once class is 3. Memory is allocated once object is created.
created
1.1.2 ABSTRACTION
It refers to the act of representing essential features without including the background details or
explanations. It is one of the key concepts of object-oriented programming (OOP) languages. Its
main goal is to handle complexity by hiding unnecessary details from the user.
For example, people do not think of a car as a set of tens of thousands of individual parts. They
think of it as a well-defined object with its own unique behavior. This abstraction allows people to
use a car to drive to the desired location without worrying about the complexity of the parts that
form the car. They can ignore the details of how the engine, transmission, and braking systems
work. Instead, they are free to utilize the object as a whole.
Abstarction in Java
● In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
1.1.3 ENCAPSULATION
Encapsulation is the process of combining data and functions into a single unit. In Java, the basis
of encapsulation is the class. Encapsulation achieves the concept of data hiding.
Data hiding: Data inside the class is accessible only through the function within the class

Advantage of Encapsulation
● It provides you the control over the data.
● It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.
● The encapsulate class is easy to test. So, it is better for unit testing.
Abstarction Encapsulation
1. It refers to the act of representing essential 1. Encapsulation is the process of combining
features without including the background data and functions into a single unit. In Java,
details or explanations. the basis of encapsulation is the class
2. It is used in the design phase. 2. It is used in the implementation phase.

DEPARTMENT OF CSE Page 5


Object Oriented Programming 2019

1.1.4 INHERITANCE
Inheritance is the process of forming new class from the existing class.
● Existing class is also called as parent class or base class or super class.
● New class is also called as child class or derived class.

For example,
● Animal is the base class.
● Mammal and reptile are the deived class of Animal. So they inherits the properties from
Animal base class.
● Whale and Dog are the derived class of Mammal. So they inherits the properties from
mammal base class.
Advantage of Inheritance
1. Reusability
2. Reducing the code size of program.
3. Sub class inherits all the properties from base class.
1.1.5 POLYMORPHISM
Polymorphism is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.
● The word "poly" means many
● "morphs" means forms.
● So polymorphism means many forms.

DEPARTMENT OF CSE Page 6


Object Oriented Programming 2019

Example:

Here,
● Shape is the base class.
● In the Circle class, draw() is used to draw the circle.
● In the Rectangle class, draw() is used to draw the rectangle.
● In the Triangle class, draw() is used to draw the triangle.
1.2 OOP CONCEPTS IN JAVA- CHARACTERISTICS OF JAVA
Java is a object oriented, platform independent, portable, compiled and interpreted programming
language. Java is an object-oriented programming language developed by James Gosling and
colleagues at Sun Microsystems in the early 1990s. Java was started as a project called "Oak" by
James Gosling in June 1991.
Characteristics Of Java are following:
1. Simple
2. Secure

DEPARTMENT OF CSE Page 7


Object Oriented Programming 2019

3. Portable
4. Platform independent
5. Object-oriented
6. Robust
7. Multithreaded
8. Architecture-neutral
9. Interpreted
10. High performance :
11. Distributed
12. Dynamic
Simple :
● Java is Easy to write and more readable.
● Java has a concise, cohesive set of features that makes it easy to learn and use.
Secure :
● Java program cannot harm other system
● Java provides a secure means of creating Internet applications.
● Java provides secure way to access web applications.
Portable :
● Java programs can be transferred over world wide web (e.g applets)
Platform independent:
● Programs in java can be executed on a variety of platforms.
Object-oriented :
● Java programming is object-oriented programming language.
● Like C++, java provides most of the object oriented features.
● Java is pure OOP Language. (while C++ is semi object oriented)
Robust :
● Java encourages error-free programming by being strictly typed and performing run-time
checks.
Multithreaded :
● Java provides integrated support for multithreaded programming.
Architecture-neutral :
● Java is not tied to a specific machine or operating system architecture.
● Java is machine independent.
Interpreted :
● Java supports cross-platform code through the use of Java bytecode.
● Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).

DEPARTMENT OF CSE Page 8


Object Oriented Programming 2019

High performance :
● Bytecodes are highly optimized.
● JVM can execute bytecodes much faster .
Distributed :
● Java is designed with the distributed environment.
● Java can be transmitted over internet.
Dynamic :
● Java programs carry substantial amounts of run-time type information with them that is
used to verify and resolve accesses to objects at run time.
C C++ Java
Platform dependent Platform dependent Platform independent
It needs to be compiled It needs to be compiled It needs to be compiled and
interpreted
No multithreading No multithreading multithreading
Pointers No pointers No pointers
No templates Templates Templates
Database handling is complex. Database handling is complex. Database handling is easy.

1.3 JAVA ENVIRONMENT (JE)


Java Environment is made up of three things. They are,
1. Java Development Kit
2. Application Programming Interface
3. Java Runtime Environment
Java Development Kit
The Java Development Kit (JDK) is a software development environment used for developing
Java applications and applets.

DEPARTMENT OF CSE Page 9


Object Oriented Programming 2019

● javac
o It converts source file into byte code
● java
o It converts byte code into machine code
● jdb (java debugger)
o Find errors in program.
● javap (java disassembler)
o Converts byte code into program description
● javah
o create the header files
● javadoc
o creates HTML documents from source file.
● appletviewer
o execute java applets.

Application Programming Interface


Java API consist of a large number of classes and methods. The Java API classes are organized in
packages. Commonly used packages are following:
1. Input/Output package
Package: java.io
The classes in this package are used for input and output operations.
2. Language package
Package: java.lang
DEPARTMENT OF CSE Page 10
Object Oriented Programming 2019

The classes in this package are used for design of Java programming language.
3. Networking Package
Package: java.net
The classes in this package are used for networking purposes.
4. Utility package
Package: java.util
The classes in this package are used for date and time facilities, internationalization, and a random-
number generator
5. Text classes
Package: java.text
The classes in this package are used for handling text.
Java Runtime Environment (JRE)
JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE was
originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle
Corporation.
JRE consists of the following components:
Name of the component Elements of the component
Deployment technologies Deployment
Java Web Start
Java Plug-in
User interface toolkits Abstract Window Toolkit (AWT)
Swing
Input methods.
Integration libraries Interface Definition Language (IDL)
Java Database Connectivity (JDBC)
Remote Method Invocation (RMI)
Scripting.
base libraries Input/Output (I/O)
Beans
Math
Networking
Security
Lang and util base libraries lang and util
Versioning
Zip
Logging
Java Virtual Machine (JVM) Java HotSpot Client
Server Virtual Machines
Java Virtual Machine (JVM)
The JVM is an interpreter for the bytecode form of the program. It steps through one bytecode
instruction at a time. It is an abstract computing machine that enables a computer to run
a Java program. The JVM is a program that provides the runtime environment necessary for Java
programs to execute. Java programs cannot run without JVM .
1.4 JAVA SOURCE FILE STRUCTURE / STRUCTURE OF JAVA PROGRAM

DEPARTMENT OF CSE Page 11


Object Oriented Programming 2019

Java source file is a text file that contains one or more class definitions. Java source file must be
saved with an extension of “.java”.
To create Java source file, we need any of the following:
● Notepad − Text editor
● Netbeans − A Java IDE that is open-source and free
● Eclipse − A Java IDE developed by the eclipse open-source community

Figure: Java Source File Structure


● Main method class is essential.
● Others are optional
i) Documentation Section:
Document section is a set of comment lines giving the name of the program, the author name and
other details.
There are two types of comments.
1) //single line comments
2) /* …. */ multiple line comments.
Example:
● // Author : Joshna
● /* Matrix Addition Program */
ii) Package Statement :
A package is a pack (group) of classes, interfaces and other packages. Packages are used in Java
in order to prevent naming conflicts, to control access, to make searching/locating easier.

Rules:
o The package statement should be the first line in the source file. .
o If a package statement is not used, the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
Keyword: package
DEPARTMENT OF CSE Page 12
Object Oriented Programming 2019

Syntax
Package packagename;
Example:
package animals;
class Animal
{
public void eat();
public void travel();
}
iii) Import Statement:
The import statement makes external classes available to the current Java source program at the
time of compilation.
Keyword: import
Syntax
● To import a single class, we specify the name of the class
import packagename;
● To import all classes, we specify *.
import packagename.* ;
Examples
import mypackage.MyClass;
import mypackage.reports.accounts.salary.EmpClass;
import java.awt.*;
iv) Interface statemant
Interface is like a class but it includes group of method definitions. Interfaces are like a class that
includes a group of method declarations. It's an optional section.
Keyword: interface
Syntax
Interface interfacename
Example:
interface Animal
{
public void eat();
public void travel();
}
v) class definitions
A Java program may contain one or more class definitions.
Keyword:
class
Syntax
class classname
{
//statements

DEPARTMENT OF CSE Page 13


Object Oriented Programming 2019

}
Example:
class Animal
{
public void eat();
public void travel();
}
vi) main method class
Every java program requires the main method as the starting point of the program. This is an
essential part of a Java program. There may be many classes in a Java program, and only one
class defines the main method.
Example:
Class sample
{
Public static void main(String args[])
{
//statements
}
}
1.5 COMPILATION
Java source code is compiled into bytecode using javac compiler. The bytecodes are platform-
independent instructions for the Java VM. They are saved on the disk with the file extension .class.

Steps:
1. Java programs need to be compiled to bytecode.
2. When the bytecode is run, it needs to be converted to machine code.
Compiling the Program

DEPARTMENT OF CSE Page 14


Object Oriented Programming 2019

javac sample.java

Interpreting and Running the Program


java sample

Quick compilation procedure


To execute the first Java program, follow the steps:
1. Open text editor. Type the java program in a new text document.
2. Save the file as HelloWorld.java.
3. Next, open any command-line application. For example, Command Prompt on Windows;
and, Terminal on Linux and Mac OS.
4. Compile the Java source file using the command:
javac HelloWorld.java
5. Once the compiler returns to the prompt, run the application using the following command:
java HelloWorld
1.6 FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA
(Refer java source file structure page no:10)
Keywords
Keywords are reserved words that have fixed meaning. Examples of keywords are,
● if
● else
● int
● float
● char
Identifier / variable
Identifiers are sequence of characters that can be written using alphabets, digits, underscore, dollar
system.
Example: age, height, name1
Literals
Literals are the kind of variables for representing the constant variables. Types of literals are,
● Integer literal
● Floating point literal
● Boolean Literal
● Character Litearl
Operators
Operator in java is a symbol that is used to perform operations. Java provides a rich set of
operators to manipulate variables. For example: +, -, *, / etc.
All the Java operators can be divided into the following groups −
● Arithmetic Operators :
Multiplicative : * / %
Additive :+-
● Relational Operators
Comparison : < > <= >= instanceof
Equality : == !=
● Bitwise Operators

DEPARTMENT OF CSE Page 15


Object Oriented Programming 2019

bitwise AND : &


bitwise exclusive OR : ^
bitwise inclusive OR : |
Shift operator: << >> >>>
● Logical Operators
logical AND : &&
logical OR : ||
logical NOT : ~ !
● Assignment Operators: =
● Ternary operator: ? :
● Unary operator
Postfix : expr++ expr—
Prefix : ++expr --expr +expr -expr
Data Types
Data types represent the category of values used in program.. In java, there are two categories of
data types:
o Primitive data types
o Non-primitive data types

Figure: Data types in java


Constant
Constant means fixed value that do not change during the execution of program. Java constant is
divided into two types. They are,
1. Numeric constant
i.Integer constant
const int a =10;
ii.Real constant
const real a =10.5;

DEPARTMENT OF CSE Page 16


Object Oriented Programming 2019

2. Character constant
i.Char constant
const char a =’X’;
ii.String constant
const string s=”hello”;
Expressions:
An expression is a sequence of operators and operands that specifies the computation
Simple Expression
An expression that has only one operator is known as simple expression.
Example:
X=a+b;
X=++a;
Compound Expression
An expression that has more than one operator is known as compound expression.
Example:
X=a+b*c/f;
Arithmetic Expression
An expression consisting of arithmetic operators is known as arithmetic expression.
Example:
X=a+b;
Logical Expression
An expression consisting of logical operators is known as Logical expression.
Example:
X=a>b;
1.7 DEFINIG CLASSES IN JAVA
A class can be defined as a template/blueprint that describes the behavior/state of objects. Class
is a set of objects that share the common structure and behavior. The class is at the core of Java .
Syntax of class:
class classname
{
datatype instance-variable1;
datatype instance-variable2;
...
datatype instance-variableN;
datatype methodname1(parameter-list)
{
// body of method
}
...
datatype methodnameN(parameter-list)
{
// body of method
}
}
● The data, or variables, defined within a class are called instance variables.

DEPARTMENT OF CSE Page 17


Object Oriented Programming 2019

● The code is contained within methods.


● The methods and variables defined within a class are called members of the class.
Example:
A Simple Class class called Rectangle that defines two instance variables: length, width.
class Rectangle
{
double length;
double width;
void getdata( )
{ …..}
}
Characteristics of class:
1. Class must be declared using keyword ‘class’
2. Class definition must be written within {…..}
3. We create any number of objects belong to that class.

Object
An object is an instance of a class. Objects have states and behaviors.
Example: Dog
states: color, name, breed
behaviors : wagging the tail, barking, eating.
Syntax
i) Object declarartion
Classname objectname;
ii) Object instantiation
Objectname = new classname( );
Example:
Rectangle rect ;
Rect= new Rectangle( );
(OR)
Rectangle rect = new Rectangle( );
● rect will be an instance of Rectangle.
Accessing variables in class:
To access these variables, we will use the dot (.) operator.
Syntax
objectname. variable;
objectname. methodname( );
Example:
rect.length =10;
rect.getdata( );

Program:
//Rectarea.java
class Rectangle

DEPARTMENT OF CSE Page 18


Object Oriented Programming 2019

{
double length;
double width;
double area;
Rectangle (double x, double y)
{
length = x;
width = y;
}
double calculate( )
{
area = length * width;
return area;
}
}
class Rectarea
{
public static void main(String args[])
{
Rectangle rect1 = new Rectangle( 25,10);
double area1;
area1= rect.calculate();
System.out.println(“ AREA OF RECTANGLE = “ + area1);
}
}
Output:
javac Rectarea.java
java Rectarea
AREA OF RECTANGLE = 250
Predefined Class
Predefined class are already defined. Users cannot change the definition of predefined class. Some
of the predefined classes are,
● String
● StringBuffer
● Math
● Vector
● Hashtable
● Date
1.8 CONSTRUCTORS
Constructors are used for initializing new objects immediately when it is created .Every class has
a constructor. If the constructor is not defined in the class, the Java compiler builds a default
constructor for that class.

Characteristics / Rules of constructor:


● Constructor name must be same as the class name.

DEPARTMENT OF CSE Page 19


Object Oriented Programming 2019

● While a new object is created, at least one constructor will be invoked.


● Constructor on java cannot be abstract, final, static.
Synatx:
class classname
{
classname( )
{
……
}
}
Example:
class Rectangle
{
Rectangle ( )
{
…..
}
}

Types of Constructors

There are two type of constructor in Java:


1. No-argument constructor / Default constuctor:
A constructor that has no parameter is known as default constructor. If the constructor is not
defined in a class, then compiler creates default constructor for the class Default constructor
provides the default values to the object like 0, null etc. depending on the type.
Synatx:
class classname
{
classname( )
{
……
}
}
2. Parameterized Constructor
A constructor that has one or more parameters is known as parameterized constructor. If we want
to initialize fields of the class with your own values, then use parameterized constructor.
Synatx:
class classname
{
classname( parameter1, parameter2 )
{
……
}
}

DEPARTMENT OF CSE Page 20


Object Oriented Programming 2019

3. Constructor Overloading / Overloading Consructor


We can overload constructors in java i.e, the same class contain more than one constructor.
Synatx:
class classname
{
classname( )
{
……
}
classname( parameter1, parameter2 )
{
……
}
}
Program:
//Rectarea.java
class Rectangle
{
double length;
double width;
double area;
Rectangle( )
{
System.out.prinln(“ DEFAULT CONSTRUTOR”);
length=0;
width = 0;
area =0;
}
Recangle (double x, double y)
{
System.out.prinln(“ PARAMETERIZED CONSTRUTOR”);
length = x;
width = y;
}
double calculate( )
{
area = length * width;
return area;
}
}
class Rectarea
{
public static void main(String args[])
{
Rectangle rect1 = new Rectangle();

DEPARTMENT OF CSE Page 21


Object Oriented Programming 2019

double area1;
area1= rect1.calculate();
System.out.println(“ AREA OF RECTANGLE = “ + area1);
Rectangle rect2 = new Rectangle( 25,10);
double area2;
area2= rect2.calculate();
System.out.println(“ AREA OF RECTANGLE = “ + area2);
}
}
Output:
javac Rectarea.java
java Rectarea
DEFAULT CONSTRUTOR
AREA OF RECTANGLE = 0
PARAMETERIZED CONSTRUTOR
AREA OF RECTANGLE = 250
Constructors vs methods
Constructors Methods
Construcor name must be same as the class It is not necessary for the method in java.
name.
Constructors do not have any return type methods have the return type
Constructor is called only once at the time of Methods can be called any numbers of time.
Object creation
1.9 METHODS IN JAVA
A method is a collection of statement that performs specific task. In Java, method define the
behavior of that class.
Advantages of methods
● Program development and debugging are easier
● Increases code sharing and code reusability
● Increases program readability
● It makes program modular and easy to understanding
● It shortens the program length by reducing code redundancy
Types of methods
There are two types of methods in Java programming:
● Standard library methods (built-in methods or predefined methods)
● User defined methods
Standard library methods
The standard library methods are built-in methods in Java programming to handle tasks such as
mathematical computations, I/O processing, graphics, string handling etc. These methods are
already defined.
Packages Library Descriptions
Methods
java.lang.Math acos() Computes cosine of the argument
exp() Computes the exponent value
abs() Computes absolute value of argument

DEPARTMENT OF CSE Page 22


Object Oriented Programming 2019

log() Computes log value


sqrt() Computes square root of the argument
pow() Computes the power value
java.lang.String charAt() Returns the char value at the specified index.
concat() Concatenates two string
compareTo() Compares two string
indexOf() Returns the index of given character
toUpperCase() converts all of the characters in the String to
upper case
java.awt add() inserts a component
setSize() set the size of the component
setLayout() defines the layout manager
setVisible() changes the visibility of the component
Example: Program to compute square root of a given number using built-in method.
public class mathEx
{
public static void main(String[] args)
{
System.out.print("Square root of 14 is: " + Math.sqrt(14));
}
}
Output:
Square root of 14 is: 3.7416573867739413
User-defined methods
The methods created by user are called user defined methods.
Every method has the following.
● Method declaration
● Method definition
● Method call
Method Declaration
Syntax:
returntype method_name(parameter_list);
Here, the return_type specifies the data type of the value returned by method.
Method Definition
Method definition provides the actual body of the method.
Syntax:
return_type method_name(parameter_list)
{
// body of the method
}
Here,
return_type – Data type of the value returned by the method
method_name- Unique name to identify the method.
parameter_list- List of input parameters separated by comma.
method body – block of code enclosed within { and } braces to perform specific task

DEPARTMENT OF CSE Page 23


Object Oriented Programming 2019

Method Call
A method gets executed only when it is called.
The syntax for method call is.
Syntax:
methodname(parameters);
The number and type of parameters passed in method call should match exactly with the parameter
list mentioned in method prototype.
Classification of method based on arguments and return values
● Method with no arguments and no return value
● Method with no arguments and a return value
● Method with arguments and no return value
● Method with arguments and a return value.
i) Method with no arguments and no return value
In this type of method, no value is passed in between calling method and called method.
Program:
//Sample.java
class sample
{
void add( )
{
int a=10,b=20;
System.out.println("Sum:"+(a+b));
}
public static void main(String[] args)
{
sample s = new sample( );
s.add(); // method call with no arguments
}
}
Output:
javac sample.java
java sample
Sum : 30
ii) Method with no arguments and a return value
In this type of method, no value is passed from calling method to called method but a value is
returned from called method to calling method.
Program:
//Sample.java
class sample
{
int add( )
{
int a=10,b=20;
return(a+b);

DEPARTMENT OF CSE Page 24


Object Oriented Programming 2019

}
public static void main(String[] args)
{
int sum;
sample s=new sample( );
sum=s .add();
System.out.println("Sum:"+sum);
}
}
Output:
javac sample.java
java sample
Sum : 30
iii) Method with arguments and no return value
In this type of method, parameters are passed from calling method to called method but no value
is returned from called method to calling method.
Program:
//Sample.java
class sample
{
void add(int x,int y)
{
System.out.println("Sum:"+(x+y));
}
public static void main(String[] args)
{
int a=10,b=20;
sample s = new sample( );
s.add(a,b); // method call with arguments
}
}
Output:
javac sample.java
java sample
Sum : 30
iv) Method with arguments and a return value.
In this type of method, there is data transfer in between calling method and called method. Here,
when the method is called program control transfers to the called method with arguments, executes
the method, and return the value back to the calling method.
Program:
//Sample.java
class sample
{
int add(int x,int y)
{

DEPARTMENT OF CSE Page 25


Object Oriented Programming 2019

return(x+y);
}
public static void main(String[] args)
{
int a=10,b=20;
sample s = new sample( );
System.out.println("Sum:"+obj.add(a,b));
}
}
Output:
javac sample.java
java sample
Sum : 30
Parameter passing in Java
The commonly available parameter passing methods are:
● Pass by value / call by value
● Pass by reference / call by reference
i) Pass by Value
● Values of actual arguments are passed to formal parameter.
● Changes made in formal parametrs does not affect the actual argument.

Program:
//Sample.java
class sample
{
void add(int x,int y)
{
System.out.println("Sum:"+(x+y));
}
public static void main(String[] args)
{
int a=10,b=20;
sample s = new sample( );
s.add(a,b); // method call with arguments
}
}
Output:
javac sample.java
java sample
Sum : 30
ii) Pass by Reference
● Reference (address) of the actual parameters is passed to the local parameters in the method
definition.
● Changes made in formal parametrs affect the actual argument.
Program:

DEPARTMENT OF CSE Page 26


Object Oriented Programming 2019

//Sample.java
void swap(sample ref) // method to interchange values
{ /* Object is passed by reference. So the original object value
int temp;
a, b gets changed*/
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
Method Overloading
Method overloading is the process of having multiple methods with same name that differs in
parameter list. The number and the data type of parameters must differ in overloaded methods. It
is one of the ways to implement polymorphism in Java. When a method is called, the overloaded
method whose parameters match with the arguments in the call gets invoked.
Program for addition using Method Overloading
//sample.java
class MethodOverload
{
void add()
{
System.out.println("No parameters");
}
void add(int a,int b)
{
System.out.println("Sum:"+(a+b));
}
void add(int a,int b,int c)
{
System.out.println("Sum:"+(a+b+c));
}
}
class sample
{
public static void main(String[] args)
{
MethodOverload m=new MethodOverload();
m.add();
m.add(1,2);
m.add(1,2,3);
}
}
Output:
javac sample.java
java sample
No parameters
Sum:3

DEPARTMENT OF CSE Page 27


Object Oriented Programming 2019

Sum:6
Sum:35.7
finalize() method
The finalize() method is called the finalizer. finalize() is the method of Object class. The main
purpose of a finalizer is, however, to release resources used by objects before they’re removed
from the memory. finalize() method overrides to dispose system resources, perform clean-up
activities and minimize memory leaks.
Syntax
protected void finalize() throws Throwable
{
…………….
}
Program:
//sample.java
import java.util.*;
class sample
{
public static void main(String[] args)
{
sample s = new sample();
System.out.println("" + s.getTime());
System.out.println("Finalizing...");
s.finalize();
System.out.println("Finalized.");
}
}
Output:
javac sample.java
java sample

Mon Aug 21 16:02:29 IST 2017


Finalizing...
Finalized.
Press any key to continue . . .
1.10 ACCESS SPECIFIERS
Access specifiers or access modifiers specifies accessibility (scope) of a data member, method,
constructor or class. It determines whether a data or method in a class can be used or invoked by
other class or subclass.
Types of Access Specifiers
There are 4 types of java access specifiers:
1. private
2. default (no speciifer)
3. protected
4. public

DEPARTMENT OF CSE Page 28


Object Oriented Programming 2019

Access Modifiers default private protected public


Accessible inside the class Yes Yes Yes Yes
Accessible within the subclass Yes No Yes Yes
inside the same package

Accessible outside the package No No No Yes

Accessible within the subclass No No Yes yes


outside the package

i) public access modifier

The public access specifier has highest level of accessibility. Methods, class, and fields declared
as public are accessible by any class in the same package or in other package.
Program:
//sample.java
class Example
{
public int x=10;
}
class sample
{
public static void main(String[] args)
{
Example e = new Example ( );
System.out.println(e.x);
}
}
Output:
javac sample.java
java sample
10

ii) private access modifier

Private access modifier provides low level of accessibility. Private data fields and methods are
accessible only inside the class where it is declared. Encapsulation and data hiding can be achieved
using private specifier.
Program:
//sample.java
class Example
DEPARTMENT OF CSE Page 29
Object Oriented Programming 2019

{
private int x;
public int y;
}
class sample
{
public static void main(String[] args)
{
Example e = new Example ( );
System.out.println(e.x);
System.out.println(e.y);
}
}
Output:
javac sample.java
java sample
10
Error: cannot access y

iii) default access modifier

If the specifier is not mentioned, then it is treated as default. There is no default specifier keyword.
Using default specifier we can access class, method, or field from the same package, but not from
outside this package.
Program:
//sample.java
class Example
{
int x=10;
}
class sample
{
public static void main(String[] args)
{
Example e = new Example ( );
System.out.println(e.x);
}
}
Output:
javac sample.java
java sample
10

iv) protected access modifier

DEPARTMENT OF CSE Page 30


Object Oriented Programming 2019

Protected methods and fields are accessible within same class, subclass inside same package.
Program:
//sample.java
class A
{
protected int x=10;
}
class B extends A
{
protected int y=20;
}
class sample
{
public static void main(String[] args)
{
B b = new B ( );
System.out.println(b.x);
System.out.println(b.y);
}
}
Output:
javac sample.java
java sample
10
20
1.11 STATIC MEMBERS
Static Members can be static variable or static method or static block or static class or static import.
Static Members can be used accessed without using any object. The static keyword can be used
with:
● Variable (static variable or class variable)
● Method (static method or class method)
● Block (static block)
● Nested class (static class)
● import (static import)
i) Static variable
Variable declared with keyword static is a static variable. It is a class level variable commonly
shared by all objects of the class.
● Automatically initialized to 0.
● Static variables can be accessed directly in static and non-static methods.
Syntax:
● Declaration : static datatype variable
● Accessing : classname.staticvariable
Program:
//sample.java
class Example

DEPARTMENT OF CSE Page 31


Object Oriented Programming 2019

{
static int a=10;
}
class sample
{
public static void main(String[] args)
{
System.out.println(Example.a);
}
}
Output:
javac sample.java
java sample
10

ii) Static Method


The method declared with static keyword is known as static method. main() is most common static
method. A static method can directly access only static variables of class and directly invoke only
static methods of the class.
Syntax:
● Declaration : static datatype methodame
● Accessing : classname.staticmethodname( )
Program:
//sample.java
class Example
{
static void display()
{
System.out.println("WELCOME”);
}
}
class sample
{
public static void main(String[] args)
{
Example.display();
}
}
Output:
javac sample.java
java sample
WELCOME
iii) Static Block

DEPARTMENT OF CSE Page 32


Object Oriented Programming 2019

A static block is a block of code enclosed in braces, preceded by the keyword static. The
statements within the static block are first executed automatically before main when the class is
loaded into JVM. A class can have any number of static blocks.
Syntax: static
{
…………….
}
Example:
class sample
{
static
{
System.out.println("First static block");
}
public static void main(String[] args)
{
sample obj=new sample ();
}
}
Output:
javac sample.java
java sample
First static block
iv) static class
Nested class is a class declared inside another class. The inner class must be a static class declared
using keyword static.
Syntax:
class OuterClass
{
……..
static class InnerClass
{
……….
}
}
Example:
class Outer
{
static class Inner
{
void show( )
{
System.out.println(“welcome”);
}
}

DEPARTMENT OF CSE Page 33


Object Oriented Programming 2019

}
class sample( )
{
public static void main(String args[])
{
Outer.Inner obj=new Outer.Inner();
obj.show();
}
}
Output:
javac sample.java
java sample
welcome
v) Static Import
The static import allows the programmer to access any static members of imported class directly.
Syntax:
import static package_name;

Advantage:
● Less coding is required if you have access any static member of a class oftenly.
Disadvantage:
● Overuse of static import makes program unreadable and unmaintable.
Example:
import static java.lang.System.*;
class sample
{
public static void main(String args[])
{
out.println("Static Import Example");
}
}
Output:
javac sample.java
java sample
Static Import Example
1.12 COMMENTS
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement.
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment / Javadoc comment
1.12.1 SINGLE LINE COMMENT
The single line comment is used to comment only one line.

DEPARTMENT OF CSE Page 34


Object Oriented Programming 2019

Syntax:
//This is single line comment
Program:
class sample //Here, sample is a classname
{
public static void main(String[] args)
{
int i=10; //Here, i is a variable
System.out.println(i);
}
}
Output:
javac sample.java
java sample
10
1.12.2 MULTI LINE COMMENT
The multi line comment is used to comment multiple lines of code.

Syntax:
/*
This
is
multi line
comment
*/
Program:
class sample
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:
javac sample.java
java sample
10
1.12.3 DOCUMENTATION COMMENT / JAVADOC COMMENT
Javadoc is a JDK tool that generates API documentation from documentation comments. It is used
for generating Java code documentation in HTML format from Java source code.
Structure of Javadoc Comments

DEPARTMENT OF CSE Page 35


Object Oriented Programming 2019

Javadoc comments are any multi-line comments ("/** ... */") that are placed before class, field, or
method declarations. They must begin with a slash and two stars, end with with one star and slash.
Syntax:
/**
* This is documentation comment
*/
Types:
1. Classlevel comments
o provides decription and purpose of a class.
2. datamemberlevel comments
o provides decription and purpose of a datamember.
3. methodlevel comments
o provides decription and purpose of a method.
4. Constructorlevel comments
o provides decription and purpose of a constructor
Example:
/**
*sample class provides methods to get addition and subtraction of given 2 numbers.
* @author kavitha

*/
class sample
{
/**
* The add() method returns addition of given numbers
* @param a,b
*/
static int add(int a, int b)
{
return a+b;
}
/**
* The sub() method returns subtraction of given numbers.
* @param a,b
*/
public static int sub(int a, int b)
{
return a-b;
}
}
Compile it by javac tool:
javac sample.java
Create Documentation API by javadoc tool:
javadoc sample.java
commonly used Javadoc tags .

DEPARTMENT OF CSE Page 36


Object Oriented Programming 2019

Tag Description Syntax

@author It describes the author of a class @author name-text


@exception It describes exception in class @exception classname description
@param It describes parameter used in class @param parametername description
@return It describes return value @return description
@throws It describes throws exception in class @throws class-name description

1.13 DATATYPES
Data types represent the category of values used in program.. In java, there are two categories of
data types:
o Primitive data types
o Non-primitive data types

Figure: Data types in java


i) Primitive data types
There are 8 types of primitive data types.
● boolean data type
● byte data type
● char data type
● short data type
● int data type
● long data type
● float data type
● double data type

DEPARTMENT OF CSE Page 37


Object Oriented Programming 2019

Data Type Default Value Default size


Boolean false 1 bit
Byte 0 1 byte
Char '\u0000' 2 byte
Short 0 2 byte
Float 0.0f 4 byte
Int 0 4 byte
Long 0L 8 byte
Double 0.0d 8 byte
Boolean data type
● The Boolean data type is used to store only two possible values: true and false.
● The Boolean data type specifies one bit of information.

Example:
Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
Example:
byte a = 10;
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between (-216) to (216-
1).The char data type is used to store characters.
Example: char x = 'A';
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between
(-216) to (216- 1). Its default value is 0.
Example:
short s = 10000;
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between (-231)
to (231 -1). Its default value is 0.
Example:
int a = 100000;
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between (-263) to (263-
1). Its default value is 0.
Example:
long a = 100000L;
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save memory in large arrays of
floating point numbers. Its default value is 0.0F.

DEPARTMENT OF CSE Page 38


Object Oriented Programming 2019

Example: float f1 = 234.5f;


Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. Its default value
is 0.0d.
Example: double d1 = 12.3;
ii) Non Primitive dtata types
String:
Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’.
Syntax:
String stringname = “sequenceofstring”;
Example:
String str = "Geeks";

Array:
Array is a collection of elements of similar data type stored in contiguous memory location. It is
index based and the first element is stored at 0th index.

Syntax for declaration:


datatype[] arrayName;
Or
datatype arrayName [];
Example:
int[ ] a;
Program:
class Sample
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Output:
javac sample.java
java sample

DEPARTMENT OF CSE Page 39


Object Oriented Programming 2019

20
1.14 VARIABLES
A variable is a name which holds the value while the java program is executed. A variable is
assigned with a datatype. Variable is a name of memory location.
Synatx:
datatype variablename= value;
Example:
int a=10;
There are three types of variables in java:
1. Local variable
2. Instance variable
3. Static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. We can use this variable
only within that method. A local variable cannot be defined with "static" keyword.

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable.
It is not declared as static. It is called instance variable because its value is instance specific and
is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. We can create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Program:
class Sample
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Output:
javac sample.java
java sample
20
1.15 OPERATORS
Operator is a symbol that is used to perform operations. Java provides a rich set of operators to
manipulate variables. For example: +, -, *, / etc.
There are many types of operators. They are,
1. Arithmetic Operators :

DEPARTMENT OF CSE Page 40


Object Oriented Programming 2019

* / %
+ -
2. Relational Operators
Comparison : < > <= >= instanceof
Equality : == !=
3. Bitwise Operators
bitwise AND : &
bitwise exclusive OR : ^
bitwise inclusive OR : |
4. Logical Operators
logical AND : &&
logical OR : ||
logical NOT : ~ !
5. Assignment Operators: =
6. Ternary operator: ? :
7. instance of operator
8. Unary operator
Postfix : expr++ expr—
Prefix : ++expr --expr +expr -expr
i) Arithmetic Operators
Operator Description Example
+ (Addition) Adds values on either side of the operator. A + B will give 30
Subtracts right-hand operand from left-hand
- (Subtraction) A - B will give -10
operand.
Multiplies values on either side of the
* (Multiplication) A * B will give 200
operator.
Divides left-hand operand by right-hand
/ (Division) B / A will give 2
operand.
Divides left-hand operand by right-hand
% (Modulus) B % A will give 0
operand and returns remainder.
Program
class sample
{
public static void main(String args[])
{
int a = 10;
int b = 20;

System.out.println("add: " + (a + b) );
System.out.println("sub : " + (a - b) );
System.out.println("Mul: " + (a * b) );
System.out.println("Div: " + (b / a) );
System.out.println("modulo = " + (b % a) );
}

DEPARTMENT OF CSE Page 41


Object Oriented Programming 2019

}
Output:
javac sample.java
java sample
add: 30
sub: -10
Mul: 200
Div: 2
modulo: 0
ii) Relational Operators
Operator Description Example
Checks if the values of two operands are equal or
== (equal to) (A == B) is not true.
not, if yes then condition becomes true.
Checks if the values of two operands are equal or
!= (not equal to) not, if values are not equal then condition becomes (A != B) is true.
true.
Checks if the value of left operand is greater than the
> (greater than) value of right operand, if yes then condition becomes (A > B) is not true.
true.
Checks if the value of left operand is less than the
< (less than) value of right operand, if yes then condition becomes (A < B) is true.
true.
Checks if the value of left operand is greater than or
>= (greater than
equal to the value of right operand, if yes then (A >= B) is not true.
or equal to)
condition becomes true.
Checks if the value of left operand is less than or
<= (less than or
equal to the value of right operand, if yes then (A <= B) is true.
equal to)
condition becomes true.
Program
Class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
}
}
Output:
javac sample.java

DEPARTMENT OF CSE Page 42


Object Oriented Programming 2019

java sample
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = fals
iii) The Bitwise Operators
Operator Description Example
Binary AND Operator copies a bit to the (A & B) will give 12 which is
& (bitwise and)
result if it exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists (A | B) will give 61 which is
| (bitwise or)
in either operand. 0011 1101
Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
^ (bitwise XOR)
set in one operand but not both. 0011 0001
(~A ) will give -61 which is
Binary Ones Complement Operator is 1100 0011 in 2's complement
~ (bitwise compliment)
unary and has the effect of 'flipping' bits. form due to a signed binary
number.
Binary Left Shift Operator. The left
A << 2 will give 240 which is
<< (left shift) operands value is moved left by the number
1111 0000
of bits specified by the right operand.
Binary Right Shift Operator. The left
operands value is moved right by the A >> 2 will give 15 which is
>> (right shift)
number of bits specified by the right 1111
operand.
Shift right zero fill operator. The left
operands value is moved right by the
A >>>2 will give 15 which is
>>> (zero fill right shift) number of bits specified by the right
0000 1111
operand and shifted values are filled up with
zeros.
iv) Logical Operators
Operator Description Example
Called Logical AND operator. If both the operands
&& (logical and) (A && B) is false
are non-zero, then the condition becomes true.
Called Logical OR Operator. If any of the two
|| (logical or) operands are non-zero, then the condition becomes (A || B) is true
true.
Called Logical NOT Operator. Use to reverses the
! (logical not) logical state of its operand. If a condition is true then !(A && B) is true
Logical NOT operator will make false.
Program:
class sample

DEPARTMENT OF CSE Page 43


Object Oriented Programming 2019

{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output:
javac sample.java
java sample
a && b = false
a || b = true
!(a && b) = true
v) Assignment Operators
Operator Description Example
Simple assignment operator. Assigns values from C = A + B will assign value of A +
=
right side operands to left side operand. B into C
Add AND assignment operator. It adds right
+= operand to the left operand and assign the result to C += A is equivalent to C = C + A
left operand.
Subtract AND assignment operator. It subtracts
-= right operand from the left operand and assign the C -= A is equivalent to C = C – A
result to left operand.
Multiply AND assignment operator. It multiplies
*= right operand with the left operand and assign the C *= A is equivalent to C = C * A
result to left operand.
Divide AND assignment operator. It divides left
/= operand with the right operand and assign the result C /= A is equivalent to C = C / A
to left operand.
Modulus AND assignment operator. It takes
%= modulus using two operands and assign the result C %= A is equivalent to C = C % A
to left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
vi) Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions.

DEPARTMENT OF CSE Page 44


Object Oriented Programming 2019

Syntax:
Condition ? exp1 : exp2;
● If condition is true, exp1 is executed
● If condition2 is false, exp2 is executed
Program:
class sample
{
public static void main(String args[])
{
int a=10;
int b=20;
int c;
c= a> b? a: b;
System.out.println( “greatest number :” + c);
}
}
Output:
javac sample.java
java sample
greatest number : 20
vii) 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.
Program:
class sample
{
public static void main(String args[])
{
String name ="James";
boolean result = name instanceof String;
System.out.println( result );
}
}
Output:
javac sample.java
java sample
true
Precedence of Java Operator
Larger number means higher precedence.
Lower number means less precedence.
Precedence Operator Type Associativity
() Parentheses
15 [] Array subscript Left to Right
· Member selection

DEPARTMENT OF CSE Page 45


Object Oriented Programming 2019

++ Unary post-increment
14 Right to left
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 Right to left
- Unary minus
! Unary logical negation
~ Unary bitwise complement
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Program:
// Precedence.java
class Precedence
{
public static void main(String[] args)
{

DEPARTMENT OF CSE Page 46


Object Oriented Programming 2019

int a = 4, b = 2, c = 5, result;
result = a+b*c/2;
System.out.println(result);
}
}
Output:
javac Precedence.java
java Precedence
9
1.16 CONTROL FLOW
Java Control statements control the flow of execution in a java program, based on data values and
conditional logic used. There are three main categories of control flow statements;
● Selection statements: if, if-else and switch.
● Loop statements: while, do-while and for.
● Transfer statements: break, continue, return

1.16.1 SELECTION STATEMENTS


The selection statements checks the condition only once for the program execution.
i) if Statement:
The if statement executes a block of code only if the specified condition is true. If the condition is
false, then the if block is skipped and execution continues with the rest of the program.
Syntax:
if (condition)
{
………..
}
Program
class sample
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println("%d is largest",a);
if (b>a)
System.out.println("%d is largest",b);
}
}
Output:
javac sample.java
java sample
20 is largest
ii) if-else Statement
The if/else statement is an extension of the if statement. If the condition is true, the statements in
the if block are executed. If the condition is false, the statements in the else block are executed.

DEPARTMENT OF CSE Page 47


Object Oriented Programming 2019

Syntax:
if (condition)
{
………..
}
else
{
…………
}
Program1 : largest among two numbers
class sample
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println("%d is largest",a);
else
System.out.println("%d is largest",b);
}
}
Output:
javac sample.java
java sample
20 is largest
Program2 : odd or even number
class sample
{
public static void main(String[] args)
{
int a = 10;
if(a%2==0)
System.out.println("even number");
else
System.out.println("odd number");
}
}
Output:
javac sample.java
java sample
even number
iii) if-else-else if
It is a multiway selection statement. If the condition1 is true, the statements in the if block are
executed. If the condition1 is false and condition2 is true, the statements in the else if block are
executed. Otherwise, else block is exceuted.

DEPARTMENT OF CSE Page 48


Object Oriented Programming 2019

Syntax:
if (condition1)
{
………..
}
else if (condition2)
{
…………
}
else
{
………
}
Program : largest among three numbers
class sample
{
public static void main(String[] args)
{
int a = 10, b = 20,c=30;
if (a > b && a>c)
System.out.println("%d is largest",a);
else if(b>c)
System.out.println("%d is largest",b);
else
System.out.println("%d is largest",c);
}
}
Output:
javac sample.java
java sample
30 is largest
iv) nested if
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition)
{
if(condition)
{
………..
}
}

class sample

DEPARTMENT OF CSE Page 49


Object Oriented Programming 2019

{
public static void main(String[] args)
{
int age=20;
int weight=80;
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
}
}
}
Output:
javac sample.java
java sample
You are eligible to donate blood

v) Switch Case Statement


The switch case statement is also called as multi-way branching statement with several choices. A
switch statement is easier to implement than a series of if/else statements. The switch statement
begins with a keyword switch, followed by an expression.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

DEPARTMENT OF CSE Page 50


Object Oriented Programming 2019

Program2 : odd or even number


class sample
{
public static void main(String[] args)
{
int a = 10;
int r;
r=a%2;
switch(r)
{
case 0:
System.out.println("even number");
break;
case 1:
System.out.println("odd number");
break;
}
}
Output:
javac sample.java
java sample
even number
1.16.2 ITERATION STATEMENTS/LOOPING STATEMENTS
Iteration statements execute a block of code for several numbers of times until the condition is
true.

DEPARTMENT OF CSE Page 51


Object Oriented Programming 2019

i) while Statement
The while statement is repetitive control structure that executes a block of code while a condition
is true.
Syntax
while (condition)
{
// code block to be executed
}
Program: Printing Numbers from 1 to 5
class sample
{
public static void main(String[] args)
{
int i = 1;
while (i <= 5)
{
System.out.println(i);
i++;
}
}
}
Output:
javac sample.java
java sample
1
2
3
4
5
ii) do-while Loop Statement
The do/while loop is a variant of the while loop. The do—while loop executes atleast once without
checking the condition. It begins with the keyword do, followed by the statements of the loop.
Syntax
do
{
………. // code block to be executed
}while (condition);
Program: Printing Numbers from 1 to 5
class sample
{
public static void main(String[] args)
{
int i = 1;
do
{

DEPARTMENT OF CSE Page 52


Object Oriented Programming 2019

System.out.println(i);
i++;
} while(i<=5);
}
}
Output:
javac sample.java
java sample
1
2
3
4
5
iii) for Loop
The while statement is repetitive control structure that executes a block of code for a specified
number of times. It’s a counter controlled loop.
Syntax
for (initalization; condition; increment/decrement)
{
// code block to be executed
}
Program: Printing Numbers from 1 to 5
class sample
{
public static void main(String[] args)
{
for (int i = 1; i < =5; i++)
{
System.out.println(i);
}
}
}
Output:
javac sample.java
java sample
1
2
3
4
5

1.16.3 TRANSFER STATEMENTS

Transfer statements are used to transfer the flow of execution from one statement to another.

DEPARTMENT OF CSE Page 53


Object Oriented Programming 2019

i) Continue Statement

A continue statement stops the current iteration of a loop (while, do or for) continue with next
iteration.
Syntax:
continue;
Program: Printing Numbers from 1 to 5 except 3
class sample
{
public static void main(String[] args)
{
for (int i = 1; i < =5; i++)
{
if( i==3)
continue;
System.out.println(i);
}
}
}
Output:
javac sample.java
java sample
1
2
4
5

ii) break Statement

The break statement terminates the loop (for, while, do or switch statement). Break statement can
be used when we want to jump immediately to the statement following the enclosing control
structure.

Syntax:
break;

Program:
class sample
{
public static void main(String[] args)
{
for (int i = 1; i < =5; i++)
{
if( i==3)

DEPARTMENT OF CSE Page 54


Object Oriented Programming 2019

break;
System.out.println(i);
}
}
}
Output:
javac sample.java
java sample
1
2
1.17 ARRAYS
Array is a collection of elements of similar data type stored in contiguous memory location. It is
index based and the first element is stored at 0th index.

Advantages of Array

● Code Optimization: Multiple values can be stored under common name. Date retrieval or
sorting is an easy process.
● Random access: Data at any location can be retrieved randomly using the index.

Disadvantages of Array
● Inefficient memory usage: Array is static. It is not resizable at runtime based on number of
user’s input. To overcome this limitation, Java introduce collection concept.
Types of Array
There are two types of array.
● One Dimensional Array
● Multidimensional Array
1.17.1 ONE DIMENSIONAL ARRAY
Array with only one subscript is known as one dimensional array.
Syntax for declaration:
datatype[] arrayName;
Or
datatype arrayName [];
Example:
int[] a;

Instantiation of an Array

DEPARTMENT OF CSE Page 55


Object Oriented Programming 2019

Array can be created using the new keyword. To allocate memory for array elements, we must
mention the array size.
Syntax:
arrayname=new datatype[size];
Or
datatype[] arrayname=new datatype[size]; //declaration and instantiation

Example:
int[] a=new int[5];

Initialize array
Syntax:
datatype[] arrayname=new datatype[]{list of values separated by comma};
Or
datatype[] arrayname={ list of values separated by comma};
Example:
int[] a={12,13,14};
int[] a=new int[]{12,13,14};
Accessing array elements
The array elements can be accessed by using indices. The index starts from 0 and ends at (array
size-1). Each element in an array can be accessed using for loop.
Program: Storing and sorting the values of array
class arraysort
{
public static void main(String args[])
{
int a[5]={20,30,10,40};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
a.sort( );
System.out.prinln(“sorted array”);
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}

Output:
javac sample.java
java sample

DEPARTMENT OF CSE Page 56


Object Oriented Programming 2019

20
30
10
40
sorted array
10
20
30
40
1.17.2 TWO DIMENSIONAL ARRAY
Array with two subscript is known as one dimensional array.
Syntax for declaration:
datatype[ ][ ] arrayName;
Or
Datatype arrayName[ ] [];
Example:
int[ ][ ] a;
(OR)
int a[ ][ ];

Instantiation of an Array

Array can be created using the new keyword. To allocate memory for array elements, we must
mention the array size.
Syntax:
arrayname=new datatype[rowsize][columnsize];
Or
datatype[ ][ ] arrayname=new datatype [rowsize][columnsize];
Example:
int[ ][ ] a=new int[5][5];
Initialize array
Syntax:
datatype[][ ] arrayname=new datatype[ ][ ]{list of values separated by comma};
Or
datatype[ ][ ] arrayname={ list of values separated by comma};
Example:
int[ ][ ] a={12,13,14};
int[ ][ ] a=new int[ ][ ]{12,13,14};
Accessing array elements
The array elements can be accessed by using indices. The index starts from 0 and ends at (array
size-1). Each element in an array can be accessed using for loop.

DEPARTMENT OF CSE Page 57


Object Oriented Programming 2019

Program1: Martx Addition


// MatrixAddition.java
class MatrixAddition
{
public static void main(String args[])
{
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}
}
Output:
javac MatrixAddition.java
java MatrixAddition
2 6 8
4 8 6
4 6 9

DEPARTMENT OF CSE Page 58


Object Oriented Programming 2019

Program2: Martx Multiplication


//Matrixmul.java
class Matrixmul
{
public static void main(String args[])
{
int a[][]={{1,1,1},{1,2,3},{3,2,1}};
int b[][]={{1,2,3},{3,2,1},{1,4,2}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
javac Matrixmul.java
java Matrixmul
1 1 1
1 2 3
3 2 1

Martix subtraction: same as matrix addition only change c[i][j]=a[i][j]+b[i][j];


Matrix division: same as matrix addition only change c[i][j]=a[i][j]/b[i][j];
1.18 PACKAGES
A Package is a container that provides a way of grouping classes, interfaces, enumerations and
annotations together. It is similar to folders in computer.
Need for packages
● Reusability: Clases in the package can be easily reused.

DEPARTMENT OF CSE Page 59


Object Oriented Programming 2019

● Prevent naming conflicts - It is generally used to avoid naming conflicts. For example,
there can be two classes with same name in different packages, company.branch1.Employee and
company.branch2.Employee
● Make searching/locating and usage of classes, interfaces, enumerations and annotations
easier, etc.
● Provide access protection based on the access specifier used.
Types of Packages
Based on whether the package is defined by the user or not, packages are divided in two
categories:
● Built-in packages / Predefined packages
● User-defined packages / Java API packages
1.18.1 BUILT-IN PACKAGES
Java has various in-built packages which are already defined. These packages consist of a large
number of classes which are a part of Java API. Some of the commonly used built-in packages
are:
Built-in Definition Some Classes & Interfaces available
Package inside package
java.lang Basic package which is PrintWriter, String, StringBuilder,
automatically imported in all StringBuffer, All Wrapper Classes,
programs. Thread, Runnable, Throwable ,
Exception etc
java.io It contains classes related to Scanner, File , FileReader , FileWriter,
input/output operations BufferedReader,InputStreamReader,
IOException, FileNotFoundException
java.util It contains utility classes which Date , Calender, Stack , Queue ,
implement data structures like Vector , ArrayList, Set, HashMap
Linked List, Dictionary and
support for Date / Time
operations
java.applet Contains classes for creating Applet, AppletContext, AppletStub
Applets
java.awt Contain classes for Button, Label, TextArea, Menu,
implementing the components MenuItem
for graphical user interfaces
java.net Contain classes for supporting HttpCookie, ServerSocket, Socket,
networking operations URLConnection
java.sql classes used for JDBC Connection, DriverManager,
programming ResultSet, SQLException
1.17.2 USER-DEFINED PACKAGES
These are the packages that are defined by the user. The package keyword is used to create a
package in java. The general form of the package statement is:
Syntax:
package pkgname;
Here, pkgname is the name of the package.
Example:

DEPARTMENT OF CSE Page 60


Object Oriented Programming 2019

package MyPack;

Steps to create a Java package name MyPack:


1. Create package with package name.
2. Store all the classes and interfaces in the package MyPack.
3. Begin each of the .java files with a package declaration:
package myPack;
public class Addition
{
public static void add(int a,int b)
{
System.out.println("Sum:"+(a+b));
}
}
4. Save the file Addition.java inside the directory MyPack.
5. Compile the files by running javac command.
6. Access the classes and interfaces of package MyPack
import MyPack.Addition.*;
public class sample
{
public static void main(String args[])
{
Addition a=new Addition();
a.add(10,20);
}
}
Access Specifier Private Default Protected Public
Same class Yes Yes Yes` Yes
Same package subclass No Yes Yes` Yes
Same package non-
No Yes Yes` Yes
subclass
Different package
No No Yes` Yes
subclass
Different package non-
No No No Yes
subclass
Program:
// Addition.java
package MyPack;
public class Addition
{
public void add(int a,int b)
{
System.out.println(“Sum:”+(a+b));
}
}

DEPARTMENT OF CSE Page 61


Object Oriented Programming 2019

// Subtraction.java
package MyPack;
public class Subtraction
{
public void sub(int a,int b)
{
System.out.println(“Difference:”+(a-b));
}
}
//Package Usage
//sample.java
import MyPack.*;
public class sample
{
public static void main(String args[])
{
Addition a=new Addition();
a.add(10,20);
Subtraction s=new Subtraction();
s.sub(10,20);
}
}
Output:
javac sample.java
java sample
Sum:30
Difference:10

DEPARTMENT OF CSE Page 62


Object Oriented Programming 2019

PART A (2 Marks with Answers)


1. Define OOP.
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which may contain data (attributes) and code (procedures or methods).
Object= data+ function
OOP concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

2. Define Object and Class in java ( Nov/Dec 2018)


Object
An object is an instance of a class. Objects have states and behaviors.
Class
A class can be defined as a template/blueprint that describes the behavior/state of objects. Class
is a set of objects that share the common structure and behavior.
Example:
class Rectangle // Class declarartion
{
double length;
double width;
void getdata( )
{ …..}
}
Rectangle rect = new Rectangle( ); // object declarartion

3. Define Polymorphism.
Polymorphism is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.
● The word "poly" means many
● "morphs" means forms.
● So polymorphism means many forms.

4. What is meant by Abstraction.

DEPARTMENT OF CSE Page 63


Object Oriented Programming 2019

It refers to the act of representing essential features without including the background details or
explanations. It is one of the key concepts of object-oriented programming (OOP) languages. Its
main goal is to handle complexity by hiding unnecessary details from the user.

5. Define Encapsulation
Encapsulation is the process of combining data and functions into a single unit. In Java, the basis
of encapsulation is the class. Encapsulation achieves the concept of data hiding.
Data hiding: Data inside the class is accessible only through the function within the class

6. List the advantage of OOPs over Procedure-oriented programming language


Procedural Programming object-oriented programming
The program is written is based on the The program is written is based on the objects.
procedures.
Low efficiency High efficiency
POP follows Top Down approach. OOP follows Bottom Up approach.
To add new data and function in POP is not so OOP provides an easy way to add new data
easy. and function.
Example of POP are : C, VB, FORTRAN, Example of OOP are : C++, JAVA, VB.NET,
Pascal. C#.NET

7. Define JVM and byte code.


The JVM (Java Virtual Machine) is an interpreter for the byte code of the program. It steps
through one byte code instruction at a time. The JVM is a program that provides the
runtime environment necessary for Java programs to execute. Java programs cannot run without
JVM .
Bytecode is a highly optimized set of instructions designed to be executed by the java run-time
system, which is called as java virtual machine (JVM). JVM is an interpreter for bytecode.

8. List out the features of Java.


● Simple
● Secure
● Portable
● Object-oriented
● Robust
● Multithreaded
● Architecture-neutral
● Interpreted
● High performance
● Distributed
● Dynamic

9. List out the operator in Java


▪ Arithmetic Operators
▪ Increment and Decrement Operators
▪ Bitwise Operators

DEPARTMENT OF CSE Page 64


Object Oriented Programming 2019

▪ Relational Operators
▪ Logical Operators
▪ Assignment Operators

10. Name any three tags used in Java Doc Comment


Tag Description Syntax
@author It describes the author of a class @author name-text
@exception It describes exception in class @exception classname description
@param It describes parameter used in class @param parametername description
@return It describes return value @return description
@throws It describes throws exception in class @throws class-name description

11. Differentiable between break and continue statements?


continue break
A continue statement stops the current iteration The break statement terminates the loop (for,
of a loop (while, do or for) continue with next while, do or switch statement). Break
iteration. statement can be used when we want to jump
Syntax: immediately to the statement following the
continue; enclosing control structure.
Syntax:
break;

11. Define Access Specifier (Nov/Dec 2018)


Access specifiers or access modifiers specifies accessibility (scope) of a data member, method,
constructor or class. It determines whether a data or method in a class can be used or invoked by
other class or subclass.
Types of Access Specifiers
There are 4 types of java access specifiers:
● private
● default (no speciifer)
● protected
● public

12. What is a variable? How to declare variable in java?


A variable is a name which holds the value while the java program is executed. A variable is
assigned with a datatype. Variable is a name of memory location.
There are three types of variables in java:
4. Local variable

DEPARTMENT OF CSE Page 65


Object Oriented Programming 2019

5. Instance variable
6. Static variable
Synatx:
datatype variablename= value;
Example:
int a=10;

13. What is the use of comment?


The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement.
There are 3 types of comments in java.
1. // Single Line Comment
2. /*….*/ Multi Line Comment
3. /**……….*/ Documentation Comment / Javadoc comment

14. Write a note on conditional operator/ternary operator in Java.


Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions.
Syntax:
Condition ? exp1 : exp2;
● If condition is true, exp1 is executed
● If condition2 is false, exp2 is executed
Example:
c= a> b? a: b;

15. What are constructors?


Constructors are used for initializing new objects immediately when it is created .Every class has
a constructor. If the constructor is not defined in the class, the Java compiler builds a default
constructor for that class.
Characteristics / Rules of constructor:
● Constructor name must be same as the class name.
● While a new object is created, at least one constructor will be invoked.
● Constructor on java cannot be abstract, final, static.
Synatx:
class classname
{
classname( )
{
……
}
}
Example:

DEPARTMENT OF CSE Page 66


Object Oriented Programming 2019

class Rectangle
{
Rectangle ( )
{
…..
}
}

16. Distinguish between Default constructor and Parameterized Constructor


1. No-argument constructor / Default constuctor:
A constructor that has no parameter is known as default constructor. If the constructor is not
defined in a class, then compiler creates default constructor for the class. Default constructor
provides the default values to the object like 0, null etc. depending on the type.
Synatx:
class classname
{
classname( )
{
……
}
}
2. Parameterized Constructor
A constructor that has one or more parameters is known as parameterized constructor. If we want
to initialize fields of the class with your own values, then use parameterized constructor.
Synatx:
class classname
{
classname( parameter1, parameter2 )
{
……
}
}
17. What is a package? List its usage.
A Package is a container that provides a way of grouping classes, interfaces, enumerations and
annotations together. It is similar to folders in computer.
● Reusability: Classes in the package can be easily reused.
● Prevent naming conflicts - It is generally used to avoid naming conflicts. For example,
there can be two classes with same name in different packages, company.branch1.Employee and
company.branch2.Employee
● Make searching/locating and usage of classes, interfaces, enumerations and annotations
easier, etc.
● Provide access protection based on the access specifier used.

DEPARTMENT OF CSE Page 67


Object Oriented Programming 2019

18. What are the types of packages?


1. Built-in packages / Predefined packages
o Java has various in-built packages which are already defined.
o Example: java.lang, java.io
2. User-defined packages / Java API packages
o These are the packages that are defined by the user.
o Syntax:
package pkgname;
Example: package MyPack;
19. Write notes on static member.
● Static variable: It is a class level variable commonly shared by all objects of the class.
● Static Method: A static method can directly access only static variables of class and
directly invoke only static methods of the class.
● Static Block: A static block is a block of code enclosed in braces, preceded by the keyword
static. The statements within the static block are first executed automatically before main when
the class is loaded into JVM.

20. Define JavaDoc comment


Javadoc is a JDK tool that generates API documentation from documentation comments. It is used
for generating Java code documentation in HTML format from Java source code.
Structure of Javadoc Comments
Javadoc comments are any multi-line comments ("/** ... */") that are placed before class, field, or
method declarations. They must begin with a slash and two stars, end with with one star and slash.
Syntax:
/**
* This is documentation comment
*/

21. List the control statements in java.


Java Control statements control the flow of execution in a java program, based on data values and
conditional logic used. There are three main categories of control flow statements;
● Selection statements: if, if-else and switch.
● Loop statements: while, do-while and for.
● Transfer statements: break, continue

22. How do you create arrays in java?


Array is a collection of elements of similar data type stored in contiguous memory location. It is
index based and the first element is stored at 0th index.

DEPARTMENT OF CSE Page 68


Object Oriented Programming 2019

Syntax for declaration:


datatype[] arrayName;
Or
datatype arrayName [];
Example: int[] a;

23. What are the differences between static variable and instance variable?
Static Variables Instance Variables
1.Memory for static variable is allocated only 1. Memory for instance variable is allocated
once when class is loaded each time when an object is created
2. The memory is commonly shared by all 2. Each object memory is independent
objects of the class
3.Static variables are accessible without objects 3. Instance variables are accessible only using
objects
4. They are automatically initialized to default 4. Not initialized automatically
values
5. Example: static int no; 5. Example: int no=10;

24. What is a method and method overloading?


A method is a collection of statement that performs specific task. In Java, method define the
behavior of that class.
Types of methods
● Standard library methods (built-in methods or predefined methods)
● User defined methods
Method overloading is the process of having multiple methods with same name that differs in
parameter list. The number and the data type of parameters must differ in overloaded methods.
Example:
void add(int,int){}
void add(int,int,int){}
void add(double,double){}

25. List datatypes in java

DEPARTMENT OF CSE Page 69


Object Oriented Programming 2019

PART B (Possible Questions)


1. i) Explain the characteristics of OOPs ( 6) (Nov/Dec 2018)
ii) Explain the features and characteristic of java (7) (Nov/Dec 2018)
2. i) What is a method? How it is defined? Give example. (6) (Nov/Dec 2018)
ii) State the purpose of finalize method in java? With an example how finalize method be used
in java program. (Nov/Dec 2018)
3. i) Explain OOPS and its features. (7)
ii) .Summarize about the usage of constructor with an example using Java. (6)
4. i) What is class? How do you define a class and object in Java (7)
ii) Describe variables and operators in Java
5. Define and explain the control flow statements in Java with suitable examples (13)
6. i) Analyse & develop a simple Java program to sort the given numbers in increasing order.(7)
ii.Write a Java program to reverse the given number. (6)
7. i) Define Arrays. What is array sorting and explain with an example.
ii)Tabulate and explain documentation comments in Java.
8. Illustrate what is meant by package? How its types are created and implemented in Java. (13)
9. i). Classify the characteristics of Java.(6)
ii).Illustrate the working principles of Java Virtual Machine. (4)
iii) .Show with an example the structure of Java Program (3)

DEPARTMENT OF CSE Page 70


Object Oriented Programming 2019

PART C (Possible Questions)


1. Develop a Java application to generate Electricity bill. Create a class with the following
members: Consumer no., consumer name, previous month reading, current month reading, type
of EB connection (i.e domestic or commercial). Compute the bill amount using the following
tariff. If the type of the EB connection is domestic, calculate the amount to be paid as follows:
i. First 100 units - Rs. 1 per unit
ii. 101-200 units - Rs. 2.50 per unit
iii. 201 -500 units - Rs. 4 per unit
iv. > 501 units - Rs. 6 per unit
2. Evaluate a Java program to find a smallest number in the given array by creating one
dimensional array and two dimensional array using new operator.
3. Explain class hierarchy and explain its types with suitable examples.
4. Develop a Java application with Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate
Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the
inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for
staff club fund. Generate pay slips for the employees with their gross and net salary.

DEPARTMENT OF CSE Page 71


Object Oriented Programming 2019

ADDITIONAL PROGRAMS
1. Sum of two numbers
//sample.java
import java.io.*;
import java.util.Scanner;
public class sample
{
public static void main(String[] args)
{
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
javac sample.java
java sample
Enter First Number:

DEPARTMENT OF CSE Page 72


Object Oriented Programming 2019

121
Enter Second Number:
19
Sum of these numbers: 140
2. check Even or Odd number
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String args[])
{
int num;
System.out.println("Enter number:");
Scanner sc= new Scanner(System.in);
num = sc.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}

Output:
javac sample.java
java sample
Enter number:
78
Entered number is even
3. Calculate Area Of Circle
//area.java
import java.io.*;
import java.util.Scanner;
class area
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the radius:");
double r= sc.nextDouble();
double area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}
}
Output:

DEPARTMENT OF CSE Page 73


Object Oriented Programming 2019

javac area.java
java area
Enter the radius :7
Area of circle : 154.0
4. alphabet is vowel or consonant
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the character:");
char ch=sc.next( );
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )
System.out.println(ch + " is vowel");
else
System.out.println(ch + " is consonant");
}
}
Output:
javac sample.java
java sample
Enter the character: i
i is vowel
5. Reverse of a string
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String[ ] arg)
{
String str;
char ch;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string : ");
str=sc.nextLine();
System.out.println("Reverse of a tring:");
for(int j=str.length();j>0;--j)
{
System.out.print(str.charAt(j-1));
}
}

DEPARTMENT OF CSE Page 74


Object Oriented Programming 2019

}
Output:
javac sample.java
java sample
Enter a string : java
Reverse of a String: avaj
7. Reverse A Number
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String[] arg)
{
int a,res=0,n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();
while(n!=0)
{
a=n%10;
res=(res*10)+a;
n=n/10;
}
System.out.println("reverse of a number is "+res);
}
}

Output:
javac sample.java
java sample
Enter a number : 123
Reverse of a String: 321

8. Calculate Factorial
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();

DEPARTMENT OF CSE Page 75


Object Oriented Programming 2019

fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factoral="+fact);
}
}
Output:
javac sample.java
java sample
Enter a number : 5
factorial =120

9. fibnacci series
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String args[])
{
int n1=0,n2=1;
int n3,i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
count=sc.nextInt();
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
Output:
javac sample.java
java sample
0 1 1 2 3 5 8 13 21 34
10. Check Prime Number using a for loop
import java.io.*;
import java.util.Scanner;
public class sample

DEPARTMENT OF CSE Page 76


Object Oriented Programming 2019

{
public static void main(String[] args)
{
int num;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
num=sc.nextInt();
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
flag = true;
break;
}
}
if (flag=true)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Output:
javac sample.java
java sample
Enter a number : 9
9 is not a prime number.

UNIT II –INHERITANCE AND INTERFACES

DEPARTMENT OF CSE Page 77


Object Oriented Programming 2019

Inheritance – Super classes- sub classes –Protected members – constructors in sub


classes- the Object class – abstract classes and methods- final methods and classes –
Interfaces – defining an interface, implementing interface, differences between classes
and interfaces and extending interfaces - Object cloning -inner classes, Array Lists –
Strings

DEPARTMENT OF CSE Page 78


Object Oriented Programming 2019

INHERITANCE AND INTERFACES


2.1 INHERITANCE- SUPERCLASS AND SUBCLASSES
Inheritance is the process of forming new class from the existing class.
● Existing class is also called as parent class or base class or super class.
● New class is also called as child class or derived class.

Example:

DEPARTMENT OF CSE Page 79


Object Oriented Programming 2019

● Animal is the base class.


● Mammal and reptile are the deived class of Animal. So they inherits the properties from
Animal base class.
● Whale and Dog are the derived class of Mammal. So they inherits the properties from
mammal base class.
Advantage of Inheritance
● Reusability
● Reducing the code size of program.
● Sub class inherits all the properties from base class.
Syntax:
class Subclass-name extends Superclass-name
{
…………….//methods and fields
}
Here, the extends keyword indicates creating a new class that derives from an existing class.
Note: The constructors of the superclass are never inherited by the subclass

Types of inheritance
There are four types of inheritance. They are,
1. Single inheritance
2. Multi level inheritance
3. Hiearchical inheritance
4. Hybrid inheritance
i) Single Inheritance :
In single inheritance, there is one super class and one sub class(a subclass inherit the
features of one superclass)

DEPARTMENT OF CSE Page 80


Object Oriented Programming 2019

Synatx:
Class superclass
{
…………
}
class Subclass extends Superclass
{
…………….
}

Employee

Program: name= “ kavitha”


//Single.java
class Employee printemp()
{
String name=”kavitha”;
void printgen( ) extends
{
System.out.println("NAME:”+name);
} Manager

} id= 100
class Manager extends Employee
printman()
{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class single
{
public static void main(String[] args)
{
Manager m= new Manager( );
m.printemp( );
m.printman( );
}
}
Output:
javac single.java
java single
NAME : kavitha
ID : 100
ii) Multilevel Inheritance:
DEPARTMENT OF CSE Page 81
Object Oriented Programming 2019

In Multilevel Inheritance, there ia s a sub class with one super class but that super class is
derived from another super class (a subclass inherit the features of one superclass)

Here,
● ClassA is the super class.
● ClassB is the immediate super class.
● ClassC is the sub class.
Syntax:
class classA
{
…………
}
class classB extends classA
{
…………….
}
class classC extends classB
{
…………….
}
Example

Employee

Program: name= “ kavitha”


//multilevel.java
class Employee printemp( )
{
String name=”kavitha”;
void printgen( ) extends
{
System.out.println("NAME:”+name);
} Manager

} id= 100
class Manager extends Employee
printman( )

DEPARTMENT OF CSE Page 82


extends
Object Oriented Programming 2019

{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class Generalmanager extends Manager
{
int salary = 10000;
void printgen( )
{
System.out.println("SALARY :”+salary);
}
}
class multillevel
{
public static void main(String[] args)
{
Generalmanager g= new Generalmanager( );
g.printemp( );
g.printman( );
g.printgen( );
}
}
Output:
javac multillevel.java
java multillevel
NAME : kavitha
ID : 100
SALARY :10000
iii) Hierarchical Inheritance:
In Hierarchical Inheritance, there is one super class and more than one sub classes (a subclass
inherit the features of one superclass)

DEPARTMENT OF CSE Page 83


Object Oriented Programming 2019

Here,
● ClassA is the super class.
● ClassB and classC are the sub class.
Syntax:
class classA
{
…………
}
class classB extends classA
{
…………….
}
class classC extends classA
{
…………….
}

Employee

name= “ kavitha”
Program:
//hierarchichal.java printemp( )
class Employee
{
String name=”kavitha”;
void printgen(
extends) extends
{
System.out.println("NAME:”+name);
Manager Programmer
}
id= 100 Language=”java”
}
class Manager extends
printman( ) Employee printgen( )
{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class Programmer extends Employee
{
String language=”java”;
void printpro( )
{
System.out.println("LANGUAGE: +language);
}
}
DEPARTMENT OF CSE Page 84
Object Oriented Programming 2019

class hierarchichal
{
public static void main(String[] args)
{
Manager m= new Manager( );
Programmer p =new Programmer( );
m.printemp( );
m.printman( );
p.printpro( );
}
}
Output:
javac hierarchichal.java
java hierarchichal
NAME : kavitha
ID : 100
LANGUAGE: java

iv) Hybrid inheritance


The process of combining more than one inheritance (single, multilevel, Hierarchichal) is called
as Hybrid inheritance.

Here,
● ClassA is the super class.
● ClassB and classC are the sub class of ClassA.
● ClassD is the subclass of classC
Syntax:

DEPARTMENT OF CSE Page 85


Object Oriented Programming 2019

class classA
{
…………
}
class classB extends classA
{
…………….
}
class classC extends classA
{
…………….
}
class classD extends classC
{
…………….
}

Example:

Program: Employee
//hybrid.java
class Employee name= “ kavitha”
{
printemp( )
String name=”kavitha”;
void printgen( )
{
System.out.println("NAME:”+name);
extends extends
}

} Manager Programmer
class Manager extends Employee
{
id= 100 Language=”java”
int printman(
id=100; ) printgen( )
void printman( )
{
System.out.println("ID: “+id);
extends
}
} Generalmanager
class Programmer extends Employee
{ salary= 10000
String language=”java”;
printgen( )

DEPARTMENT OF CSE Page 86


Object Oriented Programming 2019

void printpro( )
{
System.out.println("LANGUAGE: +language);
}
}
class Generalmanager extends Manager
{
int salary = 10000;
void printgen( )
{
System.out.println("SALARY :”+salary);
}
}
class hybrid
{
public static void main(String[] args)
{
Generalmanager g= new Generalmanager( );
Programmer p =new Programmer( );
g.printemp( );
g.printman( );
g.printgen( );
p.printpro( );
}
}
Output:
javac hybrid.java
java hybrid
NAME : kavitha
ID : 100
SALARY : 10000
LANGUAGE: java
2.2 PROTECTED MEMBERS
Protected methods and fields are accessible within same class, subclass inside same package. It is
mainly used in inheritance. Protected memebers can be,
● Protected data
● Protected method
● Protected class
Access Modifiers default private protected public
Accessible inside the class Yes Yes Yes Yes

Accessible within the subclass Yes No Yes Yes


inside the same package

DEPARTMENT OF CSE Page 87


Object Oriented Programming 2019

Accessible outside the package No No No Yes

Accessible within the subclass No No Yes yes


outside the package

Keyword:
protected
Program:
//Sample.java
class Employee
{
String name=”kavitha”;
protected void printgen( )
{
System.out.println("NAME:”+name);
}

}
class Manager extends Employee
{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class sample
{
public static void main(String[] args)
{
Manager m= new Manager( );
m.printemp( );
m.printman( );
}
}
Output:
javac sample.java
java sample
//ERROR: cannot acess

2.3 CONSTRUCTORS IN SUBCLASSES

DEPARTMENT OF CSE Page 88


Object Oriented Programming 2019

The constructors of the superclass are never inherited by the subclass. super() can be used to
invoke immediate parent class constructor.
Use of super keyword:
● Access superclass variables
● Access superclass method
● Access superclass constructor
Use of super with constructors:
The super keyword can also be used to invoke the parent class constructor.
Syntax:
super();
super(parameterlist);
● super() must always be the first statement inside a subclass constructor.
Constructor chaining:
When we invoke a super() statement within a subclass constructor, we are invoking the immediate
super class constructor
Prgram:
class A
{
A( )
{
System.out.println("In A class Constructor");
}
}
class B extends A
{
B( )
{
super();
System.out.println("In B class Constructor");
}
}
class C extends B
{
C( )
{
super();
System.out.println("In C class Constructor");
}
}
class sample
{
public static void main(String[] args)
{
C ca = new C( );
}

DEPARTMENT OF CSE Page 89


Object Oriented Programming 2019

}
Output:
javac sample.java
java sample
In A class Constructor
In B class Constructor
In C class Constructor
2.4 THE OBJECT CLASS
The Object class is the parent class of all the classes in java by default (directly or indirectly).
The java.lang.Object class is the root of the class hierarchy. Some of the Object class are Boolean,
Math, Number, String etc.

Object

Boolean Character Number Math String StringBuffer

Byte Short Integer Long Float Double

Some of the important methods defined in Object class are listed below.
Object class Methods Description
boolean equals(Object) returns true if two references point to the same object.
String toString() Converts object to String
void notify()
void notifyAll() Used in synchronizing threads
void wait()
void finalize() called just before an object is garbage collected
Object clone() Returns a new object that are exactly the same as the current object
int hashCode() Returns a hash code value for the object.

i) toString()
It converts object to String
Syntax:
Obj.toString( );
Output format:
classname@memoryaddress
Program:
//sample.java
class sample
{

DEPARTMENT OF CSE Page 90


Object Oriented Programming 2019

public static void main(String[] args)


{
Sample s =new sample( );
System.out.println(s.toString());
}
protected void finalize() // finalize() is called just once on an object
{
System.out.println("finalize method called");
}
}
Output:
javac sample.java
java sample
sample@2a139a55
finalize method called
ii) equals(object)
It returns true if two references point to the same object.
Synatx:
obj1.equals(obj2);
Program:
//sample.java
class sample
{
public static void main(String[] args)
{
Integer x = new Integer(50);
Float y = new Float(50f);
System.out.println(x.equals(y));
System.out.println(x.equals(50));
}
}
Output:
javac sample.java
java sample
false
true
2.5 ABSTRACT CLASSES AND METHODS
Abstract class:
A class that is declared as abstract is known as abstract class. Abstract class can have abstract and
non-abstract methods. It cannot be instantiated.
Keyword :
abstract
Syntax:
abstract class classname
{

DEPARTMENT OF CSE Page 91


Object Oriented Programming 2019

………
}
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method. Abstract method can never be final and static.
Note:
A normal class (non-abstract class) cannot have abstract methods.
Syntax:
abstract returntype methodname ();
Rules
1. Abstract class can have abstract and non-abstract methods
2. A normal class (non-abstract class) cannot have abstract methods.
3. Abstract class cannot be instantiated.
4. Abstract method can never be final and static.
5. Abstract classes can have Constructors, Member variables and Normal methods.
Program:
//sample.java
abstract class A
{
abstract void display();
}
class B extends A
{
void display()
{
System.out.println("In B class ");
}
}
class C extends A
{
void display()
{

System.out.println("In C class”);
}
}
class sample
{
public static void main(String[] args)
{
B b =new B( );
C ca = new C( );
b.display( );
ca.display( );
}

DEPARTMENT OF CSE Page 92


Object Oriented Programming 2019

}
Output:
javac sample.java
java sample
In B class
In C class

Abstract class method


It may or may not have abstract methods It cannot have abstract method
It cannot be instantiated It cannot be instantiated
The keyword abstract is used for declaring The keyword class is used for declaring

It act as parent class. It act as parent class or sub class.


Syntax: Syntax:
abstract class classname class classname
{ {
…….. ……..
} }
2.6 FINAL METHODS AND CLASSES
The final keyword in java is used to restrict the user. The java final keyword can be applied to:
❖ variable
❖ method
❖ class
Java final variable - To prevent constant variables
Java final method - To prevent method overriding
Java final class - To prevent inheritance
Figure: Uses of final in java
i) final Method
A Java method with the final keyword is called a final method and it cannot be overridden in the
subclass. It is used to prevent method overriding.
Syntax:
final datatype methodname( )
{
………
}
Program:
//sample.java
class A
{
final void display()
{
System.out.println("A class");

DEPARTMENT OF CSE Page 93


Object Oriented Programming 2019

}
}
class B extends A
{
void display()
{
System.out.println("B class");
}
}
class sample
{
public static void main(String args[])
{
B obj= new B();
obj.display();
}
}
Output:
javac sample.java
java sample
/sample.java:11: error: display() in B cannot override display() in A
Points to be remembered while using final methods:
❖ Private methods of the superclass are automatically considered to be final.
❖ Since the compiler knows that final methods cannot be overridden by a subclass, so these
methods can sometimes provide performance enhancement by removing calls to final methods and
replacing them with the expanded code of their declarations at each method call location.
ii) Final Class
❖ Final class is a class that cannot be extended i.e. it cannot be inherited.
❖ A final class can be a subclass but not a superclass.
❖ Declaring a class as final implicitly declares all of its methods as final.
Syntax:
final class classname public final class A
{ {
OR
//code //code
} }
Program:
//sample.java
final class A
{
void display()
{
System.out.println("A class");
}
}
class B extends A

DEPARTMENT OF CSE Page 94


Object Oriented Programming 2019

{
void display()
{
System.out.println("B class");
}
}
class sample
{
public static void main(String args[])
{
B obj= new B();
obj.display();
}
}
Output:
javac sample.java
java sample
/sample.java:11: error: B cannot inherit from final A
2.7 INTERFACES
An interface is a reference type in Java. It supports multiple inheritance.
● It is similar to class.
● Interface may also contain abstract methods, default methods, static methods
● An interface can contain any number of methods.
● It gives outline for class
2.7.1 Defining an Interface
An interface is defined by using keyword “interface”
Keyword: interface
Syntax:
interface interfacename
{
datatype instance-variable1;
datatype instance-variable2;
...
datatype instance-variableN;
datatype methodname1(parameter-list)
{
// body of method
}
...
datatype methodnameN(parameter-list)
{
// body of method
}
}
Example:

DEPARTMENT OF CSE Page 95


Object Oriented Programming 2019

interface Animal
{
public void eat();
public void travel();
}
2.7.2 Implementing an Interface
Once an interface has been defined, one or more classes can implement that interface.
Keyword: implements
Syntax:
class classname implements interfacename
{
// class-body
}
❖ A class can implement more than one interface at a time.
Example:
Class Mammal implements Animal
{
…………
}
2.7.3 Extending interface
The interface can be extended using multiple inheritance.
Keyword: extends
Syntax:
interface interface
{
…………
}
interface interface extends superinterface
{
…..
}

Program: Multiple inheritance in java


interface Printable
{
void print();
DEPARTMENT OF CSE Page 96
Object Oriented Programming 2019

}
interface Showable
{
void show();
}
class A implements Printable,Showable
{
void print()
{
System.out.println("Hello");
}
void show()
{
System.out.println("Welcome");}
}
}
class sample
{
public static void main(String args[])
{
A obj = new A ();
obj.print();
obj.show();
}
}

Output:
javac sample.java
java sample
Hello
Welcome
2.7.4 Diffference between class and interface
Parameters Class Interface
Basic A class can be instantatied An interface can never be instantiated
Keyword class interface
The members of a class can be private,
The members of an interface are
Access specifier
public or protected. always public.
Methods The methods of a class are defined The methods are not defined
An interface can extend multiple
A class can implement any number of
inheritance interfaces but cannot implement any
interfaces
interface.
Inheritance
extends implements
keyword

DEPARTMENT OF CSE Page 97


Object Oriented Programming 2019

An interface can never have a


A class can have constructors to
Constructor constructor as there is hardly any
initialize the variables.
variable to initialize.
class class_Name interface interfaceName
{ {
Declaration //fields //fields
Syntax //Methods //Methods
} }

Diffference between abstract class and interface


Parameters Abstract Class Interface
Keyword abstract interface
The members of a abstract class can be The members of an interface are
Access specifier
public or protected. always public.
Inheritance
extends implements
keyword
An abstract class can have both abstract An interface can have only abstract
methods
and concrete methods methods
An abstract class can extend only one An interface can extend any number
extends
class or one abstract class at a time of interfaces at a time
abstract class className interface interfaceName
{ {
Declaration //fields //fields
Syntax //Methods //Methods
} }

2.8 OBJECT CLONING


Object cloning refers to creation of exact copy of an object. It creates a new instance of the class of current
object .
Keyword: clone( )
Example:
Student s = new Student( );
Student copy= s.clone( );
Types of cloning
1. Shallow cloning
2. Deep Cloning

DEPARTMENT OF CSE Page 98


Object Oriented Programming 2019

Program:
//sample.java
import java.io.*;
class student
{
int a = 10;
int b =20;
}
class sample
{
public static void main(String[] args)
{
student s1 = new student( );
System.out.println(“a=”+ s1.a);
System.out.println(“a=”+ s1.b);
student s2=s1.clone();
System.out.println(“a=”+ s2.a);
System.out.println(“a=”+ s2.b);
}
}

Output:
javac sample.java
java sample
a = 10
b =20
a = 10
b =20

DEPARTMENT OF CSE Page 99


Object Oriented Programming 2019

2. 9 INNER CLASSES( NESTED CLASSES )

Inner classes are the non staic nested classes. It can be used as the security mechanism in Java. It
is a class that is defined inside the other class.

OUTER
Syntax CLASS
of Inner class
class Outer_class
{ INNER
class Inner_classCLASS
{
…….
}
}
Advantage of java inner classes
● Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class
● Nested classes are used to develop more readable and maintainable code
● Code Optimization: It requires less code to write.
Types of inner class:
1. Non-static nested class (inner class)
a. Member inner class
b. Anonymous inner class
c. Local inner class
2. Static nested class

Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing interface or extending class. Its name is
Class decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.

i) Member Inner Class

The Member inner class is a class written within another class.


Syntax of Inner class
class Outer_class
{
class Inner_class
{
…….

DEPARTMENT OF CSE Page 100


Object Oriented Programming 2019

}
}
Program:
//sample.java
class outer
{
class Inner
{
void display()
{
System.out.println("This is an inner class”);
}
public static void main(String args[])
{
outer out = new outer( );
outer.inner in = out.new inner( );
in.display( );
}
}
}
Output:
javac sample.java
java sample
This is an inner class
ii) Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class. The
anonymous inner classes can be created and instantiated at the same time.
Program:
//sample.java

abstract class Outer

abstract void display();

class Inner

public static void main(String args[])

DEPARTMENT OF CSE Page 101


Object Oriented Programming 2019

Outer out=new Outer()

void display()

System.out.println("This is the anonymous inner class");

};

out.display();

Output:
javac sample.java
java sample

This is the anonymous inner class

iii) local Inner Class

A class can be written within a method, is called as local inner class.

Program:
//sample.java
class outer
{
void display()
{
class Inner
{

void print()
{
System.out.println("This is an inner class”);
}
}
Inner in = new Inner( );

DEPARTMENT OF CSE Page 102


Object Oriented Programming 2019

in.print( );
}
public static void main(String args[])
{
outer out = new outer( );
out.display( );
}
}
Output:
javac sample.java
java sample
This is an inner class
2.10 ARRAYLIST
ArrayList is a part of collection framework. It is present in java.util package. It provides us
dynamic arrays in Java.
● ArrayList inherits AbstractList class and implements List interface.
● ArrayList is initialized by a size; however the size can increase if collection grows or shrink
if objects are removed from the collection.
● Java ArrayList allows us to randomly access the list.
● ArrayList cannot be used for primitive types, like int, char, etc.
● ArrayList in Java is much similar to vector in C++.

Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

DEPARTMENT OF CSE Page 103


Object Oriented Programming 2019

ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the
collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

Methods of Java ArrayList

Method Description
void add(int index, Object It is used to insert the specified element at the specified position index in a list.
element)
boolean addAll(Collection c) It is used to append all of the elements in the specified collection

void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified
element

Object[] toArray() It is used to return an array containing all of the elements in this list in the correct
order.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection into this list,
Collection c) starting at the specified position.
Object clone() It is used to return a shallow copy of an ArrayList.

Program:
//sample.java
import java.util.*;
class Arraylistexample
{
public static void main(String args[])
{
ArrayList<String> a1=new ArrayList<String>();
a1.add("Bala");
a1.add("Mala");
a1.add("Vijay");
ArrayList<String> a2=new ArrayList<String>();
a2.add("kala");
a2.add("Banu");
a1.addAll(a2);
Iterator itr=a1.iterator();

DEPARTMENT OF CSE Page 104


Object Oriented Programming 2019

while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
javac sample.java
java sample
Bala
Mala
Vijay
2.11 JAVA STRING
Strings are defined as an array of characters. It must be specified within double quotes. The
difference between a character array and a string is the string is terminated with a special character
‘\0’.
The string objects can be created using two ways.
1. By String literal
2. By new Keyword
i) String Literal
Java String literal is created by using double quotes.
Syntax:
String stringname = “sequenceofcharacters”;
Example:
String str = "java”;
ii) By new keyword
Syntax:
String stringname = new String(“sequenceofcharacters”);
Example:
String str = new String("java”);

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

String class methods

DEPARTMENT OF CSE Page 105


Object Oriented Programming 2019

Method Description
char charAt(int index) returns char value for the particular index
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
String substring(int beginIndex, returns substring from given begin index to end index
int endIndex)
boolean equals(Object another) checks the equality of string with object
boolean isEmpty() checks if string is empty

String concat(String str) concatenates specified string

String replace(char old, char new) replaces all occurrences of specified char value
String replace(CharSequence old, replaces all occurrences of specified CharSequence
CharSequence new)

int indexOf(int ch) returns specified char value index

int indexOf(int ch, int fromIndex) returns specified char value index starting with given
index
int indexOf(String substring) returns specified substring index
int indexOf(String substring, int returns specified substring index starting with given
fromIndex) index

String toLowerCase() returns string in lowercase.


String toLowerCase(Locale l) returns string in lowercase using specified locale.

String toUpperCase() returns string in uppercase.

String toUpperCase(Locale l) returns string in uppercase using specified locale.


String trim() removes beginning and ending spaces of this string.
Program:
//stringhandling.java
class stringhandling
{
public static void main(String[] args)
{
String str1 = "object oriented";
String str2 = "java";
System.out.println(Original String:);
System.out.println(“s1=”+s1);
System.out.println(“s2=”+s2);
//substring
DEPARTMENT OF CSE Page 106
Object Oriented Programming 2019

System.out.println(s1.substring(7,13);
//equals
if(s1.equals(s2))
System.out.println(“same”);
else
System.out.println(“different”);
//uppercase
System.out.println(s1.toUppercase());
//lowercase
System.out.println(s2.toLowercase());
//length
System.out.println(s1.length());
//charat()
System.out.println(s1.charAt(5));
//indexof
System.out.println(s1.indexOf(t));
if(s1.compare(s2)
System.out.println(“s1<s2”);
else
System.out.println(“s1>s2”);
//trim
System.out.println(s1.trim());
//concatenation
System.out.println(s1.concat(s2));
//append
System.out.println(s1.append(s2));\
}
}
Output:
javac stringhandling.java
java stringhandling
s1=object oriented
s2= java
object oriented java
oriented
same
OBJECT
Java
14
t
5
s1>s2
objectoriented
object oriented java
object oriented java

DEPARTMENT OF CSE Page 107


Object Oriented Programming 2019

PART A (2 Marks with Answers)


1. What is object cloning? ( Nov/Dec 2018)
Object cloning refers to creation of exact copy of an object. It creates a new instance of the class
of current object .
Keyword: clone( )
Example:
Student s = new Student( );
Student copy= s.clone( );
Types of cloning

DEPARTMENT OF CSE Page 108


Object Oriented Programming 2019

1. Shallow cloning
2. Deep Cloning
2. What is class hierarchy? Give example. ( Nov/Dec 2018)
The class hierarchy defines the inheritance relationship between the classes. The root of the
class hierarchy is the class Object. Every class in Java directly or indirectly extends (inherits
from) this class.
● Existing class is also called as parent class or base class or super class.
● New class is also called as child class or derived class.
3. What is meant by Inheritance? List types (OR) Define super class and subclass.
Inheritance is the process of forming new class from the existing class.
● Existing class is also called as parent class or base class or super class.
● New class is also called as child class or derived class.

There are four types of inheritance. They are,


o Single inheritance
o Multi level inheritance
o Hiearchical inheritance
o Hybrid inheritance
4. How do you implement multiple inheritance in Java?
Java does not allow multiple inheritance:
● To reduce the complexity and simplify the language
● To avoid the ambiguity caused by multiple inheritance
It can be implemented using Interfaces.
5. What are the advantages of Inheritance?
● Reusability
● Reducing the code size of program.
● Sub class inherits all the properties from base class.

6. State the use of keyword super.


The constructors of the superclass are never inherited by the subclass. super() can be used to
invoke immediate parent class constructor.
Use of super keyword:
● Access superclass variables
● Access superclass method
● Access superclass constructor
Syntax:

DEPARTMENT OF CSE Page 109


Object Oriented Programming 2019

super();
super(parameterlist);
7. Distinguish between interface and class.
Parameters Class Interface
Basic A class can be instantatied An interface can never be instantiated
Keyword class interface
The members of a class can be private,
The members of an interface are
Access specifier
public or protected. always public.
Methods The methods of a class are defined The methods are not defined
An interface can extend multiple
A class can implement any number of
inheritance interfaces but cannot implement any
interfaces
interface.
Inheritance
extends implements
keyword
An interface can never have a
A class can have constructors to
Constructor constructor as there is hardly any
initialize the variables.
variable to initialize.
class class_Name interface interfaceName
{ {
Declaration //fields //fields
Syntax //Methods //Methods
} }
8. Define abstract class and abstract methods.
Abstract class:
A class that is declared as abstract is known as abstract class. Abstract class can have abstract
and non-abstract methods. It cannot be instantiated.
Keyword :
abstract
Syntax:
abstract class classname
{
………
}

Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method. Abstract method can never be final and static.
A normal class (non-abstract class) cannot have abstract methods.
Syntax:
abstract returntype methodname ();
9. Write short notes on Object class.

DEPARTMENT OF CSE Page 110


Object Oriented Programming 2019

The Object class is the parent class of all the classes in java by default (directly or indirectly).
The java.lang.Object class is the root of the class hierarchy. Some of the Object class are Boolean,
Math, Number, String etc.

Object

Boolean Character Number Math String StringBuffer

Byte Short Integer Long Float Double

Object class Methods Description


boolean equals(Object) returns true if two references point to the same object.
String toString() Converts object to String
10. What are the uses of final class and method?
The final keyword in java is used to restrict the user. The java final keyword can be applied to:
❖ variable
❖ method
❖ class
Java final variable - To prevent constant variables
Java final method - To prevent method overriding
Java final class - To prevent inheritance
Syntax for final method
final datatype methodname( )
{
………
}
Syntax for final class
final class classname
{
//code
}
11. What is meant by interface?
An interface is a reference type in Java. It supports multiple inheritance.
● It is similar to class.
● Interface may also contain abstract methods, default methods, static methods
● An interface can contain any number of methods.
● It gives outline for class
i) Defining an Interface
An interface is defined by using keyword “interface”

DEPARTMENT OF CSE Page 111


Object Oriented Programming 2019

Keyword: interface
Syntax:
interface interfacename
{
datatype instance-variable1;
datatype instance-variable2;
...
datatype instance-variableN;
datatype methodname1(parameter-list)
{
// body of method
}
...
datatype methodnameN(parameter-list)
{
// body of method
}
}
12. How will you find out the length of a string in java? Give an example?
length() : returns string length
Example:
String str1 = "object oriented";
System.out.println(s1.length());
Output: 14
13. What is inner class? Give types

Inner classes are the non-static nested classes. It can be used as the security mechanism in Java. It
is a class that is defined inside the other class.

OUTER
Syntax CLASS
of Inner class
class Outer_class
{ INNER
class Inner_classCLASS
{
…….
}
}

14. Define string. Give example


Strings are defined as an array of characters. It must be specified within double quotes. The
difference between a character array and a string is the string is terminated with a special character
‘\0’.
The string objects can be created using two ways.
3. By String literal

DEPARTMENT OF CSE Page 112


Object Oriented Programming 2019

4. By new Keyword
i) String Literal
Java String literal is created by using double quotes.
Syntax:
String stringname = “sequenceofcharacters”;
Example:
String str = "java”;
ii) By new keyword
Syntax:
String stringname = new String(“sequenceofcharacters”);
Example:
String str = new String("java”);

15. What is meant by array list


ArrayList is a part of collection framework. It is present in java.util package. It provides us
dynamic arrays in Java.
Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the
collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

16. Distinguish between deep cloning and shallow cloning.

17. Difference between abstract class and interface


Parameters Abstract Class Interface
Keyword abstract interface
The members of a abstract class can be The members of an interface are
Access specifier
public or protected. always public.
Inheritance
extends implements
keyword

DEPARTMENT OF CSE Page 113


Object Oriented Programming 2019

An abstract class can have both abstract An interface can have only abstract
methods
and concrete methods methods
An abstract class can extend only one An interface can extend any number
extends
class or one abstract class at a time of interfaces at a time
abstract class className interface interfaceName
{ {
Declaration //fields //fields
Syntax //Methods //Methods
} }

18. Give types and advantages of inner class.


Advantage of java inner classes
● Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class
● Nested classes are used to develop more readable and maintainable code
● Code Optimization: It requires less code to write.
Types of inner class:
1. Non-static nested class (inner class)
a. Member inner class
b. Anonymous inner class
c. Local inner class
2. Static nested class

19. List some of the String methods

Method Description
char charAt(int index) returns char value for the particular index
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
String substring(int beginIndex, returns substring from given begin index to end index
int endIndex)
boolean equals(Object another) checks the equality of string with object
boolean isEmpty() checks if string is empty

String concat(String str) concatenates specified string

String replace(char old, char new) replaces all occurrences of specified char value

20. What is finalize () method?


The finalize() method is called just before an object is garbage collected. It is used to dispose
system resources, perform clean-up activities and minimize memory leaks.

DEPARTMENT OF CSE Page 114


Object Oriented Programming 2019

Syntax:
protected void finalize() // finalize() is called just once on an object
{
………………
}

PART B (Possible Questions)


1. Define inheritance. With daiagrammatic illustration and java programs, illustrate the
inheritance with the examples. (13)
2. Write java program to crate the stdent examination database system that prints the mark sheet
of students. Input student name, marks in 5 subjects. This mark should be between 0 and 100.
● If average of marks is >= 80 then prints Grade A
● If average of marks is < 80 and >=60 then prints Grade B
● If average of marks is < 60 and >=40 then prints Grade C
● else prints Grade D. (13)
3. What is interface? Write a java program to illustrate the use of interface. (13)
4. i) Write briefly on Abstract classes with an example (7)
ii) List the type of constructors and the concept of destructor with example (6)
5. i) What is meant by object cloning? Explain it with an example (6)
ii) Illustrate briefly about final methods and classes (7)
6. i) Demonstrate any six methods available in the String class(7)
ii) Explain about inner classes and its types with example (6)
7. Illustrate String handling class in Java with example. (13)

DEPARTMENT OF CSE Page 115


Object Oriented Programming 2019

8. i). Explain with an example what is meant by object cloning? (7)


ii) Summarize in detail about inner class with its usefulness. (6)

PART C (Possible Questions)


1. Develop a program to perform string operations using ArrayList. Write functions for the
following
i) Append - add at end
ii) Insert – add at particular index
iii) Search
iv) List all string starts with given letter “a” .
2. Develop a Java Program to create an abstract class named Shape that contains two integers
and an empty method named print Area(). Provide three classes named Rectangle, Triangle and
Circle such that each one of the classes extends the class Shape. Each one of the classes contains
only the method print Area () that prints the area of the given shape.
3. Consider a class student .Inherit this class in UG Student and PG Student. Also inherit
students into local and non-local students. Define five Local UG Students with a constructor
assuming all classes have a constructor.
4. Create a abstract Reservation class which has Reserve abstract method. Implement the sub-
classes like ReserveTrain and ReserveBus classes and implement the same

DEPARTMENT OF CSE Page 116


Object Oriented Programming 2019

4. Develop an Employee class which implements the Comparable and Cloneable interfaces.
Implement the sorting of persons (based on name in alphabetical). Also implement the
shallow copy (for name and age) and deep copy (for DateOfJoining
5. Declare an abstract class to represent a bank account with data members name, account
number, address and abstract methods withdraw and deposit. Method display() is needed to show
balance. Derive a subclass Savings Account and add the following details: return on investment
and the method calcAmt() to show the amount in the account after 1 year. Create instance of
Savings Account and show the use of withdraw and deposit abstract methods

ADDITIONAL PROGRAMS
1. Check Palindrome
// Palindrome.java
class Palindrome
{
public static void main(String[] args)
{
int num = 121, rev = 0, remainder;
while( num != 0 )
{
remainder = num % 10;
rev = rev* 10 + remainder;
num /= 10;
}
if (originalInteger == reversedInteger)
System.out.println(originalInteger + " is a palindrome.");

DEPARTMENT OF CSE Page 117


Object Oriented Programming 2019

else
System.out.println(originalInteger + " is not a palindrome.");
}
}
Output:
javac Palindrome.java
java Palindrome
121 is a palindrome number.
2. Program to display student grade details
//studentgrade.java
import java.util.Scanner;
class studentgrade
{
public static void main(String[] args)
{
int english, chemistry, computers, physics, maths;
float total, Percentage;
Scanner sc = new Scanner(System.in);
System.out.print(" Please Enter the Five Subjects Marks : ");
english = sc.nextInt();
chemistry = sc.nextInt();
computers = sc.nextInt();
physics = sc.nextInt();
maths = sc.nextInt();
total = english + chemistry + computers + physics + maths;
Percentage = (total / 500) * 100;
System.out.println(" Total Marks = " + total);
System.out.println(" Marks Percentage = " + Percentage);
if(Percentage >= 80)
{
System.out.println("Grade A");
}
else if(Percentage < 80 && Percentage >=60)
{
System.out.println("Grade B");
}
else if(Percentage <60 && Percentage >=40)
{
System.out.println("\n Grade C");
}
else
{
System.out.println("Grade D");
}
}

DEPARTMENT OF CSE Page 118


Object Oriented Programming 2019

}
Output:
javac studentgrade.java
java studentgrade
Please Enter the Five Subjects Marks : 80 80 70 85 94
Total Marks=409.0
Marks Percentage =81.6
Grade B
3. String operations using ArrayList
import java.util.*;
public class sample
{
public static void main(String[] args)
{
ArrayList<String> lst = new ArrayList<String>();
lst.add("C"); // add() takes Object. String upcast to Object implicitly
lst.add("Java");
lst.add("Perl");
System.out.println(lst);
int choice;
String s;
System.out.pritln(“1.append 2.insert 3.search 4. List”);
Scanner sc=new Scanner(System.in);
System.out.println("enter choice");
choice=sc.nextInt();
switch(choice)
{
case 1:
System.out.println("enter String");
s=sc.next();
lst.add(s);
System.out.println(lst);
break;
case 2:
System.out.println("enter index and string to insert");
int index=sc.nextInt();
s=sc.next();
lst.add(index,s);
System.out.println(lst);
break;
case 3:
System.out.println("enter String to search");
s=sc.next();
System.out.println(lst.contains(s));

DEPARTMENT OF CSE Page 119


Object Oriented Programming 2019

break;
case 4:
System.out.println(lst);
break;
default:
System.out.println("enter correct choice");
}
}
}

CHAPTER III
DEPARTMENT OF CSE Page 120
Object Oriented Programming 2019

EXCEPTION HANDLING AND I/O

Exceptions – exception hierarchy – throwing and catching exceptions – built-in

exceptions,creating own exceptions, Stack Trace Elements. Input / Output Basics –

Streams–Byte streams and Character streams – Reading and Writing Console –

Reading and Writing Files.

DEPARTMENT OF CSE Page 121


Object Oriented Programming 2019

EXCEPTION HANDLING AND I/O


3.1 EXCEPTIONS– EXCEPTION HIERARCHY
An exception is defined as unusual condition or unexpected event. It occurs during the execution
of a program (at run time), which disrupts the normal flow of the program.
This leads to abnormal termination of the program.
An exception may occur due to the following reasons. They are.
● Invalid data as input.
● File cannot be found/opened.
● Division by zero
● Network connection may be disturbed in the middle of communications
Exceptions are caused by user error, programmer error, and physical resources.
Errors:

DEPARTMENT OF CSE Page 122


Object Oriented Programming 2019

Errors are not exception.Errors are problems that may arise beyond the control of the user.
Exception Hierarchy
Exceptions can be classified into three categories
1. Checked Exception / Compile time Exeptions
2. Unchecked exception / Runtime Exeptions
3. Own Exception
3.1. 1.CHECKED EXCEPTIONS
A checked exception is an exception that occurs at the compile time, also called as compile time
(static time) exceptions. These exceptions cannot be ignored at the time of compilation.
Checked Exception is divided into following types,
i) ClassNotFound Exception
ii) IllegalAccess Exception
iii) NoSuchField Exception
iv) NoSuchMethod Exception
v) EOF Exception
vi) FileNotFound Exception
vii) UnknownHost Exception
i) ClassNotFound Exception
If the class is not found in the program,the exception is thrown
ii) IllegalAccess Exception
If the denied class is accessed, the exception is thrown.
iii) NoSuchField Exception
If the field does not exist in the program,the exception is thrown.
iv) NoSuchMethod Exception
If the method does not exist in the program,the exception is thrown.
v) EOF Exception
If the EndOfFile is not reached,the exception is thrown.
i) FileNotFound Exception
If the file is not found,the exception is thrown.
ii) UnknownHost Exception
If the host is unknown,the exception is thrown.

java.lang
3.1.2.UNCHECKED EXCEPTIONS / RUNTIME EXEPTIONS
An unchecked exception is an exception that occurs at run time, also called as Runtime
Exceptions. Runtime exceptions are ignored at the time of compilation.
object
Unchecked Exception is divided into following types,
i) Arithmetic expectation
ii) ArrayIndexOutOfBounds Exception
iii) NegativeArraySize Exception throwable
iv) IllegalState Exception
v) NullPointer Exception
i) Arithmetic expectation
error exception
If divide by zero occurred,then the exception is thrown.
ii) ArrayIndexOutOfBounds Exception
compile runtime checked unchecked own
DEPARTMENT
error OF CSE error Page 123
exception exception exception

IO classNotFound IllegalAccess
Object Oriented Programming 2019

When the array index is out of boundary,then the exception is thrown.


iii) NegativeArraySize Exception
When the array is created with a negative size, the exception is thrown.
iv) IllegalState Exception
When the program is in the incorrect state, then the exception is thrown.
v) NullPointer Exception
If any problem is in the null pointer,then the exception is thrown.
3.1.3 OWN EXCEPTION
The user must define the own exception. It is divided into two types
i) Throwable getCause()
ii) String getMessage()
i) Throwable getCause()
It returns the description of the exception that lies on the current exception.
ii) String getMessage()
It returns the description of the exception.
Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a =10,b=0,c;
try
{
c = a/b;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("completed.");
}
}

Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Division by zero
Completed

3.2 THROWING & CATCHING EXCEPTION(EXCEPTION HANDLING)

DEPARTMENT OF CSE Page 124


Object Oriented Programming 2019

⮚ Exception handling means it detects and report the exception in the program and handles
the exception.
⮚ It is the error handling mechanism in java.
There are four task in the exception handling process.
1. Try the exception
The exception is created here and finds the exception.
2. Throw the exception
Informs that the exception has been occurred.
3. Catch the exception
Receive the exception information.
4. Handle the exception
Take the corrective action.

try

i) Try Block
The try block contains
throw exception causing statement. It is implemented by the keyword ‘try’. It
must be followed by either catch or finally block. If an exception occurs it is thrown
Syntax
try catch
{
statement1;
statement2; // exception causing statement
statement3; handle
}
ii) Throw Block
The ‘throw’ keyword is used to throw an exception.When exception is raised in try block,then it
is thrown to catch block.
Syntax
throw(Exception);

iii) Catch block


catch block contains exception handling statement.when the exception is thrown, catchblock
catches the exception and handles it. It is implemented by the keyword ‘catch’.catchblock must be
created immediately after the try block.
Syntax
try
{
statement1;
statement2; // exception causing statement
statement3;
}

DEPARTMENT OF CSE Page 125


Object Oriented Programming 2019

catch(Exception e)
{
statement1;
statement2; // exception handling statement
}

Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a =10,b=0,c;
try
{
c = a/b;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("completed.");
}
}

Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Division by zero
Completed
iv) Multiple catchblock

DEPARTMENT OF CSE Page 126


Object Oriented Programming 2019

In some situation,different exception occurs in the single try block. To handle such situation, we
use the multiple catch block. When the exception is thrown ,the exception handler search for the
appropriate block. If the match is found,the exception is displayed.when no match is found,the
program is terminated.
Syntax
try
{
……….
……….
}
catch(Exception e)
{
………..
………..
}
catch(Exception e)
{
………..
………..
}

Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a[2]={10,20};
int c;
try
{
c = a[2]/10;
}
catch (ArithmeticException e)
{
System.out.println("Divide by zero.");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
System.out.println("completed.");
}
}
Output

DEPARTMENT OF CSE Page 127


Object Oriented Programming 2019

C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Array index error
Completed
v) Throwing exception
Throwing exception is done by two methods.
1. Using throw
2. Using throws
Using throw
● It is used to throw exception explicitly.
● It is declared by the keyword ‘throw’
● ‘throw’ is used within method
Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a =10,b=0,c;
if(b==0)
{
throw new ArithmeticException(“divide by zero”);
}
System.out.println("completed.");
}
}

Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Exception in thread:java.lang.ArithmeticException:divide by zero
at ExceptionThrow.fun(ExceptionThrow.java:7)
at ExceptionThrow.fun(ExceptionThrow.java:17)
Using throws
When method wants to throw exception,’throws’ keyword is used.
Syntax
methodname(parameterlist)throws Exception
{
……………
}
Program:
//Exceptiondemo.java
class Exceptiondemo
{
void fun(int a,int b) throws ArithmeticException

DEPARTMENT OF CSE Page 128


Object Oriented Programming 2019

{
int c;
try
{
c=a/b;
}
catch(Arithmetic Exception e)
{
System.out.println("uncaught Exception." +e);
}
}
public static void main(String args[])
{
int a=5;
int b=10;
fun(a,b);
}
}
Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Uncaught Exception : java.lang
.ArithmeticException:divide by zero
throw throws
Java throw keyword is used explicitly to Java throws keyword is used to declare an
throw an exception. exception.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
we cannot throw multiple exceptions. We can declare multiple exceptions.

void m(){ void m() throws IOException{


throw new IOException(“Error”); //code
} }

iv) finallyblock
A finally block of code always executes, irrespective of occurrence of an Exception. The finally
block follows a try block or a catch block. finally block statement is also called as cleanup code.
The finally block is to free the resources.
Syntax

DEPARTMENT OF CSE Page 129


Object Oriented Programming 2019

try

…………

catch (ExceptionType1 e1)

// Catch block

catch (ExceptionType2 e2)

// Catch block

finally

// The finally block always executes.

Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a =10,b=0,c;
try
{
c = a/b;
}
catch (ArithmeticException e)
{

DEPARTMENT OF CSE Page 130


Object Oriented Programming 2019

System.out.println("Division by zero.");
}
finally
{
System.out.println("completed.");
}
}
}

Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Division by zero
Completed
Nested try
Try blocks embedded within another try block is nested try.
Syntax

try

………..

try

……….

3.3 BUILT-IN EXCEPTIONS


Built-in exceptions are the pre-defined exceptions which is already defined in Java libraries. The
built-in exceptions in Java are listed as
Exceptions Description
IOException when an illegal input-output operation is
performed,exception is thrown
ClassNotFoundException This Exception is raised when we try to access a class
whose definition is not found.
IllegalAccessException If the denied class is accessed,the exception is thrown.
NoSuchMethodException It is thrown when accessing a method which is not
found.

DEPARTMENT OF CSE Page 131


Object Oriented Programming 2019

NoSuchFieldException It is thrown when a class does not contain the field (or
variable) specified.
EOFException If the EndOfFile is reached,the exception is thrown..
FileNotFoundException If the file is not found,the exception is thrown.
UnknownHostException It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted./if the host is
unknown,the exception is thrown.
Arithmetic Exception It is thrown when an exceptional condition has
occurred in an arithmetic operation.eg.divide by zero.

ArrayIndexOutOfBoundException When the array index is out of boundary,i.e the index


is either negative or greater than or equal to the size of
the array, then the exception is thrown.
NegativeArraySizeException When the array is created ,with a negative size,the
exception is thrown.
IllegalStateException When the program is in the incorrect state,then the
exception is thrown.
NullPointerException If any problem is in the null pointer,then the exception
is thrown.

Program:
Refer page no:
3.4 CREATING OWN EXCEPTIONS (USER DEFINED EXCEPTIONS)
We can create our own exceptions in java and throws that exception using ‘throw’ keyword.
Syntax
class ownException extends Exception
{
………..
}
throw new OwnException();
Example:
class MyException extends Exception
{
…………….
}
throw new MyException();
Program:
import java.lang.Exception;
class MyException extends Exception
{
int a;
MyException(int b)
{

DEPARTMENT OF CSE Page 132


Object Oriented Programming 2019

a=b;
}
public String toString()
{
return(“Exception number=” +a);
}
}
class Exceptiondemo
{
public static void main(String args[])
{
try
{
throw new MyException(2);
}
catch(MyException e)
{
System.out.println(e);
}
}
}

Output
C:\javac ownexceptiondemo.java
C:\java ownexceptiondemo
Exception number=2
Explanation
In the above program, MyException is the user defined exception.In the try block,throw the
MyException with the value 2.so,as to get the value of 2.when the exception is thrown, the catch
block gets executed.so we get the output message ‘Exception number=2’
3.5 STACK TRACE ELEMENTS
Stack Trace Element is created to represent the specific execution point.
Syntax
StackTraceElement(String classname, String methodname, String filename,
int linenumber);
where,
StackTraceElement -- represents the StackTraceElement
Classname -- represents the name of the class for the execution point.
methodname – represents the name of the method for the execution point.
filename – represents the name of the file for the execution point.
linenumber – represents the linenumber for the execution point. If linenumber is negative ,it
denotes information is unavailable.
Methods
1. String getclassName()
It returns the classname which is represented by StackTraceElement.

DEPARTMENT OF CSE Page 133


Object Oriented Programming 2019

2. String getfileName()
It returns the filename which is represented by StackTraceElement.
3. int getLineNumber()
It returns the linenumber which is represented by StackTraceElement.
4. int hashcode()
It returns the hashcode of the StackTraceElement.
5. String toString()
It returns the string which is represented by StackTraceElement.
6. boolean equals(object obj)
It returns the true if the object and the StackTraceElement represent the same execution point.
Program:
//StackTracedemo.java
public class StackTracedemo
{
public static void main(String[] args)
{
try
{
throw new RuntimeException("go"); //raising an runtime exception
}
catch(RuntimeException e)
{
System.out.println("Printing stack trace:");
final StackTraceElement[] s = e.getStackTrace();
System.out.println(s.getFileName() + ":" + s.getLineNumber());
}
}
}
Output:
C:\javac StackTracedemo.java
C:\java StackTracedemo
Printing stack trace:
StackTracedemo.java:5
3.6 INPUT / OUTPUT BASICS (STREAMS)
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of stream to make I/O operation fast. All the classes required for input and output
operations are declared in java.io package.
Stream is a channel on which data flow from sender to receiver.
⮚ A stream can also be defined as a sequence of data.
⮚ The InputStream is used to read data from a source
⮚ OutputStream is used for writing data to a destination.

DEPARTMENT OF CSE Page 134


Object Oriented Programming 2019

Types Of Streams
Java supports two types of streams. They are,
1. Byte Stream
2. Character Stream
Streams
1. Byte Stream : It is used for handling input and output of 8 bit bytes. The frequently used
classes are FileInputStream and FileOutputStream.
2. Character Stream : It is used for handling input and output of characters. Character stream
uses 16 bit Unicode. The frequently used classes are FileReader and FileWriter.
Byte Stream
3.6.1 BYTE STREAMS Character Stream
⮚ Byte stream is used for reading and writing bytes.
⮚ Byte stream is the abstract class.
⮚ There are two kinds of byte stream classes:
a. InputStream classes
b. Input Stream
OutputStream classes.Output Stream Reader Stream Writer Stream
i) InputStream
⮚ InputStream class is an abstract class.
⮚ The InputStrearn class is the superclass for all byte-oriented input stream classes.
⮚ All the methods of this class throw an IOException.
⮚ The InputStrearn class cannot be instantiated hence, its subclasses are used.

Input Streams
The InputStream classes are
Class Description
BufferedInputStream contains methods to read bytes from the buffer (memory area)
Buffered Input Stream Sequence Input Stream
ByteArrayInputStream contains methods to read bytes from a byte array
DataInputStream contains methods to read primitive data types
FileInputStream contains methods to read bytes from a file
Data Input Stream Object Input Stream
ObjectInputStream contains methods to read bytes from the object.
PipedInputStream contains methods to read from the pipe.

Piped Input Stream


Byte Array Input Stream
DEPARTMENT OF CSE Page 135
File Input Stream
Object Oriented Programming 2019

SequenceInputStream contains methods to concatenate multiple input streams and then read
from the combined stream.
Methods in the InputStream
1.read()
It is used to read the byte.
2.read(byte b[])
It is used to read the byte from the array b.
3.read(byte b[],int n,int m)
It read the m bytes starting from nth byte from b.
4.close()
It is used to close the InputStream.
ii) OutputStream
⮚ OutputStream class is an abstract class.
⮚ The OutputStrearn class is the superclass for all byte-oriented output stream classes.
⮚ All the methods of this class throw an IOException.
Output Streams
The Output Stream classes are
Class Description
BufferedOutputStream Contains methods to write bytes to the buffer.
ByteArrayOutputStream
Buffered Output Stream Contains methods to write bytes into a byte array Output Stream
Sequence
DataOutputStream Contains methods to write primitive data types
FileOutputStream Contains methods to write bytes to a file
Data Output Stream Object Output Stream
ObjectOutputStream Contains methods to write bytes to the object.
PipedOutputStream Contains methods to write to a pipe.
SequenceOutputStream Contains methods to write bytes to the multiple output stream.
Piped Output Stream
Byte Array Output Stream
Methods in the OutputStream
1.write() File Output Stream
It is used to write the byte.
2.write(byte b[])
It is used to write the byte from the array b.
3.write(byte b[],int n,int m)
It write the m bytes starting from nth byte from b.
4.close()
It is used to close the InputStream.
3.6.2 CHARACTER STREAMS
⮚ Character Stream is used for inputing and outputting character.
⮚ There are two kinds of character stream classes:
a. ReaderStream
b. WriterStream
a.Reader Stream
⮚ Reader Stream classes are used to read 16-bit unicode characters from the input stream.
DEPARTMENT OF CSE Page 136
Object Oriented Programming 2019

⮚ The Reader class is the superclass for all character-oriented input stream classes.
⮚ All the methods of this class throw an IOException.

Reader Stream
The Reader Stream classes are
Reader class Description
BufferedReader contains methods to read characters from the buffer
CharArray Reader contains methods to read characters from the CharArray
Buffered Reader
InputStreamReader contains methods to read the character fromPipe
theReader
InputStream
File Reader contains methods to read the character from a file
String Reader contains methods to read the character from the string
Filter Reader
Char Array Reader contains methods to read the character fromReader
Pushback the filter
Pipe Reader contains methods to read the character from the pipe
Pushback Reader contains methods to pushing back character
Methods in the ReaderStream
1.read() String Reader
Input Stream Reader
It is used to read the character.
2.read(char b[])
It is used to read the array of characters from b. Reader
Filter
3.read(char b[],int n,int m)
File Reader
It read the m characters from array b starting from nth character.
4.close()
It is used to close the ReaderStream.
b.Writer Stream
⮚ Writer classes are used to write 16-bit Unicode characters onto an outputstream.
⮚ The Writer class is the superclass for all character-oriented output stream classes .
⮚ All the methods of this class throw an IOException
Writer Stream
The Writer Stream classes are
Writer class Description
BufferedWriter contains methods to write characters onto the buffer
Buffered Writer
CharArray Writer contains methods to write characters ontoPipe
the Writer
CharArray
OutputStreamWriter contains methods to write characters onto the OutputStream
File Writer contains methods to write the character onto a file
Char Array Writer Print Writer
String Writer contains methods to write the character onto the string
Filter Writer contains methods to write the character onto the filter
Pipe Writer String Writer
contains methods to write the character onto the pipe
Output Stream Writer
Print Writer contains print( ) and println( ) methods to write the characters
Methods in the WriterStream Filter Writer
File Writer
DEPARTMENT OF CSE Page 137
Object Oriented Programming 2019

1.write()
It is used to write the character.
2. write(char b[])
It writes the array of characters to b.
3. write(char b[],int n,int m)
It write the m characters starting from nth character into b.
4.close()
It is used to close the WriterStream.
3.7 READING AND WRITING CONSOLE
⮚ In java, system is a class defined in java.lang and in,out,err are the variables of the class
system.
⮚ system.out is an object used for standard OutputStream and system.in and system.err are
the objects for the Standard InputStream and err.
3.7.1 Reading Console : Input
Reads the input from the keyboard using two methods
1. Using BufferedReader
2. Using Scanner
1) Using BufferedReader
System.in is used to read some characters from the console.
Syntax
BufferedReader objectname=new BufferedReader(new InputStreamReader(system.in));
Steps:
i.Import the java.io package
ii.Create the instance for BufferedReader
Syntax
BufferedReader objectname=new BufferedReader(new InputStreamReader(system.in));
iii.Use the read method to read the character string
Reading the character
Program:
//readchardemo.java
import java.io.*;
class readchardemo
{
public static void main( String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c;
System.out.println("Enter character: ");
c = (char)br.read(); //Reading character
System.out.println(“character=”+c);
}
}
Output
C:\javac readchardemo.java
C:\java readchardemo

DEPARTMENT OF CSE Page 138


Object Oriented Programming 2019

Enter character:k
character=k
Reading the string
Program:
//readstringdemo.java
import java.io.*;
class readstringdemo
{
public static void main( String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
System.out.println("Enter String: ");
s = br.readLine();
System.out.println(“String=”+s);
}
}
Output
C:\javac readstringdemo.java
C:\java readstringdemo
Enter String:object oriented
String= object oriented

Reading the Integer


Program:
readintdemo.java
import java.io.*;
class readintdemo
{
public static void main( String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i;
String s;
System.out.println("Enter integer: ");
s = br.readLine();
i=Integer.parseint(s);
System.out.println(“Integer=”+i);
}
}
Output
C:\javac readintdemo.java
C:\java readintdemo
Enter integer:10
Integer= 10

DEPARTMENT OF CSE Page 139


Object Oriented Programming 2019

2).Using Scanner
The scanner is a class defined in java.util package
Steps:
i.Import the java.util package
ii.Create the instance for the Scanner class
Syntax
Scanner obj=new Scanner(system.in);
iii.Use the next() method to read the input.
Reading the character
Program:
//readchardemo.java
import java.io.*;
class readchardemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
char c;
System.out.println("Enter character: ");
c = (char)sc.next(); //Reading character
System.out.println(“character=”+c);
}
}
Output
C:\javac readchardemo.java
C:\java readchardemo
Enter character:k
character=k
Reading the string
Program:
//readstringdemo.java
import java.io.*;
class readstringdemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
String s;
System.out.println("Enter String: ");
s = sc.next();
System.out.println(“String=”+s);
}
}
Output

DEPARTMENT OF CSE Page 140


Object Oriented Programming 2019

C:\javac readstringdemo.java
C:\java readstringdemo
Enter String:object oriented
String= object oriented
Reading the Integer
Program:
//readintdemo.java
import java.io.*;
class readintdemo
{
public static void main( String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
int i;
System.out.println("Enter integer: ");
i=sc.nextInt();
System.out.println(“Integer=”+i);
}
}
Output
C:\javac readintdemo.java
C:\java readintdemo
Enter integer:10
Integer= 10
3.7.2 Writing Console : Output
There are three methods to write console output.
1. System.out.write()
2. System.out.print() and System.out.println()
3. Using PrintWriter class
1.System.out.write()
writing the integer
Program:
writeintdemo.java
class writeintdemo
{
public static void main(String args[])throws IOException
{
int a=5;
System.out.write("a="+a);
}
}
Output
C:\javac writeintdemo.java
C:\java writeintdemo
a=5

DEPARTMENT OF CSE Page 141


Object Oriented Programming 2019

2.System.out.println()
Program:
//printlndemo.java
class printlndemo
{
public static void main(String args[])throws IOException
{
int a=5;
System.out.println("a="+a);
}
}
Output
C:\javac printlndemo.java
C:\java printlndemo
a=5
3.Using PrintWriter class
Program:
//writeintdemo.java
class writeintdemo
{
public static void main(String args[])throws IOException
{
int a=5;
PrintWriter pw=new PrintWriter(System.out,true);
pw.write(a);
}
}
Output
C:\javac writeintdemo.java
C:\java writeintdemo
5
3.8 READING AND WRITING FILES
⮚ Java provides the method to read and write bytes from and to a file.
⮚ Java contains two classes for reading/writing files.They are
1. FileInputStream
2. FileOutputStream

3.8.1.FILE
Input INPUTSTREAM
File File Input
FileInput stream is used for reading data from the files.
Two common constructors Stream
i) FileInputStream(filename)
ii) FileInputStream(fileobj) Program
i) fileInputStream(filename)
Syntax
InputStream f = new FileInputStream("filename ");

OutputOF
DEPARTMENT File
CSE Page 142
File Output
Stream
Object Oriented Programming 2019

ii) fileInputStream(fileobj)
Syntax
InputStream f = new FileInputStream(f);
Methods in the FileInputStream
1.int read()
It reads the byte from the file.
It returns the total number of bytes for reading.
2.int read(byte b[])
It reads the byte from the array b.
3.int read(byte b[],int n,int m)
It reads m bytes from array b starting from nth byte.
4.int available()
It returns the number of bytes that are available for reading.
5.void reset()
It reset the pointer to the beginning of the file.
6.int mark(int n)
It place the pointer to the nth byte.
7.void close()
It closes the FileInputStream.
3.8.2.FILEOUTPUTSTREAM
FileOutputStream is used to create a file and write data into it.
Two common constructors
i) FileOutputStream(filename)
ii) FileOutputStream(fileobj)
i) FileOutputStream(filename)
Syntax
OutputStream f = new FileOutputStream("filename");
ii) FileOutputStream(fileobj)
Syntax
OutputStream f = new FileOutputStream(f);
Methods in the FileOutputStream
1.int write()
● It writes the byte to the file.
● It returns the total number of bytes for writing.
2.int write(byte b[])
It writes the byte to the array b.
3.int write(byte b[],int n,int m)
It writes m bytes starting from nth byte to b.
4.flush()
It is used for clearing the file.
5.close()
It closes the FileOutputStream
Program for copying the file into another file
Program: copyfiledemo.java
import java.io.*;

DEPARTMENT OF CSE Page 143


Object Oriented Programming 2019

class copyfiledemo
{
public static void main(String args[])throws IOException
{
File f1=new file(“input.txt”);
File f2=new file(“output.txt”);
byte b;
try
{
FileInputStream fis = new FileInputStream("f1");
FileOutputStream fos = new FileOutputStream("f2");
do
{
b=(byte)fis.read();
fos.write(b);
}while(b!=-1);
}
catch (filenotfoundException e)
{
System.out.println("file is not found");
}
finally
{
System.out.println("end of program");
fis.close();
fos.close();
}
}
}
Output
C:\type input.txt
object oriented
C:\type output.txt
C:\javac copyfiledemo.java
C:\java copyfiledemo
end of program
C:\type output.txt
object oriented
java
PART A (2 Marks with Answers)
1.Define runtime exception. (nov/dec2018)
An unchecked exception is an exception that occurs at run time, also called as Runtime
Exceptions.Runtime exceptions are ignored at the time of compilation.
i) Arithmetic expectation
ii) ArrayIndexOutOfBounds Exception

DEPARTMENT OF CSE Page 144


Object Oriented Programming 2019

iii) NegativeArraySize Exception


iv) IllegalState Exception
v) NullPointer Exception
2.What is the use of assert keyword. (nov/dec2018)
Assert is a Java keyword used to define an assert statement. An assert statement is used
to declare an expected boolean condition in a program. If the program is running with assertions
enabled, then the condition is checked at runtime. If the condition is false, the Java runtime
system throws an AssertionError.
3. What is meant by exception and error.
An exception is defined as unusual condition or unexpected event. It occurs during the execution
of a program (at run time), which disrupts the normal flow of the program.
An exception may occur due to the following reasons. They are.
● Invalid data as input.
● File cannot be found/opened.
● Division by zero
● Network connection may be disturbed in the middle of communications
Errors:
Errors are not exception.Errors are problems that may arise beyond the control of the user.
4. What are the types of exceptions?
Exceptions can be classified into three categories
4. Checked Exception / Compile time Exeptions
5. Unchecked exception / Runtime Exeptions
6. Own Exception
5. What is meant by checked exceptions (OR) compile time exceptions
A checked exception is an exception that occurs at the compile time, also called as compile time
(static time) exceptions. These exceptions cannot be ignored at the time of compilation.
Checked Exception is divided into following types,
viii) ClassNotFound Exception
ix) IllegalAccess Exception
x) NoSuchField Exception
xi) NoSuchMethod Exception
xii) EOF Exception
xiii) FileNotFound Exception
xiv) UnknownHost Exception
6. What is meant by exception handling process
Exception handling means it detects and report the exception in the program and handles the
exception. It is the error handling mechanism in java.
There are four tasks in the exception handling process.
5. Try the exception
The exception is created here and finds the exception.
6. Throw the exception
Informs that the exception has been occurred.
7. Catch the exception
Receive the exception information.
8. Handle the exception

DEPARTMENT OF CSE Page 145


Object Oriented Programming 2019

Take the corrective action.


7. Write the syntax of try and catch block.
try
{
statement1;
statement2; // exception causing statement
statement3;
}
catch(Exception e)
{
statement1;
statement2; // exception handling statement
}
8. Name any four java built in exceptions.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Arithmetic Exception Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast
9. Compare throw and throws in java (OR) How the exception is thrown in java.
Throwing exception is done by two methods.
3. Using throw
4. Using throws
throw throws
Java throw keyword is used explicitly to Java throws keyword is used to declare an
throw an exception. exception.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
we cannot throw multiple exceptions. We can declare multiple exceptions.

void m(){ void m() throws IOException{


throw new IOException(“Error”); //code
} }

10. State the purpose of finally block


A finally block of code always executes, irrespective of occurrence of an Exception. The finally
block follows a try block or a catch block. finally block statement is also called as cleanup code.
The finally block is to free the resources.
Syntax
try

DEPARTMENT OF CSE Page 146


Object Oriented Programming 2019

{
…………
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
finally
{
// The finally block always executes.
}
11. What is the use of Stack Trace Element?
It is created to represent the specific execution point.
Syntax
StackTraceElement(String classname, String methodname, String filename,
int linenumber);
where,
StackTraceElement -- represents the StackTraceElement
Classname -- represents the name of the class for the execution point.
methodname – represents the name of the method for the execution point.
filename – represents the name of the file for the execution point.
linenumber – represents the linenumber for the execution point. If linenumber is negative ,it
denotes information is unavailable
12. What are the methods in StackTrace Element
7. String getclassName()
It returns the classname which is represented by StackTraceElement.
8. String getfileName()
It returns the filename which is represented by StackTraceElement.
9. int getLineNumber()
It returns the linenumber which is represented by StackTraceElement.
10. int hashcode()
It returns the hashcode of the StackTraceElement.
11. String toString()
It returns the string which is represented by StackTraceElement.
12. boolean equals(object obj)
It returns the true if the object and the StackTraceElement represent the same execution point.
13. Define Stream. What are the types.
Stream is a channel on which data flow from sender to receiver.
⮚ A stream can also be defined as a sequence of data.
⮚ The InputStream is used to read data from a source
⮚ OutputStream is used for writing data to a destination.

DEPARTMENT OF CSE Page 147


Object Oriented Programming 2019

Java supports two types of streams. They are,


3. Byte Stream
4. Character Stream
14. What is Byte Stream? List types
⮚ Byte stream is used for reading and writing bytes.
⮚ Byte stream is the abstract class.
⮚ There are two kinds of byte stream classes:
c. InputStream classes
d. OutputStream classes.
InputStream OutputStream
BufferedInputStream BufferedOutputStream
ByteArrayInputStream ByteArrayOutputStream
DataInputStream DataOutputStream
FileInputStream FileOutputStream
ObjectInputStream ObjectOutputStream
PipedInputStream PipedOutputStream
SequenceInputStream SequenceOutputStream

15. Define Character Stream. List types.


⮚ Character Stream is used for inputing and outputting character.
⮚ There are two kinds of character stream classes:
c. ReaderStream
d. WriterStream
Reader class OutputStream
BufferedReader BufferedOutputStream
CharArray Reader ByteArrayOutputStream
InputStreamReader DataOutputStream
File Reader FileOutputStream
String Reader ObjectOutputStream
Filter Reader PipedOutputStream
Pipe Reader SequenceOutputStream

16. How read and write operation from the console is performed in java?
● Reads the input from the keyboard using two methods
3. Using BufferedReader
4. Using Scanner
● There are three methods to write console output.

DEPARTMENT OF CSE Page 148


Object Oriented Programming 2019

4. System.out.write()
5. System.out.print() and System.out.println()
6. Using PrintWriter class
17. What are input and output streams?
An I/O Stream represents an input source or an output destination. A stream can represent many
different kinds of sources and destinations, including disk files, devices, other programs, and
memory arrays.
18. How the user create their own exceptions?
We can create our own exceptions in java and throws that exception using ‘throw’ keyword.
Syntax
class ownException extends Exception
{
………..
}
throw new OwnException();
Example:
class MyException extends Exception
{
…………….
}
throw new MyException();

PART B (Possible Questions)


1. Explain the different types of exceptions and the exception hierarchy in java with appropriate
examples.(13) (Nov/Dec2018)
2.What are input and output streams?Explain them with illustrations.(13) (Nov/Dec2018)

DEPARTMENT OF CSE Page 149


Object Oriented Programming 2019

3.Explain briefly about user defined exceptions and the concept of throwing and catching
exception in java with examples.
4. Describe the stack trace elements with an example.
5.Summarize the concept of streams and stream classes and their classification
6.Differentiate byte stream and character stream with necessary examples.
7.Explain how to handle arithmetic exception by giving a suitable example.
8.Explain the importance of try - catch block with example
9.Evaluate a try block that is likely to generate three types of exception and then incorporate
necessary catch blocks and handle them appropriately.
10.Write programs to illustrate arithmetic exception, ArrayIndexOutOfBounds Exception and
NumberFormat Exception.

PART C (Possible Questions)


1. Develop a Java program to implement user defined exception handling.

DEPARTMENT OF CSE Page 150


Object Oriented Programming 2019

2. Develop the Java program to concatenate the two files and produce the output in the
third file.
3. How does InputStream.read() method work? Can you give me some sample code?
4. Deduce a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of
the file in bytes.
5. Why only read() methods in ByteArrayInputStream does not throw IOException?
6. Write a calculator program using exceptions and functions.
7. Write a program to receive the name of a file within a text field and then displays its
contents within a text area.

DEPARTMENT OF CSE Page 151


Object Oriented Programming 2019

ADDITIONAL PROGRAMS
1.write a program to accept 5 numbers from the user and display it.
Program:
numberdemo.java
import java.io.*;
class numberdemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
int i=1,n;
System.out.println("Enter number: ");
while(i<=5)
{
n=sc.nextInt();
System.out.println(“number=”+n);
i++;
}
}
}
Output
C:\javac numberdemo.java
C:\java numberdemo
Enter number:5 10 15 20 25
number= 5
number= 10
number= 15
number= 20
number= 25

2. write a program to accept 7 characters from the user and display it.
Program:
chardemo.java
import java.io.*;
class chardemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
char c;
int i=1;
System.out.println("Enter character: ");
while(i<=7)
{
c = (char)sc.next(); //Reading character

DEPARTMENT OF CSE Page 152


Object Oriented Programming 2019

System.out.println(“character=”+c);
i++;
}
}
}
Output
C:\javac chardemo.java
C:\java chardemo
Enter character:a b c d e f g
character=a
character=b
character=c
character=d
character=e
character=f
character=g

3. write a program to accept 5 employee name from the user and display it.
Program:
employeedemo.java
import java.io.*;
class employeedemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
String s;
int i=1;
System.out.println("Enter employee name: ");
while(i<=5)
{
s = sc.next();
System.out.println(“employee name=”+s);
i++;
}
}
}
Output
C:\javac employeedemo.java
C:\java employeedemo
Enter employee name:abi binu ravi raghu rahul
employee name= abi
employee name= binu
employee name= ravi
employee name= raghu

DEPARTMENT OF CSE Page 153


Object Oriented Programming 2019

employee name= rahul

4. write a program to accept 3 marks from the user and find the total,average and display
it.
Program:
markdemo.java
import java.io.*;
class markdemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
int m1,m2,m3;
int total;
float average;
System.out.println("Enter mark1: ");
m1=sc.nextInt();
System.out.println("Enter mark2: ");
m2=sc.nextInt();
System.out.println("Enter mark3: ");
m3=sc.nextInt();
total= m1+m2+m3;
average=total/3;
System.out.println("Total="+total);
System.out.println("Average="+average);
}
}
Output
C:\javac markdemo.java
C:\java markdemo
Enter mark1:90
Enter mark2:80
Enter mark3:100
Total=270
Average=90

DEPARTMENT OF CSE Page 154


Object Oriented Programming 2019

CHAPTER IV

MULTITHREADING AND GENERIC PROGRAMMING

Differences between multi-threading and multitasking, thread life cycle, creating

threads, synchronizing threads, Inter-thread communication, daemon threads, thread

groups. Generic Programming – Generic classes – generic methods – Bounded

Types – Restrictions and Limitations.

DEPARTMENT OF CSE Page 155


Object Oriented Programming 2019

DEPARTMENT OF CSE Page 156


Object Oriented Programming 2019

4.1 DIFFERENCES BETWEEN MULTI-THREADING AND MULTITASKING


In programming, there are two main ways to improve the throughput of a program:
i. by using multi-threading
ii. by using multitasking
Multithreading
The system executes multiple threads of the same or different processes at the same time.
Multitasking
The system allows executing multiple programs and tasks at the same time.

Comparison between multithreading and multi-tasking

PARAMETER MULTITHREADING MULTITASKING/


MULTIPROCESSING

1.Fundamental Thread. Process or Task.


Unit
2.Basic Lets CPU to execute multiple threads Lets CPU to execute multiple tasks
simultaneously. simultaneously.

3.Switching CPU switches between threads. CPU switches between process.

4.Cost Cost Effective. It is Expensive.

5.Memory System has to allocate memory to System has to allocate separate


Resources process, multiple threads of that memory and resources to each
process shares the same memory and program that CPU is executing.
resources allocated to the process.
6.Use Helps in developing efficient Helps in developing efficient OS
application programs. programs.
7.Block
Diagram

8.Efficiency Highly Efficient Less Efficient

DEPARTMENT OF CSE Page 157


Object Oriented Programming 2019

Difference between Thread and Process


S.No Thread Process
1 It is the Light Weight Process It is the Heavy Weight Process
Threads does not require separate Process require separate memory address
2
memory address
3 Highly Efficient Less Efficient

4.2 THREAD LIFE CYCLE


Thread
Thread is th light weight process.threads doesnot require separate memory address. Threads does
not require separate memory address for its execution.
A thread can be in one of the five states. the states are
1. New state
2. Runnable state
3. Waiting state
4. Timed Waiting state
5. Blocked state
6. Terminated state
New state
● When a new thread is created, it is in the new state.
● when thread is in this state,the thread has not yet started to run.
Runnable State
● A thread that is ready to run is moved to runnable state.
● In this state, a thread might may be running or may be ready to run.

DEPARTMENT OF CSE Page 158


Object Oriented Programming 2019

Figure: Life Cycle of a thread

Waiting state
● When one thread is waiting for another thread, it is in the waiting state.
● When the condition is fulfilled, waiting thread is moved to the runnable state.
Timed Waiting State
● When thread is waiting for time interval, it is in the Timed waiting state.
● After the time interval,timed waiting thread is moved to the runnable state.
Blocked State
● When the thread is waiting for input and output, it is in the blocked state.
● After getting the input and output resources,blocked thread is moved to the runnable state.
Terminated State:
● When the thread successfully completes the execution, it is moved to the Terminated State.
4.3 CREATING THREADS / IMPLEMENTING THREADS
Thread is th light weight process. Threads does not require separate memory address for
its execution.
Threads are independent, concurrent execution through a program, and each thread has its own
stack.
Threads can be created in two ways
1. Extending ‘Thread’ class.
2. Implementing Runnable interface.

Method used in Thread Creation


Creating Thread

Start() Used to Start a thread by calling its run() method

DEPARTMENT OF CSE
Thread Class Page 159 Runnable interface.
Object Oriented Programming 2019

run Once the thread is started,it executes the thread / Entry point for the thread

setName Used to give the name to the thread

getName Used to get the name of the thread /To obtain thread’s name

sleep Suspend a thread for a period of time

join Wait for a thread to terminate

4.3.1Extending ‘Thread’ class:


Threads can be created by extending the Thread Class.
Steps:
i) Declare the class by extending the Thread class
Example: class mythread extends Thread
{
………….// mythread code
}

ii) Implement the run() method within the class.


Example: class mythread extends Thread
{
Public void run()
{
………
}
}
iii) Create the thread object and call the start() method.
Example: mythread mt=new mythread();
mt.start();
Program
//threaddemo.java
class A extends Thread
{
Public void run()
{
System.out.println("Thread A is created ");
}
class B extends Thread
{

public void run()

DEPARTMENT OF CSE Page 160


Object Oriented Programming 2019

{
System.out.println("Thread B is created ");
}
}
class C extends Thread
{
public void run()
{
System.out.println("Thread C is created ");
}
}
class threaddemo
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
a.start();
b.start();
c.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
Thread A is created
Thread B is created
Thread C is created
4.3.2 Implementing Runnable Interface:
Threads can be created by implementing runnable interface.
Steps:
i) Declare the class by implementing runnable interface.
Example: class mythread implements Runnable
{
………….// mythread code
}
ii) Implements the run() method.
Example: class mythread implements Runnable
{
Public void run()
{
………
}
}

DEPARTMENT OF CSE Page 161


Object Oriented Programming 2019

iii) Create the thread object and call the start() method.
Example: mythread mt=new mythread();
Thread t=new Thread(mt);
mt.start();
Program
// threaddemo.java
class A implements Runnable
{
Public void run()
{
System.out.println("Thread A is created ");
}
class B implements Runnable
{

public void run()


{
System.out.println("Thread B is created ");
}
}
class C implements Runnable
{
public void run()
{
System.out.println("Thread C is created ");
}
}
class threaddemo
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
Thread t1=new thread(a);
Thread t2=new thread(b);
Thread t3=new thread(c);
t1.start();
t2.start();
t3.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo

DEPARTMENT OF CSE Page 162


Object Oriented Programming 2019

Thread A is created
Thread B is created
Thread C is created
4.4 SYNCHRONIZING THREADS
The process of ensuring one access at a time by one thread is called as synchronization.
Synchronization is based on monitor.monitor is used as a mutually exclusive lock or mutex.
When one thread owns this monitor at a time, then other threads cannot access the
resources.They have to be in waiting state.
Methods of synchronization:
Synchronization can be achieved by two ways.
1. Using synchronized method.
2. Using synchronized block or statements.
4.4.1 Synchronized Method
Synchronization can be achieved using synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
Here, we use the synchronized keyword infront of the method name
Syntax:
synchronized returntype methodname()
{
statement1;
statement2;
………….
statementn;
}
Program
//threaddemo.java
class test
{
synchronized void display(int n)
{
System.out.println(“TABLE:”+n);
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
}
System.out.println(“end of table”);
}
try
{
Thread.sleep(1000);
}
catch(Exception e)
{

DEPARTMENT OF CSE Page 163


Object Oriented Programming 2019

System.out.println("Exception occurred");
}
}
class A extends Thread
{
test t1;
A(test t)
{
t1=t;
}
public void run()
{
t1.display(2);
}
}
class B extends Thread
{
test t2;
B(test t)
{
t2=t;
}
public void run()
{
t2.display(10);
}
}
class threaddemo
{
public static void main(String args[])
{
test ts = new test();
A a=new A(ts);
B b=new B(ts);
a.start();
b.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
TABLE:2
2 4 6 8 10 12 14 16 18 20
end of table
TABLE:10

DEPARTMENT OF CSE Page 164


Object Oriented Programming 2019

10 20 30 40 50 60 70 80 90 100
end of table
4.4.2 Synchronized Block
Synchronization can be achieved using synchronized block.
⮚ Synchronized block acquires a lock in the object only between parentheses after the
synchronized keyword.
⮚ This means that no other thread can acquire a lock on the locked object until the
synchronized block exits.
⮚ But other threads can access the rest of the code of the method.
⮚ Here, we create the block of code and write synchronized keyword infront of Block.
Syntax:
synchronized (object reference)
{
statement1;
………….
statementn;
}
Program
//threaddemo.java
class test
{
void display(int n)
{
synchronized(this)
{
System.out.println(“TABLE:”+n);
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
}
System.out.println(“end of table”);
}
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Exception occurred");
}
}
class A extends Thread
{
test t1;
A(test t)

DEPARTMENT OF CSE Page 165


Object Oriented Programming 2019

{
t1=t;
}
public void run()
{
t1.display(2);
}
}
class B extends Thread
{
test t2;
B(test t)
{
t2=t;
}
public void run()
{
t2.display(10);
}
}
class threaddemo
{
public static void main(String args[])
{
test ts = new test();
A a=new A(ts);
B b=new B(ts);
a.start();
b.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
TABLE:2
2 4 6 8 10 12 14 16 18 20
end of table
TABLE:10
10 20 30 40 50 60 70 80 90 100
end of table
4.5 INTER-THREAD COMMUNICATION
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other. Two or more threads can communicate with each other by
exchanging the messages. This mechanism is called Inter-thread communication.
Inter-thread communication can be achieved by using three methods

DEPARTMENT OF CSE Page 166


Object Oriented Programming 2019

1. wait()
2. notify()
3. notifyAll()
i.wait()
The calling thread can be sent into the sleeping mode.
Syntax: wait();
ii.notify()
If the particular thread is in sleeping mode,then that thread can be resumed using the notify
cal. It resume the thread that is in sleeping state.
syntax:
public final void notify()
3.notifyAll()
It resume all the threads that are in the sleeping mode.
syntax:
public final void notifyAll()
Example.
The explanation of the below diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.

Producer Consumer Problem


Producer consumer problem is handled by interthraed communication.
Producer-A Consumer-b
Put() Get()

DEPARTMENT OF CSE Page 167


Object Oriented Programming 2019

Flag=false flag=false
Produce no 1 Sleeping Mode
Flag=true
Notify()

Sleeping Mode Read non 1


Flag=false
Notify()
Produce no 1
Flag=true Sleeping Mode
Notify()

Sleeping Mode

myclass
flag=false
Program val
//interthreaddemo.java
class myclass get()
{ put()
int val;
boolean flag=false;
A B
synchronized int get()
{ get()
if(flag=false)
put()
{
try
{
wait(); InterThread
}
catch(Exception e)
{ A().start();
System.out.println("Exception occurred");
B().start();
}
}
System.out.println("consumer consuming:"+val);
flag=false;
notify();
return val;
}
synchronized void put()
{

DEPARTMENT OF CSE Page 168


Object Oriented Programming 2019

if(flag=true)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println("Exception occurred");
}
}
this.val=val;
System.out.println("producer producing:"+val);
flag=true;
notify();
}
class Producer extends Thread
{
myclass m1;
producer(myclass t)
{
m1=t;
}
public void run()
{
for(int i=0;i<=10;i++)
{
m1.put(i);
}
}
}
class consumer extends Thread
{
myclass m1;
consumer(myclass t)
{
m2=t;
}
public void run()
{
for(int i=0;i<=10;i++)
{
m2.get(i);
}
}

DEPARTMENT OF CSE Page 169


Object Oriented Programming 2019

}
class interthreaddemo
{
public static void main(String args[])
{
myclass m = new myclass();
producer p=new producer(m1);
consumer c=new consumer(m2);
p.start();
c.start();
}
}
Output:
C:\javac interthreaddemo.java
C:\java interthreaddemo
producer producing:0
consumer producing:0
producer producing:1
consumer producing:1
producer producing:2
consumer producing:2
producer producing:3
consumer producing:3
producer producing:4
consumer producing:4
producer producing:5
consumer producing:5
producer producing:6
consumer producing:6
producer producing:7
consumer producing:7
producer producing:8
consumer producing:8
producer producing:9
consumer producing:9
producer producing:10
consumer producing:10
4.6 DAEMON THREADS
Daemon thread is a low priority thread that runs in background to perform tasks such as garbage
collection. Daemon thread in java is also called as service provider thread which provides services
to the user thread.
Methods for Java Daemon thread
Method Description

DEPARTMENT OF CSE Page 170


Object Oriented Programming 2019

setDaemon() used to mark the current thread as daemon


thread or user thread.
run() Executes the daemon thread
isDaemon() used to check whether the thread is daemon
or not.
Program
//daemonThread.java
class DaemonThread extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("This is Daemon thread");
}
else
{
System.out.println("This is User thread");
}
}
public static void main(String[] args)
{
DaemonThread t1 = new DaemonThread();
DaemonThread t2 = new DaemonThread();
DaemonThread t3 = new DaemonThread();
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
t3.setDaemon(true);
}
}
Output:
This is Daemon thread
This is User thread
This is Daemon thread
4.7 THREAD GROUP
ThreadGroup creates a group of threadscand managethe groups of threads as a unit. It is
implemented by ‘ThreadGroup’ class.
Constructors of ThreadGroup class
The two constructors of ThreadGroup class are:
Constructor Description

DEPARTMENT OF CSE Page 171


Object Oriented Programming 2019

ThreadGroup(String name) creates a thread group with given name.

ThreadGroup(ThreadGroup parent, String creates a thread group with given parent group and
name) name.
Methods used in ThreadGroup class
Method Description

activeCount() returns no. of threads running in current Threadgroup.

activeGroupCount() returns a no. of active group in the thread group.


destroy() destroys this thread group and all its sub groups.

getName() returns the name of the thread group.

getParent() returns the parent of the thread group.

interrupt() interrupts all threads of the thread group.

list() It is used to list the threads in the thread group.


Program
ThreadGroup.java
class ThreadGroup implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
ThreadGroup tgd = new ThreadGroup();
ThreadGroup tg1 = new ThreadGroup("colours");
Thread t1 = new Thread(tg1, tgd,"red");
t1.start();
Thread t2 = new Thread(tg1, tgd,"yellow");
t2.start();
Thread t3 = new Thread(tg1,tgd,"blue");
t3.start();
System.out.println("no of active threads: "+tg1.activecount());
System.out.println("thread list: "+tg1.list());
}
}
Output:
red
yellow
blue
no of active threads: 3
DEPARTMENT OF CSE Page 172
Object Oriented Programming 2019

thread list
java.lang.ThreadGroup[name=colours,maxpri=10]
Thread[red,3,Parent ThreadGroup]
Thread[yellow,3,Parent ThreadGroup]
Thread[blue,3,Parent ThreadGroup]
4.8 GENERIC PROGRAMMING
Generic Programming is a mechanism for creating general model for different datatypes.
generic programming

generic class generic method


what is the need for generic/Advantages
⮚ code reusability
⮚ easier to read
⮚ create compact code
⮚ time consuming is less
⮚ easy to debug,maintain
⮚ avoid extra effort
4.8.1 GENERIC CLASS
A class that can refer to any type is known as generic class. generic class enables programmer to
specify general class for classes of different datatypes.It can adopt classes of different data types.
Syntax to declare a generic class
class Class_name <T>
{
//code
}
where, <> brackets indicates that the class is of generic type with type parameter T.
T -🡪 anydatatype (like String, Integer, Student etc.).
Type Parameters
The commonly used type parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V – Value
Syntax to create an object of a generic class
Classname <data type> obj = new Classname<data type> ();
or
Classname <data type> obj = new Classname<>();
Program
genericclassdemo.java
class GenericClass <T> //<> brackets indicates that the class is of generic type
{
T a; //an object of type T is declared
GenericClass(T a) //constructor
{

DEPARTMENT OF CSE Page 173


Object Oriented Programming 2019

this.a = a;
}
T get()
{
return a;
}
}
class genericclassdemo
{
public static void main (String[] args)
{
GenericClass< Integer> gc1 = new GenericClass<Integer>(10); //instance of Integer type Gen
Class.
System.out.println(“integer=”+gc1.get());
GenericClass< float> gc2 = new GenericClass<float>(10.5);
System.out.println(“float=”+gc2.get());
GenericClass< String> gc3 = new GenericClass<String>("Hello"); //instance of String type Gen
Class.
System.out.println(“string=”+gc3.get()); }
}
Output:
C:\javac genericclassdemo.java
C:\java genericclassdemo
integer=10
float=10.5
string=Hello
4.8.2 GENERIC METHODS
⮚ Generic Method can accept any type of argument like generic class.
⮚ Genric method enables the programmer to specify the general method for the methods of
different datatypes.
Syntax for a generic method
<type-parameter> returntype methodname (parameters)
{
...........
}
where, <> brackets 🡪method of generic type with type parameter T.
T -🡪 anydatatype (like String, Integer, Student etc.).
Program
Finding Maximum Number Using Generic Method
maxdemo.java
class maxdemo
{
public static<T extends comparable> T maximum(T x,T y,T z)
{
T max;

DEPARTMENT OF CSE Page 174


Object Oriented Programming 2019

if(y.CompareTo(max)>0)
max=y;
if(z.CompareTo(max)>0)
max=z;
return max;
}
public static void main(String args[])
{
System.out.println(“maximum(2,5,4)=”+maximum(2,5,4));
System.out.println(“maximum(10.5,5.6,7.3)=”+maximum(10.5,5.6,7.3));
System.out.println(“maximum(“pear”,”apple”,”mango”)=”+maximum(“pear”,”apple”,”mango”)
);
}
}
Output:
C:\javac maxdemo.java
C:\java maxdemo
maximum(2,5,4)=5
maximum(10.5,5.6,7.3)=10.5
maximum(“pear”,”apple”,”mango”)=pear
4.9 BOUNDED TYPES
Using the bounded types, we can create the generic class of specific derived datatypes.
Example:
If we want to create the genric class for only numbers(int,double,float,long),then we use the
bounded type”numbers”
Syntax for declaring bounded types:
class classname <T extends superclass>
{
}
Program
//boundedclassdemo.java
class boundedClass <T extends Number>
{
T a;
boundedClass(T a)
{
this.a = a;
}
T get()
{
return a;
}
}
class boundedclassdemo
{

DEPARTMENT OF CSE Page 175


Object Oriented Programming 2019

public static void main (String[] args)


{
boundedClass< Number> bc1 = new boundedClass<Number>(10);
System.out.println(“integer=”+bc1.get());
boundedClass< Number> bc2 = new boundedClass<Number>(10.5);
System.out.println(“float=”+bc2.get());
boundedClass< Number> bc3 = new boundedClass<Number>("1890.7");
System.out.println(“double=”+bc3.get());
}
}
Output:
C:\javac genericclassdemo.java
C:\java genericclassdemo
integer=10
float=10.5
double=1890.7
4.10 RESTRICTIONS AND LIMITATIONS
1. In java,generic types arecompile time entities.The runtime execution is possible only if it
is used along with raw type.
2. Primitive type parameters is not allowed for generic programming
for example, stack<int> is not allowed.
3. For the instances of generic class throw and catch instances are not allowed.
for example: Public class Test<T>extends Exception
{
//code //Error:can’t extend the Exception class.
}
4. Instantiation of generic parameter T is not allowed.
for example:
new T() //Error
new T[10]
5. Arrays of parameterized types are not allowed.
for example
new stack<string>[10];//Error
6. Static fields and static methods with type parameters are not allowed.

DEPARTMENT OF CSE Page 176


Object Oriented Programming 2019

PART A (2 Marks with Answers)


1.what is multithreading?(Nov/Dec2018)
The system executes multiple threads of the same or different processes at the same time.
Multithreading is a conceptual programming concept where a program(process) is divid d into
two or more subprograms(process), which can be implemented at the same time in parall l. A
multithreaded program contains two or more parts that can run concurretly Each part of such a
program is called a thread, and each thread defines a separate path of execution
2.what is the need for generic code?( Nov/Dec2018)
⮚ code reusability
⮚ easier to read
⮚ create compact code
⮚ time consuming is less
⮚ easy to debug,maintain
⮚ avoid extra effort
3.How Threads are created in Java?
Threads are created in two ways. They are by extending the Thread class and by implementing
Runnable interface.
4. Define Thread?
A thread is a single sequential flow of control within program. Sometimes, it is called an
execution context or light weight process. A thread itself is not a program.A
thread cannot run on its own. Rather, it runs within a program. A program can be divided
into a number of packets of code, each representing a thread having its own separa flow of
control.
5.What is Thread Pool?
A thread pool is a managed collection of threads that are available to perform tasks. Thread
pools usually provide:
Improved performance when executing large numbers of tasks due to reduced per-task
invocation overhead
A means of bounding the resources, including threads, consumed when executing a
process.
6.What is Synchronization thread?
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which this
synchronization is achieved is called thread synchronization.
7.What do you mean by generic programming?

DEPARTMENT OF CSE Page 177


Object Oriented Programming 2019

Generic programming is a style of computer programming in which algorithms are written in


terms of to-be-specified-later types that are then instantiated when needed for specific types
provided as parameters
8.Define thread group?
Every Java thread is a member of a thread group. Thread groups provide a mechanism for
collecting multiple threads into a single object and manipulating those threads all at once, rather
than individually. For example, you can start or suspend all the threads wi hin a group with a
single method call.
9. How to create generic class?
A class that can refer to any type is known as g n ric class. Here, we are using T type
parameter to create the generic class of specific type.
example to create and use the generic class.
Creating generic class:
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;} }
The T type indicates th t it c n refer to ny type (like String, Integer, Employee etc.). The type
you specify for the class, will be used to store and retrieve the data.
10.What are wildcards in generics?
In generic code, the question mark (?), called the wildcard, represents an unknown type.
The wildcard can be used in a variety of situations: as the type of a parameter, field, or local
variable; sometimes as a return type (though it is better programming practice to be more
specific).
11.What are the restrictions on generics?
To use Java generics effectively, you must consider the following restrictions:
1. Cannot Instantiate Generic Types with Primitive Types
2. Cannot Create Instances of Type Parameters
3. Cannot Declare Static Fields Whose Types are Type Parameters
4. Cannot Use Casts or instance of With Parameterized Types
5. Cannot Create Arrays of Parameterized Types
6. Cannot Create, Catch, or Throw Objects of Parameterized Types
7. Cannot Overload a Method Where the Formal Parameter Types of Each Overload
Erase o the Same Raw Type
12.List some methods supported by Threads.
● join(): It makes to wait for this thread to die. We can wait for a thread to finish by calling
its join() method.
● sleep(): It makes current executing thread to sleep for a specified interval of time. Time is
in milli seconds.
● yield(): It makes current executing thread object to pause temporarily and gives control to
other thread to execute.
● notify(): This method is inherited from Object class. This method wakes up a single thread
that is waiting on this object's monitor to acquire lock.
● notifyAll(): This method is inherited from Object class. This method wakes up all threads
that are waiting on this object's monitor to acquire lock.

DEPARTMENT OF CSE Page 178


Object Oriented Programming 2019

● wait(): This method is inherited from Object class. This method makes current thread to
wait until another thread invokes the notify() or the notifyAll() for this object.

13.What are the types of Synchronization?

There are two types of synchronization:


i.Process Synchronization
ii.Thread Synchronization
14.Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
15.What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a
wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll()
call. The method wait() is defined in the class Object and the method sleep() is defined in the class
Thread.
16. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple
threads to shared resources. Without synchronization, it is possible for one thread to modify a
shared object while another thread is in the process of using or updating that object's value. This
often leads to significant errors.
17.When you will synchronize a piece of your code?
When you expect your code will be accessed by different threads and these threads may change a
particular data causing data corruption.
18.What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep()
method, it returns to the waiting state.
19.How to implement generic method in Java?
Generic methods are methods that can accept any type of argument.
Syntax:
<type-parameter> return_type method_name (parameters) {...}
Example:
public void display(T data) {
System.out.println(data);
}
20.What is Erasure?
The Java compiler applies type erasure to implement generic programming. It replaces all type
parameters in generic types with their bounds or Object if the type parameters are unbounded.

DEPARTMENT OF CSE Page 179


Object Oriented Programming 2019

PART B (Possible Questions)

1.Explain in detail the different states of a thread.(Nov/Dec2018)


2.Demonstrate inter thread communication and suspending,resuming and stoping threads.
(Nov/Dec2018)
3.What are the two ways of thread creation? Explain with suitable examples
4.With illustrations explain multithreading, interrupting threads, thread states with thread
properties.
5.Describe the life cycle of thread and various thread methods.
6. Describe in detail about multithread programming with
example.
7.Write a java program that synchronizes three different threads of the same program and
displays the contents of the text supplies through the threads.
8. Summarize the following
i.Thread priorities
ii.Deamon thread
9.What are the restrictions are considered to use java generics effectively? Explain in detail.
10.i.Illustrate the concept of synchronization in thread.
ii.Write a Java code for reader writers problem.
11. i.Formulate the motivations of generic programming.
ii.Develop a program to show generic class and methods with example.

DEPARTMENT OF CSE Page 180


Object Oriented Programming 2019

PART C(Possible Questions)


1.Create a bank Database application program to illustrate the use of multithreads.(Nov/Dec
2018)
2.Write a java program for inventory problem to illustrate the usage of thread synchronized
keyword and inter thread communication process. They have three classes called
consumer,producer and stock.Explain in detail about generic classes and m thods in java with
suitable example.
3. Generalize multithreading for an sample sequence of strings with a delay of 1000 millisecond
for displaying it using Java threads.
4. Assess an example program in Java on how to implement bounded types (extend superclass)
with generics.
5. Deduce a Java program to perform the following tasks using three different threads. Each
thread will be responsible for its own task only. Among these three threads one will find the
average number of the input numbers, one will be responsible for finding the Maximum number
from the input array of numbers, and one will be responsible for finding the minimum number
from the input array of numbers.

DEPARTMENT OF CSE Page 181


Object Oriented Programming 2019

ADDITIONAL PROGRAMS
1.write the java program to create two threads named x and y.Thread x display the
number from 1 to 10.Thread y display the number from 11 to 20.
Program
threaddemo.java
class X extends Thread
{
Public void run()
{
int i;
for(i=1;i<=10;i++)
System.out.println(i);
}
class Y extends Thread
{

public void run()


{
int i;
for(i=11;i<=20;i++)
System.out.println(i);
}
}
class threaddemo
{
public static void main(String args[])
{
X x=new X();
Y y=new Y();
x.start();

DEPARTMENT OF CSE Page 182


Object Oriented Programming 2019

y.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2.write a program to print numbers from 1 to 10 lone by line after every 10 seconds.
Program
threaddemo.java
class X extends Thread
{
Public void run()
{
for(i=1;i<=10;i++)
System.out.println(i);
Thread.sleep(10000);
}
}
class threaddemo
{
public static void main(String args[])
{
X x=new X();
x.start();
}

DEPARTMENT OF CSE Page 183


Object Oriented Programming 2019

}
Output:
C:\javac threaddemo.java
C:\java threaddemo
1
2
3
4
5
6
7
8
9
10

DEPARTMENT OF CSE Page 184


Object Oriented Programming 2019

CHAPTER V

EVENT DRIVEN PROGRAMMING

Graphics programming – Frame – Components – working with 2D shapes – Using

color, fonts, and images – Basics of event handling – event handlers – adapter classes

– actions – mouse events – AWT event hierarchy – Introduction to Swing – layout

DEPARTMENT OF CSE Page 185


Object Oriented Programming 2019

management – Swing Components – Text Fields , Text Areas – Buttons- Check

Boxes – Radio Buttons – Lists- choices- Scrollbars – Windows –Menus – Dialog

Boxes.

DEPARTMENT OF CSE Page 186


Object Oriented Programming 2019

DEPARTMENT OF CSE Page 187


Object Oriented Programming 2019

EVENT DRIVEN PROGRAMMING


5.1 INTRODUCTION TO GRAPHICS PROGRAMMING
Graphics is one of the most important features of Java. The graphics programming in Java is
supported by the AWT package. The AWT stands for Abstract Window Toolkit.
The AWT is an API which contains a large number of classes which helps to include various
graphical components in the Java program, for creating user interfaces and for painting graphics
and images.

Fig. 5.1 AWT Hierarchy

Graphical User Interface (GUI) offers user interaction with these graphical components. The
graphical components include text box, buttons, labels, radio buttons, list items and so on. We
need to import java.net package for using these components. These classes are arranged in
hierarchical manner which is recognized as AWT hierarchy. The hierarchy component classes are,

DEPARTMENT OF CSE Page 188


Object Oriented Programming 2019

i) Component
A component is an object having a graphical representation that can be displayed on the screen
and that can interact with the user. The Component class is the abstract superclass of all user
interface elements that are displayed on the screen. A Component object remembers current text
font, foreground and background color.
Examples: buttons, checkboxes, and scrollbars
ii) Container
The Container class is the subclass of Component. The container object is a component that can
contain other AWT components. It is responsible for managing the layout and placement of
graphical components in the container.
iii) Window
The class Window is a top level window with no border and no menu bar. The default layout for
a window is Border Layout. It decides the layout of the window.
iv) Panel
The class Panel is the derived from the container class. So it is a simplest container class. It
provides space in which an application can attach any other component, including other panels. It
is just similar to window without any border and without any menu bar, title bar.
v) Frame
A Frame is a top-level window with a title and a border. It supports the common window events
such as window open, close, activate and deactivate.
vi) Dialog
A Dialog is a top-level window with a title and a border that is typically used to take some form
of input from the user.
vii) Canvas
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the user. An
application must subclass the Canvas class in order to get useful functionality such as creating a
custom component.
5.1.1 FRAMES
A Frame is a top-level window with a title and a border. Frame encapsulates window. It and has
a title bar, menu bar, borders, and resizing corners. In Java, the Frame is a standard window.
The Frame can be displayed using the Frame class. The Frames has standard minimize, maximize
and close buttons.
Frame Constructor
● Frame()
Constructs a new instance of Frame that is initially invisible
● Frame(String title)
This creates the new instance of frame which has some title.
Methods of Frame class
Methods Description
String getTitle() Gets the title of the frame.
void Sets the background color of this window.
setBackground(Color bgColor)
void Sets whether this frame is resizable by the user.
setResizable(boolean resizable)

DEPARTMENT OF CSE Page 189


Object Oriented Programming 2019

void setShape(Shape shape) Sets the shape of the frame.


void setTitle(String title) Sets the title for this frame to the specified string.
void setSize(Dimension d) Resizes this frame with width and height
void setVisible(boolean b) Shows or hides this Window depending on the
value of parameter b.
public void show() Makes the Window visible
void Sets the menu bar for the frame
setMenuBar(MenuBar mb)
Creating a Frame
A Frame can be created by two ways:
1. By creating the object (instance) of Frame class
2. By extending Frame class
Method 1: By creating the object (instance) of Frame class
Syntax:
class classname
{
Frame obj=new Frame();
}
Program:
//FrameDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Java AWT Frame”);
fr.setSize(300,300);
fr.setVisible(true);
}
}
Output:
javac FrameDemo.java
java FrameDemo

DEPARTMENT OF CSE Page 190


Object Oriented Programming 2019

Method 2: By extending Frame class


Syntax:
class classname extends Frame
{
………………
}
Program:
//FrameDemo.java
import java.awt.*;
class FrameDemo extends Frame
{
FrameDemo()
{
setTitle(“Java AWT Frame”);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
FrameDemo fr = new FrameDemo();
}
}
Output:
javac FrameDemo.java
java FrameDemo

DEPARTMENT OF CSE Page 191


Object Oriented Programming 2019

5.2 COMPONENTS
A component is an object with a graphical representation that can be displayed on the screen and
that can interact with the user. There are various graphical components that can be placed on the
frame.
Various components for designing user interfaces are,
1. Label
2. Buttons
3. Canvas
4. Scroll bars
5. Text Components
6. Checkbox
7. Choices
8. List Panels
9. Dialogs
i) LABELS:
Labels are the components which hold the text. They allow us to add a text description to a point
on the application. The Label can be Left aligned, right aligned or it can be centered.
Syntax:
Label labelname = new Label (String);
Label labelname = new Label (String, Label.style);
Example:
Label labelname = new Label ("This is the label text", Label.CENTER);
The above declaration makes the text centered.
Program:
//FrameDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Java AWT Frame”);
fr.setSize(300,300);

DEPARTMENT OF CSE Page 192


Object Oriented Programming 2019

fr.setVisible(true);
fr.setLayout(new FlowLayout());
Label L1=new Label(“WELCOME”);
fr.add(L1);
}
}
Output:
javac FrameDemo.java
java FrameDemo

ii) BUTTONS
Buttons are called as push buttons. This component contains a text (or a label) .It generates an
event when that label is pressed.
Syntax:
Button buttonname = new Button (label/text);
Button buttonname[] = new Button[size];;
Program:
//ButtonDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Button Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Buttton b1 =new Button(“click Here”);
fr.add(b1);
}
}

DEPARTMENT OF CSE Page 193


Object Oriented Programming 2019

Output:
javac ButtonDemo.java
java ButtonDemo

iii) CANVAS
Canvas is a special area created on the frame. Canvas is a blank rectangular area which is used for
drawing the graphical components such as oval, rectangle, line and so on.
Syntax:
Canvas Canvasname = new Canvas();
Methods Description
void setSize(intwidth, int height) This method sets the size of the canvas for given width
and height.
void setBackground(Color c) Sets the background color of the canvas.
void setForeground(Color c) Sets method sets the color of the text.
Program:
// CanvasDemo.java
import java.awt.*;
class CanvasDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Canvas Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Canvas c1 = new Canvas();
c1.setSize(100,100);
c1.setBackground (Color.GRAY);
fr.add(c1);
}
}
Output:

DEPARTMENT OF CSE Page 194


Object Oriented Programming 2019

javac CanvasDemo.java
java CanvasDemo

iv) SCROLLBARS:
Scrollbar can be represented by the slider widgets. There are two styles of scrollbars . They are,
● Horizontal scrollbar
● Vertical scrollbar.
Syntax:
Scrollbar obj= new Scrollbar(Scrollbar.style);
Program:
//ScrollbarDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Scrollbar Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Scrollbar s=new Scrollbar(Scrollbar.Vertical);
fr.add(s);
}
}
Output:
javac ScrollbarDemo.java
java ScrollbarDemo

DEPARTMENT OF CSE Page 195


Object Oriented Programming 2019

iv) TEXT COMPONENTS


In Java there are two text components. They are,
● TextField
● TextArea.
Text Field
It is a slot in which one line can be entered. In the TextField we can enter the string, modify it,
copy, cut or paste it.
Syntax:
TextField obj=new TextField(int n);
where n is the total number of characters in the string.
Program:
//TextFieldDemo.java
import java.awt.*;
class TextFieldDemo
{
public static void main(String args[])
{
Frame f= new Frame("TextField Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
TextField t1=new TextField("Welcome to Javatpoint.");
TextField t2=new TextField("AWT Tutorial");
f.add(t1);
f.add(t2);
}
}
Output
javac TextFieldDemo.java

DEPARTMENT OF CSE Page 196


Object Oriented Programming 2019

java TextFieldDemo

Text Area
The Text Area is used to handle multi-line text.
Syntax
TextAre area= new TextArea(int n, int m);
where n is the number of lines and m is the number of characters.
Program:
//TextAreaDemo.java
import java.awt.*;
class TextAreaDemo
{
public static void main(String args[])
{
Frame f= new Frame("TextArea Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
TextArea area=new TextArea("Welcome to javatpoint");
f.add(area);
}
}
Output:
javac TextAreaDemo.java
java TextAreaDemo

DEPARTMENT OF CSE Page 197


Object Oriented Programming 2019

v) CHECK BOX:
A checkbox is again a label which is displayed as a pushbutton. This pushbutton can either be
checked or unchecked. Therefore, the state of the checkbox is either true or false.
Syntax
Checkbox checkboxname = new Checkbox();
Checkbox checkboxname = new Checkbox(String);
Program:
//CheckboxDemo.java
import java.awt.*;
class CheckboxDemo
{
public static void main(String args[])
{
Frame f= new Frame("Checkbox Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
Checkbox box1 = new Checkbox("C++");
Checkbox box2 = new Checkbox("Java", true);
f.add(box1);
f.add(box2);
}
}
Output:
javac CheckboxDemo.java

DEPARTMENT OF CSE Page 198


Object Oriented Programming 2019

java Checkbox Demo

vi) CHECKBOX GROUP:


The CheckboxGroup class is used to group the set of checkbox. It allows the user to make one and
only selection at atime. Thes checkbox groups is also called as radio buttons.
Syntax
CheckboxGroup Checkboxname = new CheckboxGroup();
Checkbox obj = new Checkbox(String s, Checkbox cbg, Boolean val);
Program:
//CheckboxGroupDemo.java
import java.awt.*;
class CheckboxGroupDemo
{
public static void main(String args[])
{
Frame f= new Frame("CheckboxGroup Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox box1 = new Checkbox("C++", cbg, false);
Checkbox box2 = new Checkbox("Java", cbg, true);
f.add(box1);
f.add(box2);
}
}
Output:
javac CheckboxGroupDemo.java
java Checkbox GroupDemo

DEPARTMENT OF CSE Page 199


Object Oriented Programming 2019

vii) CHOICES:
Choice class is used to show popup menu of choices. Choice selected by user is shown on the top
of the menu.
Syntax
Choice choicename = new Choice();
Program:
//ChoiceDemo.java
import java.awt.*;
class ChoiceDemo
{
public static void main(String args[])
{
Frame f= new Frame("Choice Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
Choice c=new Choice();
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
}
}
Output:
javac ChoiceDemo.java.
java ChoiceDemo

DEPARTMENT OF CSE Page 200


Object Oriented Programming 2019

viii) LIST PANELS:


List is a collection of many items. By double clicking the desired item we can select it. It is similar
to the Choice component, except it shows multiple items at a time and user is allowed to select
either one or multiple items at a time
Syntax
List listname =new List();
Program:
//ListDemo.java
import java.awt.*;
class ListDemo
{
public static void main(String args[])
{
Frame f= new Frame("List Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
Choice c=new Choice();
List L1=new List(5);
L1.add("Item 1");
L1.add("Item 2");
L1.add("Item 3");
L1.add("Item 4");
L1.add("Item 5");
f.add(L1);
}
}
Output:
javac ListDemo.java.

DEPARTMENT OF CSE Page 201


Object Oriented Programming 2019

java ListDemo

5.3 WORKING WITH 2D SHAPES:


Java has an ability to draw various 2-dimensional shapes using methods Graphics2D class. To
work with 2D shape, we have to extend canvas class.
Canvas
Canvas is a special area created on the frame. Canvas is a blank rectangular area which is used for
drawing the graphical components such as oval, rectangle, line and so on.
Syntax:
Canvas Canvasname = new Canvas();
Methods Description
void setSize(intwidth, int height) This method sets the size of the canvas for given width
and height.
void setBackground(Color c) Sets the background color of the canvas.
void setForeground(Color c) Sets method sets the color of the text.
2-D Shapes are following,
1. Line
2. Rectangle
3. Oval
4. Arc
5. Polygon
5.3.1 LINES
It is the simplest shape that we can draw with Graphics class. The drawLine() method is used to
draw a line between two points.
Syntax:
void drawLine(int x1, int y1, int x2, int y2)
where,
● x1 and y1 are starting point coordinates
● x2 and y2 are ending point coordinates of the line.
Example: drawLine (20, 100, 90, 100)

DEPARTMENT OF CSE Page 202


Object Oriented Programming 2019

Program:
//LineDemo.java
import java.awt.*;
class LineDemo extends Canvas
{
LineDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
LineDemo L1=new LineDemo();
fr.add(L1);
}
public void paint( Grpahics g)
{
g.drawLine(0,0,200,100);
g.drawLine(0,100,100,0);
}
}
Output:
javac LineDemo.java.
java LineDemo

DEPARTMENT OF CSE Page 203


Object Oriented Programming 2019

5.3.2 RECTANGLES
In Java, we can draw two type of rectangles:
● Normal rectangle
● Rectangle with round corners.
Syntax
void drawRect(int top,int left,int width,int height)
void drawRoundRect(int top, int left,int width,int height, int xdimeter, int ydimeter)
void fillRect(int top, int left, int width,int height)
void fillRound(int top,int left, int width, int height, int xdiameter, int ydiameter)
Example: g.drawRect (20 , 20 , 50 , 30 )

Figure Rectangle

Program:
// RectangleDemo.java
import java.awt.*;
class RectangleDemo extends Canvas
{
RectangleDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
RectangleDemo r1=new RectangleDemo();
fr.add(r1);
}
public void paint( Grpahics g)
{

DEPARTMENT OF CSE Page 204


Object Oriented Programming 2019

g.drawRect(10,10,50,50);
g.drawRoundRect(70,30,50,30,10,10);
}
}

Output:
javac RectangleDemo.java.
java RectangleDemo

5.3.3 OVAL
drawOval()method can be used to draw ellipses or circles.
Syntax
drawOval( int top, int left, int width, int height)
fillOval(int top, int left, int width, int height)

Figure Ellipse

Program:
// ovalDemo.java
import java.awt.*;
class ovalDemo extends Canvas
{

DEPARTMENT OF CSE Page 205


Object Oriented Programming 2019

ovalDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
ovalDemo L1=new ovalDemo();
fr.add(L1);
}
public void paint( Grpahics g)
{
g.drawOval(10,10,50,50);
g.fillOval(200,10,70,100);
}
}
Output:
javac ovalDemo.java.
java ovalDemo

5.3.4 ARCS
An arc can be drawn using the drawArc () method.
Synatx:
void drawArc (int top, int left, int width, int height, int angle1, int angle2)
void fillArc (int top, int left, int width, int height, int angle1, int angle2)
where,
angle1 is the starting angle of the arc (in degrees)
angle2 is the number of degrees (angular distance) around the arc (in degrees)

DEPARTMENT OF CSE Page 206


Object Oriented Programming 2019

Example:
fillArc(20,20,100,100,180,180);
drawArc(140,20,100,100,100,0,90);
fillArc(20,140,100,100,360,270);
drawArc(140,140,100,100,180,270);

Program:
// ArcDemo.java
import java.awt.*;
class ArcDemo extends Canvas
{
ArcDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
ArcDemo L1=new ArcDemo ();
fr.add(L1);
}
public void paint( Grpahics g)
{
g.fillArc(20,20,100,100,180,180);
g.drawArc(140,20,100,100,100,0,90);
}
}
Output:
javac ArcDemo.java.
java ArcDemo

DEPARTMENT OF CSE Page 207


Object Oriented Programming 2019

5.3.5 POLYGANS
A polygon is a closed figure with many lines joined one to another. The ending point of one line
is the starting point to another line and finally the last point is joins with the first point.
Syntax
drawPolygon(xpoints, ypoints, num);
Where,
● num represents the count of points
● xpoints represents the array of x-coordinates.
● ypoints represents the array of y-coordinates.
Example:
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
Program:
// polygonDemo.java
import java.awt.*;
class polygonDemo extends Canvas
{
polygonDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
polygonDemo L1=new polygonDemo();
fr.add(L1);
}
public void paint( Grpahics g)
{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}

DEPARTMENT OF CSE Page 208


Object Oriented Programming 2019

}
Output:
javac polygonDemo.java.
java polygonDemo

5.4 APPLET
Applets are small Java applications that can be accessed on an Internet server, transported over
Internet, and can be automatically installed and run as a part of a web document.
Applet is a predefined class in java.applet package used to design distributed application. It is a
client side technology. Applets are run on web browser.
Advantage of Applet
● Applets are supported by most web browsers.
● Applets works on client side so less response time.
● Secured: No access to the local machine and can only access the server it came from.
● Easy to develop applet, just extends applet class.
● To run applets, it requires the Java plug-in at client side.
● Android, do not run Java applets.
● Some applets require a specific JRE. If it required new JRE then it takes more time to
download new JRE.
5.4.1LIFE CYCLE OF AN APPLET

DEPARTMENT OF CSE Page 209


Object Oriented Programming 2019

Fig. Applet’s life cycle


There are 4 states in lifecycle of applet. They are,
1. Born state- init()
2. Running State - start ()
3. Display state – paint()
4. Idle State –Stop ()
5. Dead or destroyed state() –destroy()
1. Born state- init()
When the applet gets loaded it enters in the initialization state. init() method is called at the time
of starting the execution. This is called only once in the life cycle. In this method, the applet object
is created by the browser.
Syntax
public void init()
{
//initialization of variables
}
2. Running State - start ()
When the applet enters in the running state, it invokes the start() method. start() method is called
after the init() method. In start() method, applet becomes active and thereby eligible for processor
time.
syntax
public void start()
{
…..
}
3. Display state-paint():
paint() method is called by the start() method. This is called number of times in the execution. This
class includes many methods of drawing necessary to draw on the applet window. This is the place
where the programmer can write his code of what he expects from applet like animation etc. This
is equivalent to runnable state of thread.

DEPARTMENT OF CSE Page 210


Object Oriented Programming 2019

Syntax
public void paint(Graphics g)
{
…..
}
4. Idle State –Stop ()
In this method the applet becomes temporarily inactive. An applet can come any number of times
into this method in its life cycle and can go back to the active state (paint() method). It is equivalent
to the blocked state of the thread.
Syntax
public void stop()
{
…..
}

5. Dead or destroyed state() –destroy()


This is the end of the life cycle of applet. It is the best place to have cleanup code. It is equivalent
to the dead state of the thread. destroy() method is called when the applet is closed. This method
is called only once in the life cycle.
Syntax
public void destroy()
{
……
}
Program:
import java.applet.*;
import java.awt.*;
/*
<applet code="SimpleApplet.class" height="250" width="250">
</applet>
*/
public class SimpleApplet extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy()

DEPARTMENT OF CSE Page 211


Object Oriented Programming 2019

{
}
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.drawString("Hello World", 50, 100);
}
}

5.4.2 EXECUTING / RUNNING AN APPLET IN JAVA


Java Applet is compiled by javac command. It can be run by two ways
1. Using appletviewer
2. Web Browser
Using Web Browser :
a) Create an HTML file , containing the APPLET tag.
<html>
<body>
<applet code=”GraphicsDemo.class” width=”300” height=”300”>
</applet>
</body>
</html>
b) Compile the applet source code using javac.
D:\>javac SimpleApplet.java
Using appletviewer :
a) Write HTML APPLET tag comments in the source file.
<html>
<body>
<applet code=”GraphicsDemo.class” width=”300” height=”300”>
</applet>
</body>
</html>
b) Compile the applet source code using javac.
D:\>javac SimpleApplet.java
c) Use appletviewer ClassName.class to view the applet.
D :\> appletviewer SimpleApplet.java

DEPARTMENT OF CSE Page 212


Object Oriented Programming 2019

Output:

5.5 COLORS, FONTS, IMAGES


5.5.1 COLOR
Color is encapsulated by the Color class. The Color class defines several constants (for example,
Color.black, Color.red) to specify a number of common colors.
Class : Color
Syntax:
Color obj = new Color(int R,int G,int B);
Color obj = new Color (int RGBVal);
Methods:
setBackground(Color.colorname);
setForeground(Color.colorname);
setColor(Color.Colorname);
Color Constants
● Color.black (or) Color.BLACK
● Color.blue (or) Color.BLUE
● Color.cyan (or) Color.CYAN
● Color.DARK_GRAY (or) Color.darkGray
● Color.gray (or) Color.GRAY
● Color.green (or) Color.GREEN
● Color.LIGHT_GRAY (or) Color.lightGray
● Color.magenta (or) Color.MAGENTA
● Color.orange (or) Color.ORANGE
● Color.pink (or) Color.PINK
● Color.red (or) Color.RED
● Color.white (or) Color.WHITE
● Color.yellow (or) Color.YELLOW
Program:
//colordemo.java
import java.applet.*;
import java.awt.*;
/*
<applet code="colordemo" width=200 height=200>
</applet>
*/

DEPARTMENT OF CSE Page 213


Object Oriented Programming 2019

public class colordemo extends Applet


{
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
}
public void paint(Graphics g)
{
Color col = new Color(255,255,0);
g.setColor(col);
g.drawString("Hello Java",50,50);
}
}
Output
javac colordemo.java
appletviewer colordemo.java

5.5.2. FONTS
The Font class provides a method of specifying and using fonts. The Font class constructor
constructs font objects using the font's name, style (PLAIN, BOLD, ITALIC, or BOLD +
ITALIC), and font size.
Class : Font
Syntax:
Font obj = new Font(fontname,fontstyle,fontsize);
Font Style
Constant Description
Font.BOLD It makes the font style bold.
Font.ITALIC It makes the font style Italic.
Font.PLAIN It makes the font style plain.
Example:
Font obj= new Font("Arial",Font.BOLD,18);
Methods:

DEPARTMENT OF CSE Page 214


Object Oriented Programming 2019

Method Description
setFont() Set the font to string
String getFamily() Returns the family name of this Font.
int getStyle() Returns the style of this Font.
boolean isBold() Indicates whether or not this Font object's style is BOLD
boolean isItalic() Indicates whether or not this Font object's style is ITALIC.
boolean isPlain() Indicates whether or not this Font object's style is PLAIN.
static Font getFont(String nm) Returns a Font object fom the system properties list.
Program:
//fontdemo.java
import java.applet.*;
import java.awt.*;
/*
<APPLET CODE ="fontdemo" WIDTH=300 HEIGHT=200>
</APPLET>
*/
class fontdemo extends Applet
{
public void init()
{
Font f=new Font("Arial",Font.ITALIC,20);
setFont(f);
}
public void paint(Graphics g)
{

g.drawString(“Welcome to java”,4,20);
}
}
Output:

5.5.3 IMAGES

DEPARTMENT OF CSE Page 215


Object Oriented Programming 2019

Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The image can be displayed in applet using drawImage() method of Graphics class.
Class : Image
Syntax:
Image obj = getImage(URL u,String image);
Example:
Image obj = getImage (getDocumentBase(),”myimg.jpg);
Methods:
drawImage()
Program:
// imagedemo.java
/*
<APPLET CODE=JavaExampleImageUseInApplet.class WIDTH=520 HEIGHT=170
></APPLET>
*/
import java.awt.*;
import java.applet.*;
class imagedemo extends Applet
{
public void init()
{
Image img = getImage(getDocumentBase(),"Koala.jpg");
}
public void paint(Graphics gr)
{
gr.drawImage(img,45,15,this);
}
}

Output:

5. 6 EVENT HANDLING

DEPARTMENT OF CSE Page 216


Object Oriented Programming 2019

Event: Change in the state of an object is known as event i.e. event describes the change in state
of source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed when
an event occurs.
Delegation Event Model
Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
● Events : An event is a change in state of an object.
● Events Source : Event source is an object that generates an event.
● Listeners : A listener is an object that listens to the event. A listener gets notified when
an event occurs.
Steps involved in event handling
● The User clicks the button and the event is generated.
● Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
● Event object is forwarded to the method of registered listener class.
● The method is now get executed and returns.

5.6.1 EVENT HANDLERS


Event Classes Description Listener Interface
generated when button is pressed, menu-item is
ActionEvent ActionListener
selected, list-item is double clicked
generated when mouse is dragged,
MouseEvent moved,clicked,pressed or released and also when MouseListener
it enters or exit a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener
generated when value of textarea or textfield is
TextEvent TextListener
changed
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
generated when window is activated, deactivated,
WindowEvent WindowListener
deiconified, iconified, opened or closed
generated when component is hidden, moved,
ComponentEvent ComponentEventListener
resized or set visible
generated when component is added or removed
ContainerEvent ContainerListener
from container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

DEPARTMENT OF CSE Page 217


Object Oriented Programming 2019

generated when component gains or loses


FocusEvent FocusListener
keyboard focus
EVENT LISTENER
A listener is an object that listens to the event. A listener gets notified when an event
occurs. Event listeners are objects that receive notification of an event.
General form of method to register (add) a listener
public void addTypeListener(TypeListener eventlistener)
General form of method to unregister (remove) a listener
public void removeTypeListener(TypeListener eventlistener)
where,
Type is the name of the event
eventlistener is a reference to the event listener
i) ActionListener
This interface defines the method actionPerformed() which is invoked when ActionEvent
occurs.
Methods
void actionPerformed(ActionEvent ae)
ii) AdjustmentListener
This interface defines the method adjustmentValueChanged() which is invoked when
AdjustmentEvent occurs.
Methods
void adjustmentValueChanged(AdjustmentEvent ae)
iii) ComponentListener
This interface deals with the component events.
Methods
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
iv) ContainerListener
This interface deals with the events that can be generated on containers.
Methods
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
v) FocusListener
This interface deals with focus events that can be generated on different components or containers.
Methods
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
vi) ItemListener
This interface deals with the item event.
Methods
void itemStateChanged(ItemEvent ie)
vii) KeyListener
This interface deals with the key events.

DEPARTMENT OF CSE Page 218


Object Oriented Programming 2019

Methods
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
ix) MouseListener
This interface deals with five of the mouse events.
Methods
void mouseClicked(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
x) MouseMotionListener
This interface deals with two of the mouse events.
Methods
void mouseMoved(MouseEvent me)
void mouseDragged(MouseEvent me)
xi) MouseWheelListener
This interface deals with the mouse wheel event.
Methods
void mouseWheelMoved(MouseWheelEvent mwe)
xii) TextListener
This interface deals with the text events.

Methods
void textValueChanged(TextEvent te)
xiii) WindowFocusListener
This interface deals with the window focus events.
Methods
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
xiv) WindowListener
This interface deals with seven of the window events.
Methods
void windowActivated(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowIconified(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowOpened(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
Program:
//AdapterExample.java
import java.awt.*;
import java.awt.event.*;

DEPARTMENT OF CSE Page 219


Object Oriented Programming 2019

import java.applet*;
/*
<APPLET CODE=JavaExampleImageUseInApplet.class WIDTH=520 HEIGHT=170
></APPLET>
*/
class AdapterExample
{
public void init()
{
addMouseListener(new adapter1(this);
addMouseMotionListener(new adapter2(this);
}
}
class adapter1 extends MouseAdpter
{
Test obj;
adapter1(Test obj)
{
this.obj=obj;
}
void mouseClicked(MouseEvent m)
{
Obj.showStatus(“Mouse clicked”);
}
}
class adapter2 extends MouseMotionAdpter
{
Test obj;
Adapter2(Test obj)
{
this.obj=obj;
}
void mouseMoved(MouseEvent m)
{
Obj.showStatus(“Mouse moved”);
}
}
Output:
javac AdapterExample.java
appletviwer AdapterExample.java

DEPARTMENT OF CSE Page 220


Object Oriented Programming 2019

5.6.2ADAPTER CLASSES
An adapter class provides the default implementation of all methods in an event listener
interface. Adapter classes are very useful when you want to process only few of the events that are
handled by a particular event listener interface.
Adapter Class Listener Interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

WindowAdapter
WindowAdapter class implements the WindowListener interface and it contains 7 empty
implementation.
public interface windowListener
{
void windowActivated(WindowEvent we);
void windowDeactivated(WindowEvent we);
void windowIconified(WindowEvent we);
void windowDeiconified(WindowEvent we);
void windowOpened(WindowEvent we);
void windowClosed(WindowEvent we);

DEPARTMENT OF CSE Page 221


Object Oriented Programming 2019

void windowClosing(WindowEvent we);


}
public class WindowAdapter implements windowListener
{
void windowActivated(WindowEvent we){……..}
void windowDeactivated(WindowEvent we) {……..}
void windowIconified(WindowEvent we) {……..}
void windowDeiconified(WindowEvent we) {……..}
void windowOpened(WindowEvent we) {……..}
void windowClosed(WindowEvent we) {……..}
void windowClosing(WindowEvent we) {……..}
}
MouseAdapter
MouseAdapter class implements the MouseListener interface and it contains 5 empty
implementation.
public interface MouseListener
{
void mouseClicked(MouseEvent me);
void mousePressed(MouseEvent me);
void mouseReleased(MouseEvent me);
void mouseEntered(MouseEvent me);
void mouseExited(MouseEvent me);
}
public class WindowAdapter implements windowListener
{
void mouseClicked(MouseEvent me);{……..}
void mousePressed(MouseEvent me){……..}
void mouseReleased (MouseEvent we) {……..}
void mouseEntered (MouseEvent we) {……..}
void mouseExited (WindowEvent we) {……..}
}

Program:
Refer Pageno:

5.6.3 ACTIONS
ActionEvent is generated when button is pressed, menu-item is selected, list-item is double
clicked. It implements ActionListener interface.
ActionListener
This interface defines the method actionPerformed() which is invoked when ActionEvent occurs.
Methods
void actionPerformed(ActionEvent ae)
Program:
// actiondemo.java
/*

DEPARTMENT OF CSE Page 222


Object Oriented Programming 2019

<APPLET CODE=JavaExampleImageUseInApplet.class WIDTH=520 HEIGHT=170 >


</APPLET>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
class actiondemo extends Applet
{
public void init()
{
TextField tf=new TextField();
Button b=new Button("Click Here");
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to Javatpoint.");
}
}
Output:
javac actiondemo.java
appletviwer actiondemo.java

5.6.4 MOUSE EVENTS


Mouse Event is generated when mouse is dragged, moved,clicked,pressed or released and also
when it enters or exit a component. It implements the MouseListener interface.
i) MouseListener
This interface deals with five of the mouse events.
Methods
void mouseClicked(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
ii) MouseMotionListener
This interface deals with two of the mouse events.
Methods
DEPARTMENT OF CSE Page 223
Object Oriented Programming 2019

void mouseMoved(MouseEvent me)


void mouseDragged(MouseEvent me)
iii) MouseWheelListener
This interface deals with the mouse wheel event.
Methods
void mouseWheelMoved(MouseWheelEvent mwe)
Program:
Refer Pageno: 218
5.7 AWT EVENT HIERARCHY

The graphics programming in Java is supported by the AWT package. The AWT stands for
Abstract Window Toolkit.
The AWT is an API which contains a large number of classes which helps to include various
graphical components in the Java program, for creating user interfaces and for painting graphics
and images.
Event: Change in the state of an object is known as event i.e. event describes the change in state
of source. Events are generated as result of user interaction with the graphical user interface
components

Event Classes Description Listener Interface


generated when button is pressed, menu-item is
ActionEvent ActionListener
selected, list-item is double clicked

DEPARTMENT OF CSE Page 224


Object Oriented Programming 2019

generated when mouse is dragged,


MouseEvent moved,clicked,pressed or released and also when MouseListener
it enters or exit a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener
generated when value of textarea or textfield is
TextEvent TextListener
changed
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
generated when window is activated, deactivated,
WindowEvent WindowListener
deiconified, iconified, opened or closed
generated when component is hidden, moved,
ComponentEvent ComponentEventListener
resized or set visible
generated when component is added or removed
ContainerEvent ContainerListener
from container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
generated when component gains or loses
FocusEvent FocusListener
keyboard focus
EVENT LISTENER
A listener is an object that listens to the event. A listener gets notified when an event
occurs. Event listeners are objects that receive notification of an event.
General form of method to register (add) a listener
public void addTypeListener(TypeListener eventlistener)
General form of method to unregister (remove) a listener
public void removeTypeListener(TypeListener eventlistener)
where,
Type is the name of the event
eventlistener is a reference to the event listener
i) ActionListener
This interface defines the method actionPerformed() which is invoked when ActionEvent
occurs.

Methods
void actionPerformed(ActionEvent ae)
ii) AdjustmentListener
This interface defines the method adjustmentValueChanged() which is invoked when
AdjustmentEvent occurs.
Methods
void adjustmentValueChanged(AdjustmentEvent ae)
iii) ComponentListener
This interface deals with the component events.
Methods
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)

DEPARTMENT OF CSE Page 225


Object Oriented Programming 2019

void componentHidden(ComponentEvent ce)


iv) ContainerListener
This interface deals with the events that can be generated on containers.
Methods
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
v) FocusListener
This interface deals with focus events that can be generated on different components or containers.
Methods
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
vi) ItemListener
This interface deals with the item event.

Methods
void itemStateChanged(ItemEvent ie)
vii) KeyListener
This interface deals with the key events.
Methods
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
ix) MouseListener
This interface deals with five of the mouse events.
Methods
void mouseClicked(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
x) MouseMotionListener
This interface deals with two of the mouse events.
Methods
void mouseMoved(MouseEvent me)
void mouseDragged(MouseEvent me)
xi) MouseWheelListener
This interface deals with the mouse wheel event.
Methods
void mouseWheelMoved(MouseWheelEvent mwe)
xii) TextListener
This interface deals with the text events.

Methods
void textValueChanged(TextEvent te)
xiii) WindowFocusListener

DEPARTMENT OF CSE Page 226


Object Oriented Programming 2019

This interface deals with the window focus events.


Methods
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
xiv) WindowListener
This interface deals with seven of the window events.
Methods
void windowActivated(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowIconified(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowOpened(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
Program:
Refer page no:218
5.8 JAVA SWING

Limitation of AWT
1. AWT supports limited number of GUI components.
2. Components of AWT are heavy weight components.
3. AWT occupies more memory space.
4. It is not portable.
5.9 LAYOUT MANAGEMENT
LayoutManagers are used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers. There are nine types of layout
managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout

DEPARTMENT OF CSE Page 227


Object Oriented Programming 2019

4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

i) Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
1. BorderLayout.NORTH
2. BorderLayout. SOUTH
3. BorderLayout.EAST
4. BorderLayout.WEST
5. BorderLayout.CENTER

Synatx:

BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical
gaps between the components.
Program:
import java.awt.*;
import javax.swing.*;
public class BorderDemo
{
BorderDemo()
{
JFrame f =new JFrame();
JButton b1=new JButton("UP");;
JButton b2=new JButton("DOWN");;
JButton b3=new JButton("RIGHT");;
JButton b4=new JButton("LEFT");;
JButton b5=new JButton("MIDDLE");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
DEPARTMENT OF CSE Page 228
Object Oriented Programming 2019

{
BorderDemo b= new BorderDemo();
}
}
Output:

ii) Java GridLayout


The GridLayout is used to arrange the components in rectangular grid. One component is displayed
in each rectangle.

Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns
but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns alongwith given horizontal and vertical gaps.

program

import java.awt.*;
import javax.swing.*;
public class GridDemo
{
GridDmo()
{
Jframe f =new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
f.add(b1);

DEPARTMENT OF CSE Page 229


Object Oriented Programming 2019

f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.setLayout(new GridLayout(2,4));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
GridDemo g= new GridDemo();
}
}
Output:

iii) Java FlowLayout


The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the
default layout of applet or panel.

Fields of FlowLayout class

1. FlowLayout.LEFT
2. FlowLayout.RIGHT
3. FlowLayout.CENTER
4. FlowLayout.LEADING
5. FlowLayout.TRAILING

Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal
and vertical gap.

DEPARTMENT OF CSE Page 230


Object Oriented Programming 2019

2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
Program:
//FrameDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Java AWT Frame”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Label L1=new Label(“WELCOME”);
fr.add(L1);
}
}

Output:
javac FrameDemo.java
java FrameDemo

iv) Java BoxLayout


The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:

Fields of BoxLayout class

1. BoxLayout.X_AXIS

DEPARTMENT OF CSE Page 231


Object Oriented Programming 2019

2. BoxLayout.Y_AXIS
3. BoxLayout.LINE_AXIS
4. BoxLayout.PAGE_AXIS

Constructor of BoxLayout class

BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given
axis.

v) Java CardLayout
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.

Commonly used methods of CardLayout class

● public void next(Container parent): is used to flip to the next card of the given container.
● public void previous(Container parent): is used to flip to the previous card of the given
container.
● public void first(Container parent): is used to flip to the first card of the given container.
● public void last(Container parent): is used to flip to the last card of the given container.
● public void show(Container parent, String name): is used to flip to the specified card
with the given name.
Program:
public class CardDemo extends JFrame implements ActionListener
{
CardDemo()
DEPARTMENT OF CSE Page 232
Object Oriented Programming 2019

{
Container c=getContentPane();
CardLayout card =new CardLayout(40,30);
c.setLayout(card);
JButton b1=new JButton("Rose");
JButton b2=new JButton("Jasmine");
JButton b3=new JButton("Lilly");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);
c.add("b",b2);
c.add("c",b3);
}
public void actionPerformed(ActionEvent e)
{
card.next(c);
}
public static void main(String[] args)
{
CardDemo cl=new CardDemo();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:

DEPARTMENT OF CSE Page 233


Object Oriented Programming 2019

vi) Java GridBagLayout


The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline. The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells.
Each component occupies one or more cells known as its display area. Each component associates
an instance of GridBagConstraints. With the help of constraints object we arrange component's
display area on the grid. The GridBagLayout manages each component's minimum and preferred
sizes in order to determine component's size.
Program:
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
}
GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;

DEPARTMENT OF CSE Page 234


Object Oriented Programming 2019

gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:

vii) GroupLayout
GroupLayout groups its components and places them in a Container hierarchically. The
grouping is done by instances of the Group class. Group is an abstract class and two concrete
classes which implement this Group class are SequentialGroup and ParallelGroup.
SequentialGroup positions its child sequentially one after another where as ParallelGroup aligns
its child on top of each other.
The GroupLayout class provides methods such as createParallelGroup() and
createSequentialGroup() to create groups.
Program:
import java.awt.Container;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.GroupLayout.Alignment.*;
public class GroupE2
{
public static void main(String[] args)
{
JFrame frame = new JFrame("GroupLayoutExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container myPanel = frame.getContentPane();
GroupLayout groupLayout = new GroupLayout(myPanel);
groupLayout.setAutoCreateGaps(true);

DEPARTMENT OF CSE Page 235


Object Oriented Programming 2019

groupLayout.setAutoCreateContainerGaps(true);
myPanel.setLayout(groupLayout);
JButton b1 = new JButton("Button One");
JButton b2 = new JButton("Button Two");
JButton b3 = new JButton("Button Three");
groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(LEADING).addComponent(b1).addComponent(b3
)) .addGroup(groupLayout.createParallelGroup(TRAILING).addComponent(b2)));
groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(b1).addComponent(b
2)).addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(b3)));
frame.pack();
frame.setVisible(true);
}
}

Output:

5.10 SWING COMPONENS:

DEPARTMENT OF CSE Page 236


Object Oriented Programming 2019

5.10.1 TEXT FIELD


It is a slot in which one line can be entered. In the TextField we can enter the string, modify it,
copy, cut or paste it.
Syntax:
JTextField obj=new JTextField(int n);
where n is the total number of characters in the string.
Program:
//TextFieldDemo.java
import java.awt.*;
import java.swing.*;
class TextFieldDemo
{
public static void main(String args[])
{
JFrame f= new Frame("TextField Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JTextField t1=new JTextField("Welcome to Javatpoint.");
JTextField t2=new JTextField("AWT Tutorial");

DEPARTMENT OF CSE Page 237


Object Oriented Programming 2019

f.add(t1);
f.add(t2);
}
}
Output
javac TextFieldDemo.java
java TextFieldDemo

5.10.2 TEXT AREA


The Text Area is used to handle multi-line text.
Syntax
JTextArea area= new JTextArea(int n, int m)
where n is the number of lines and m is the number of characters.

Program:
//TextAreaDemo.java
import java.awt.*;
import java.swing.*;
class TextAreaDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("TextArea Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JTextArea area=new JTextArea("Welcome to javatpoint");
f.add(area);
}
}
Output:
javac TextAreaDemo.java
java TextAreaDemo
DEPARTMENT OF CSE Page 238
Object Oriented Programming 2019

5.10.3 BUTTONS
Buttons are called as push buttons. This component contains a text (or a label) .It generates an
event when that label is pressed.
Syntax:
JButton buttonname = new JButton (label/text);
jButton buttonname[] = new JButton[size];;
Program:
//ButtonDemo.java
import java.awt.*;
import java.swing.*;
class FrameDemo
{
public static void main(String[] args)
{
JFrame fr=new JFrame(“Button Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
JButtton b1 =new JButton(“click Here”);
fr.add(b1);
}
}
Output:

DEPARTMENT OF CSE Page 239


Object Oriented Programming 2019

javac ButtonDemo.java
java ButtonDemo

5.10.4 CHECK BOX:


A checkbox is again a label which is displayed as a pushbutton. This pushbutton can either be
checked or unchecked. Therefore, the state of the checkbox is either true or false.
Syntax
JCheckbox checkboxname = new JCheckbox();
JCheckbox checkboxname = new JCheckbox(String);
Program:
//CheckboxDemo.java
import java.awt.*;
import java.swing.*;
class CheckboxDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("Checkbox Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JCheckbox box1 = new JCheckbox("C++");
JCheckbox box2 = new JCheckbox("Java", true);
f.add(box1);
f.add(box2);
}
}
Output:
javac CheckboxDemo.java
java Checkbox Demo

DEPARTMENT OF CSE Page 240


Object Oriented Programming 2019

5.10. 5 RADIO BUTTON


It allows the user to make one and only selection at atime.
Syntax
JRadioButton name = new JRadioButton(String s);
Program:
// JRadioButtonDemo.java
import java.awt.*;
import java.swing.*;
class JRadioButtonDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("CheckboxGroup Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JRadioButton b1 = new JRadioButton(“C++”,true);
JRadioButton b1 = new JRadioButton(“java”,false);
f.add(b1);
f.add(b2);
}
}
Output:
javac JRadioButtonDemo.java
java JRadioButtonDemo

DEPARTMENT OF CSE Page 241


Object Oriented Programming 2019

5.10.6 SCROLLBARS:
JScrollbar can be represented by the slider widgets. There are two styles of scrollbars . They are,
● Horizontal scrollbar
● Vertical scrollbar.
Syntax:
JScrollbar obj= new Scrollbar(Scrollbar.style);
Program:
//ScrollbarDemo.java
import java.awt.*;
import java.swing.*;
class ScrollbarDemo
{
public static void main(String[] args)
{
JFrame fr=new JFrame(“Scrollbar Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
JScrollbar s=new JScrollbar(Scrollbar.Vertical);
fr.add(s);
}
}

Output:
javac ScrollbarDemo.java
java ScrollbarDemo

DEPARTMENT OF CSE Page 242


Object Oriented Programming 2019

5.10.7 CHOICES:
Choice class is used to show popup menu of choices. Choice selected by user is shown on the top
of the menu.
Syntax
JChoice choicename = new JChoice();
Program:
//ChoiceDemo.java
import java.awt.*;
import java.swing.*;
class ChoiceDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("Choice Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JChoice c=new JChoice();
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
}
}
Output:
javac ChoiceDemo.java.
java ChoiceDemo

DEPARTMENT OF CSE Page 243


Object Oriented Programming 2019

5.10.8 LIST :
List is a collection of many items. By double clicking the desired item we can select it. It is similar
to the Choice component, except it shows multiple items at a time and user is allowed to select
either one or multiple items at a time
Syntax
JList listname =new JList();
Program:
//ListDemo.java
import java.awt.*;
import java.swing.*;
class ListDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("List Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JList L1=new JList(5);
L1.add("Item 1");
L1.add("Item 2");
L1.add("Item 3");
L1.add("Item 4");
L1.add("Item 5");
f.add(L1);
}
}
Output:
javac ListDemo.java.

DEPARTMENT OF CSE Page 244


Object Oriented Programming 2019

java ListDemo

5.10. 9 JWINDOW
The JWindow class is used to create a window which does not have any toolbar, border or window
management buttons. This type of window is usually used to display messages like welcome
messages, Copyright information, etc. Commonly used Constructors:
Constructor Description
JWindow() Creates a window with no specified
owner.
JWindow(Frame owner) Creates a window with the specified
owner frame.
Program:
import java.awt.*;
import javax.swing.*;
public class Message
{
public static void displayMessage(int timeDuration)
{
JWindow msg =new JWindow();
JPanel panel= (JPanel)msg.getContentPane();
int width = 350, height = 150;
int x = 50, y = 50;
msg.setBounds(x, y, width, height);
panel.setBorder(BorderFactory.createLineBorder(Color.red, 5));
msg.setVisible(true);
}
public static void main(String args[])
{
displayMessage(8000);
System.exit(0);
}

DEPARTMENT OF CSE Page 245


Object Oriented Programming 2019

Output:

5.10. 10 JAVA JMENUBAR, JMENU AND JMENUITEM


❖ The JMenuBar class is used to display menubar on the window or frame. It may have
several menus.
❖ The Menu class represents the pull-down menu component which is deployed from a
menu bar.
❖ A JMenu is a container that can hold menu items that represent the options.
❖ The object of JMenu class is a pull down menu component which is displayed from the
menu bar. It inherits the JMenuItem class.
❖ The object of JMenuItem class adds a simple labeled menu item. The items used in a
menu must belong to the JMenuItem or any of its subclass.

Commonly used Constructors in JMenu:

Constructor Description
JMenu() Constructs a new JMenu with no text.
JMenu(Action a) Constructs a menu whose properties are taken from the
Action supplied.
JMenu(String s) Constructs a new JMenu with the supplied string as its
text.
JMenu(String s, boolea Constructs a new JMenu with the supplied string as its
text and specified as a tear-off menu or not.

Constructor in JMenuBar:

Constructor Description
JMenuBar() Creates a new menu bar.

JMenuBar menuBar = new JMenuBar();


.
myFrame.setJMenuBar(menuBar);

The following code creates two JMenu: File and Help, and add them to the JMenuBar:

DEPARTMENT OF CSE Page 246


Object Oriented Programming 2019

JMenu fileMenu = new JMenu("File");

JMenu helpMenu = new JMenu("Help");

menuBar.add(fileMenu);

menuBar.add(helpMenu);
The following code creates menu items to the menu:
JMenuItem newMenuItem = new JMenuItem("New");

JMenuItem openMenuItem = new JMenuItem("Open");

JMenuItem exitMenuItem = new JMenuItem("Exit");

The following code add menu items and a separator to the menu:

fileMenu.add(newMenuItem);

fileMenu.add(openMenuItem);

fileMenu.addSeparator();

fileMenu.add(exitMenuItem);
Program:
import javax.swing.*;
public class MenuExample
{
MenuExample()
{
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
Menu menu=new JMenu("File Menu");
JMenu submenu=new JMenu("Print");
JMenuItem i1=new JMenuItem("New");
JMenuItem i2=new JMenuItem("Open");
JMenuItem i3=new JMenuItem("Save");
JMenuItem i4=new JMenuItem("Save As");
JMenuItem i5=new JMenuItem("Print");
JMenuItem i6=new JMenuItem("Quick Print");
JMenuItem i7=new JMenuItem("Print Preview");
menu.add(i1);
DEPARTMENT OF CSE Page 247
Object Oriented Programming 2019

menu.add(i2);
menu.add(i3);
menu.add(i4);
submenu.add(i5);
submenu.add(i6);
submenu.add(i7);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
MenuExample m= new MenuExample();
}
}
Output:

5.10.11JAVA JDIALOG
❖ The JDialog control represents a top level window with a border and a title used to take
some form of input from the user.
❖ It inherits the Dialog class.

DEPARTMENT OF CSE Page 248


Object Oriented Programming 2019

❖ It doesn't have maximize and minimize buttons


Commonly used Constructors:
Constructor Description
JDialog() It is used to create a modeless dialog without a title and
without a specified Frame owner.
JDialog(Frame owner) It is used to create a modeless dialog with specified Frame
as its owner and an empty title.
JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.

Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("Click Me");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
}
d.add( new JLabel ("Click this button to proceed"));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output:

DEPARTMENT OF CSE Page 249


Object Oriented Programming 2019

PART A (2 Marks with Answers)


1. What is meant by adapter classes?
An adapter class provides the default implementation of all methods in an event listener interface.
Adapter classes are very useful when you want to process only few of the events that are handled
by a particular event listener interface.
Adapter Class Listener Interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
2. Enumerate the features of AWT in java
The graphics programming in Java is supported by the AWT package. The AWT stands for
Abstract Window Toolkit.
The AWT is an API which contains a large number of classes which helps to include various
graphical components in the Java program, for creating user interfaces and for painting graphics
and images.
3. What is the difference between the paint() and repaint() methods?
paint() repaint()
The paint() method is called when some action is Whenever a repaint method is called,
performed on the window. the update method is also called
along with paint() method.
This method supports painting via graphics object. This method is used to cause paint()
to be invoked by the AWT painting
thread.
4. What is the difference between applications and applets?

DEPARTMENT OF CSE Page 250


Object Oriented Programming 2019

5. What is a layout manager and what are different types of layout managers available in
java AWT?
A layout manager is an object that is used to organize components in a container. The different
layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and
GridBagLayout.

6. What is an event and what are the models available for event handling?
An event is an event object that describes a state of change in a source. In other words, event occurs
when an action is generated, like pressing button, clicking mouse, selecting a list.
There are two types of models for handling events and they are:
a) event-inheritance model and
b) event-delegation model

7. What is the lifecycle of an applet?


init() method - Can be called when an applet is first loaded
start() method - Can be called each time an applet is started.
paint() method - Can be called when the applet is minimized or maximized.
stop() method - Can be used when the browser moves off the applet’s page.
destroy() method - Can be called when the browser is finished with the applet.

DEPARTMENT OF CSE Page 251


Object Oriented Programming 2019

8. What class is the top of the AWT event hierarchy?


The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
9. Write a note on Borderlayout?
The BorderLayout class implements a common layout style for top-level windows. It has four
narrow, fixed-width components at the edges and one large area in the center. The four sides are
referred to as north, south, east, and west. The middles area is called the center. Here are the
constructors defined by BorderLayout
BorderLayout( )
BorderLayout(int horz, int vert)
10. Distinguish between component and container
Java's Component class represents visual elements of a Graphical User Interface. Its subclasses
include Button, Checkbox, TextField, Choice, and Canvas. The Container class is another subclass
of Component. A Container is a component that can contain other components (including other
containers). This is the essential difference between containers and other types of component.
Subclasses of Container include Frame, Panel, and Applet.

11. What is the difference between jcheckbox and jradiobutton?


In a checkbox group, a user can select more than one option. Each checkbox operates individually,
so a user can toggle each response "on" and "off."
Radio buttons, however, operate as a group and provide mutually exclusive selection values. A
user can select only one option in a radio button group.
12. What is the difference between a Choice and a List?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available
choices. Only one item may be selected from a Choice. A List may be displayed in such a way that
several List items are visible. A List supports the selection of one or more List items
13. What is the use of JList?
JList is a Swing component with which we can display a list of elements. This component also
allows the user to select one or more elements visually.
14. What is meant by controls and what are different types of controls in AWT?
Controls are components that allow a user to interact with your application and the AWT supports
the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists,
Scrollbars, and Text Components. These controls are subclasses of Component.
15. What is the difference between scrollbar and scrollpane?
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its
own events and perform its own scrolling.
16. Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
17. What are the differences between AWT and Swing?

DEPARTMENT OF CSE Page 252


Object Oriented Programming 2019

18. What is the use of WindowListener?


WindowListener interface is implemented in class to handle following activities
❖ Opening a window - Showing a window for the first time
❖ Closing a window - Removing the window from the screen.
❖ Iconifying a window - Reducing the window to an icon on the desktop.
❖ Deiconifying a window - Restoring the window to its original size.
❖ Focused window - The window which contains the "focus owner".
❖ Activated window (frame or dialog) - This window is either the focused window, or
owns the focused window.
❖ Deactivated window - This window has lost the focus. For more information about
focus, see the AWT Focus Subsystem specification.
❖ Maximizing the window - Increasing a window's size to the maximum allowable size,
either in the vertical direction, the horizontal direction, or both directions.
19. How are the elements of different layouts organized?
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East
and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a
grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However,
the elements are of different size and may occupy more than one row or column of the grid. In
addition, the rows and columns may have different sizes. The default Layout Manager of Panel
and Panel sub classes is FlowLayout.
20. What is source and listener?
source : A source is an object that generates an event. This occurs when the internal state of that
object changes in some way.
listener : A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive notifications

DEPARTMENT OF CSE Page 253


Object Oriented Programming 2019

about specific types of events. Second, it must implement methods to receive and process these
notifications.

PART B (Possible questions)


1. State and explain the AWT event handling (13)
2. Describe in detail about different layout in java GUI. Which layout is the default one? (13)
3. i) What is layout management? What is the function of Layout manager? (7)
ii. What is the process of setting the layout manager(6)
4. List the methods available to draw shapes and COLOR (13)
5. i. Clasify the classes under 2D shapes (7)
ii. Explain the Swing components in detail(6)
6. i. Describe the AWT event hierarchy(6)
ii. Discuss the adapter classes using example(7)
7. i. Illustrate what is layout management? State the various types of layout supported by Java?
Which layout is default one? (7)
ii. Examine the basic of event handling. (6)
8. i. Discuss how an application can respond to events in Java? Write the steps and the example.
ii.Discuss the adapter class using example (7)
9. Evaluate with an example program and discuss in detail about Mouse listener and Mouse Motion
Listener (13)
10. i.Formulate the methods available in graphics for COLOR. (7)
ii.Design the methods available to draw shapes (6)

DEPARTMENT OF CSE Page 254


Object Oriented Programming 2019

PART C (Possible questions)

1. Code a java program to implement the following: create four check boxes. The initial state of first box
should be in checked state. The status of each checkbox should be displayed. When we change the state of
a checkbox, the status should be displayed.
2. Recommend a Java swing with one button and adding it on the JFrame object inside the main() method.
3. i.Write a program to use setBounds() method.(8)
ii. Create a program use of BorderLayout (7)
4. Which method do you use to enable and disable components such as JButtons? What class is it defined
in? (15)
5. Write a program for a simple calculator using swing (15)
6. i. Infer JList and JComboBox with an example(7)
ii. Compare check boxes and radio buttons with an example(6)

DEPARTMENT OF CSE Page 255


Object Oriented Programming 2019

ADDITIONAL PROGRAMS
1.write a java program to create arithmetic calculator.
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
float a, b, res;
char choice, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("1. Addition\n");
System.out.print("2. Subtraction\n");
System.out.print("3. Multiplication\n");
System.out.print("4. Division\n");
System.out.print("5. Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(choice)
{
case '1' :
System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' :

DEPARTMENT OF CSE Page 256


Object Oriented Programming 2019

System.out.print("Enter Two Number : ");


a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' :
System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' :
System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' :
System.exit(0);
break;
default :
System.out.print("Wrong Choice!!!");
break;
}
System.out.print("\n---------------------------------------\n");
}while(choice != 5);
}
}
Output

DEPARTMENT OF CSE Page 257


Object Oriented Programming 2019

2.write a java program to create a calculator using AWT.


import java.awt.*;
import java.awt.event.*;
public class calculator implements ActionListener
{
int c,n;
String s1,s2,s3,s4,s5;
Frame f;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextField tf;
GridLayout g;
calculator()
{

DEPARTMENT OF CSE Page 258


Object Oriented Programming 2019

f = new Frame("My calculator");


p = new Panel();
f.setLayout(new FlowLayout());
b1 = new Button("0");
b1.addActionListener(this);
b2 = new Button("1");
b2.addActionListener(this);
b3 = new Button("2");
b3.addActionListener(this);
b4 = new Button("3");
b4.addActionListener(this);
b5 = new Button("4");
b5.addActionListener(this);
b6 = new Button("5");
b6.addActionListener(this);
b7 = new Button("6");
b7.addActionListener(this);
b8 = new Button("7");
b8.addActionListener(this);
b9 = new Button("8");
b9.addActionListener(this);
b10 = new Button("9");
b10.addActionListener(this);
b11 = new Button("+");
b11.addActionListener(this);
b12 = new Button("-");
b12.addActionListener(this);
b13 = new Button("*");
b13.addActionListener(this);
b14 = new Button("/");
b14.addActionListener(this);
b15 = new Button("%");
b15.addActionListener(this);
b16 = new Button("=");
b16.addActionListener(this);
b17 = new Button("C");
b17.addActionListener(this);
tf = new TextField(20);
f.add(tf);
g = new GridLayout(4,4,10,20);
p.setLayout(g);
p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);
p.add(b6);p.add(b7);p.add(b8);p.add(b9);
p.add(b10);p.add(b11);p.add(b12);p.add(b13);
p.add(b14);p.add(b15);p.add(b16);p.add(b17);

DEPARTMENT OF CSE Page 259


Object Oriented Programming 2019

f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;

DEPARTMENT OF CSE Page 260


Object Oriented Programming 2019

tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");
c=1;
}
if(e.getSource()==b12)
{
s1 = tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 = tf.getText();

DEPARTMENT OF CSE Page 261


Object Oriented Programming 2019

tf.setText("");
c=3;
}
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;
}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}

DEPARTMENT OF CSE Page 262


Object Oriented Programming 2019

else
tf.setText("infinite");
}
catch(Exception i){}
}
if(c==5)
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}
public static void main(String[] abc)
{
calculator v = new calculator();
}
}
Output:
C:>javac calculator.java
C:>java calculator

3. Java program for handling keyboard events.


import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg=””;
public void init()

DEPARTMENT OF CSE Page 263


Object Oriented Programming 2019

{
addKeyListener(this); //use keyListener to monitor key events
}
public void keyPressed(KeyEvent k) // invoked when any key is pressed down
{
showStatus(“KeyPressed”);
}
public void keyReleased(KeyEvent k)
{
showStatus(“KeyRealesed”);
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
Test1.html
<html>
<body>
<applet code=”Test.class” width=”400” height=”300”>
</applet>
</body>
</html>
Sample Output:

DEPARTMENT OF CSE Page 264


Object Oriented Programming 2019

B.E/B.TECH DEGREE EXAMINATION NOV/DEC 2018


COMPUTER SCIECE ENGINEERING
CS 8392 OBJECT ORIENTED PROGRAMMING
Time: Three hours Max Marks :100
Part A (10*2=20 Marks)
1. Define object and classes in java
2. What is meant by access specifier?
3. What is object cloning?

DEPARTMENT OF CSE Page 265


Object Oriented Programming 2019

4. What is class hierarchy? Give example.


5. Define runtime exceptions
6. What is the use of assert keyword?
7. What is multithreading?
8. What is the need for generic code?
9. What is meant by adapter classes?
10. Enumerate the features of AWT in java

PART B(5*13= 65 Marks)


11. a. i) Explain the characteristics of OOPs ( 6)
ii) Explain the features and characteristic of java (7)
(OR)
b. i) What is a method? How it is defined? Give example. (6)
ii) State the purpose of finalize method in java? With an example how finalize method be used in java
program (7)
12. a. i) Define inheritance. With diagrammatic illustration and java programs illustrate the types of
inheritance with an example
(OR)
ii) Write the java program to create a student examination database system that provide the mark sheet of
students. Input student name,marks in 6 subjects. This mark should be between 0 and 100.
If average is >=80 then prints Grade A
If the average is <80 and >=60 then prints Grade B
If the average is <60 and >=40 then prints Grade C
Else print Grade D (13)
13. a) Explain the different types of exceptrion and exception hierarchy in java with the examples. (13)
(OR)
b) What are the input and output streams? Explain them with illustrations (13)
14. a) Explain in detail different states of thread (13)
(OR)
b) Explain in detail about inter thread communication and suspending, resuming and stopping threads
(13)
15. a) State and explain the AWT event handling (13)
(OR)
b) Describe in detail about different layout in java GUI. Which layout is the default one? (13)

PART C(1*15= 15 Marks)


16. a. Create the database application program to illustrate the use of multithreads
(OR)
b. Code a java program to implement the following: create four check boxes. The initial state of first box
should be in checked state. The status of each checkbox should be displayed. When we change the state of
a checkbox, the status should be displayed.

B.E/B.TECH DEGREE EXAMINATION


COMPUTER SCIECE ENGINEERING
CS 8392 OBJECT ORIENTED PROGRAMMING
MODEL QUESTION PAPER-I
Time: Three hours Max Marks :100
Part A (10*2=20 Marks)
1. Define JVM and byte code.

DEPARTMENT OF CSE Page 266


Object Oriented Programming 2019

2. What is a package? List its usage.


3. What is the use of super keyword?
4. Distinguish between class and interface.
5. What are exceptions? List types
6. What is meant by streams? List types.
7. What are the states of thread?
8. What is generic class and generic program?
9. Distinguish between swing and AWT
10. What is meant by layout? List the types of layout

PART B(5*13= 65 Marks)


11. a. Explain about packages. Give an example program which uses packages. (13)
(OR)
b. i) Describe the structure of Java program. (6)
ii) Write a Java program to sort set of names stored in an array in alphabetical order. (7)
12. a. i) Explain in detail about abstract class and methods
(OR)
ii) How the interface is declared and implemented in java? Explain. (13)
13. a) Discuss in detail about exception handling. (13)
(OR)
b) Write notes on reading from file and writing to the file (13)
14. a) Explain in detail thread priorities, Daemon thread (13)
(OR)
b) Explain in detail about thread synchronization (13)
15. a) State and explain the AWT event handling (13)
(OR)
b) Describe in detail about different swing components (13)

PART C(1*15= 15 Marks)


16. a.Develop a program to perform string operations using ArrayList.Write functions for the following
Append - add at end
Insert – add at particular index
Search
List all string starts with given letter ‘a’

(OR)
b. Evaluate a Java program to find a smallest number in the given array by creating one dimensional
array and two dimensional array using new operator.

B.E/B.TECH DEGREE EXAMINATION


COMPUTER SCIECE ENGINEERING
CS 8392 OBJECT ORIENTED PROGRAMMING
MODEL QUESTION PAPER-II
Time: Three hours Max Marks :100
Part A (10*2=20 Marks)
DEPARTMENT OF CSE Page 267
Object Oriented Programming 2019

1. Define encapsulation and abstraction.


2. List out the operator in java
3. What is interface? Give example
4. Define inheritance. List types
5. What is meant by exception handling?
6. List any four character and byte stream classes
7. Give advantages of generic programming
8. What is meant by thread synchronization?
9. List the components of AWT and Swing
10. Enumerate the features of event handling

PART B(5*13= 65 Marks)


11. a. Explain about packages. Give an example program which uses packages. (13)
(OR)
b. Explain the arrays and its types in detail with example program (13)
12. a. Write the notes on string handling, array list, object cloning (13)
(OR)
b. Write the java program to implement super class is inherited from sub class. Explain. (13)
13. a Explain in detail about how exception is thrown and catched with suitable examples (13)
(OR)
bExplain the following illustrations
Reading from console
Writing to console (13)
14. a) Explain in detail about generic class and generic method (13)
(OR)
b) Explain in detail about multithread programming (13)
15. a) State and explain the 2-D shapes in java (13)
(OR)
b) Describe in detail about mouse events with suitable programs (13)

PART C(1*15= 15 Marks)


16.a. Develop a Java Program to create an abstract class named Shape that contains two integers and an
empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that
each one of the classes extends the class Shape. Each one of the classes contains only the method print
Area () that prints the area of the given shape.

(OR)
b. Develop a Java program to implement the following Create four check boxes. The initial state of the
first box should be in checked state. The status of each check box should be displayed. When we change
the state of a check box, the status should be displayed and updated

DEPARTMENT OF CSE Page 268

You might also like