0% found this document useful (0 votes)
18 views133 pages

Unit-All-Oops Using Java1

The document is a syllabus for a course on Object Oriented Programming using Java, covering five units that include OOP concepts, Java programming basics, classes and objects, inheritance, polymorphism, exception handling, multithreading, and GUI programming with Swing. It outlines key principles such as encapsulation, inheritance, and polymorphism, and provides an overview of Java's environment, data types, and the Java Virtual Machine. The syllabus is intended for students at Krishnaveni Degree College, Narasaraopet.
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)
18 views133 pages

Unit-All-Oops Using Java1

The document is a syllabus for a course on Object Oriented Programming using Java, covering five units that include OOP concepts, Java programming basics, classes and objects, inheritance, polymorphism, exception handling, multithreading, and GUI programming with Swing. It outlines key principles such as encapsulation, inheritance, and polymorphism, and provides an overview of Java's environment, data types, and the Java Virtual Machine. The syllabus is intended for students at Krishnaveni Degree College, Narasaraopet.
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/ 133

Object Oriented Programming using Java ALL UNITS

Object Oriented Programming


using Java
Material Book

Name : ______________________________

RollNo: ______________________________

Group: ______________________________

Section: _____________________________

Year : ________________________________

Krishnaveni Degree College: Narasaraopet Page No.: 1


Object Oriented Programming using Java SYLLABUS

UNIT-I
OOPs Concepts and Java Programming: Introduction to Object-Oriented
concepts, procedural and object-oriented programming paradigm
Java programming: An Overview of Java, Java Environment, Data types,
Variables, constants, scope and life time of variables, operators, type conversion
and casting, Accepting Input from the Keyboard, Reading Input with
Java.util.Scanner Class, Displaying Output with System.out.printf(), Displaying
Formatted Output with String.format(), Control Statements
UNIT-II
Arrays, Command Line Arguments, Strings-String Class Methods
Classes & Objects: Creating Classes, declaring objects, Methods, parameter
passing, static fields and methods, Constructors, and ‘this’ keyword, overloading
methods and access
Inheritance: Inheritance hierarchies, super and subclasses, member access rules,
‘super’ keyword, preventing inheritance: final classes and methods, the object
class and its methods; Polymorphism: Dynamic binding, method overriding,
abstract classes and methods;
UNIT-III
Interface: Interfaces VS Abstract classes, defining an interface, implement
interfaces, accessing implementations through interface references, extending
interface;
Packages: Defining, creating and accessing a package, understanding
CLASSPATH, importing packages.
Exception Handling: Benefits of exception handling, the classification of
exceptions, exception hierarchy, checked exceptions and unchecked exceptions,
usage of try, catch, throw, throws and finally, rethrowing exceptions, exception
specification, built in exceptions, creating own exception sub classes.
UNIT-IV
Multithreading: Differences between multiple processes and multiple threads,
thread states, thread life cycle, creating threads, interrupting threads, thread
priorities, synchronizing threads, inter thread communication.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character
streams, Reading console Input and Writing Console Output, File class, Reading
and writing Files, The Console class, Serialization
UNIT-V
GUI Programming with Swing- Introduction, MVC architecture, components,
containers. Understanding Layout Managers - Flow Layout, Border Layout, Grid
Layout, Card Layout, Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources, Event
Listeners, Event classes, Handling mouse and keyboard events, Adapter classes,
Inner classes, Anonymous Inner classes.

Krishnaveni Degree College: Narasaraopet Page No.: 2


Object Oriented Programming using Java UNIT - I

OOPs Concepts and Java Programming: Introduction to Object-


Oriented concepts, procedural and object-oriented programming
paradigm
Java programming: An Overview of Java, Java Environment, Data types,
Variables, constants, scope and life time of variables, operators, type
conversion and casting, Accepting Input from the Keyboard, Reading
Input with Java.util.Scanner Class, Displaying Output with
System.out.printf(), Displaying Formatted Output with String.format(),
Control Statements

Introduction to Object-Oriented concepts: All computer programs consist


of two elements i.e. code and data. A program can be conceptually organized
around its code or around its data. Depending on the organization the high
level language programming is divided into two new programming
paradigms. They are
1. Procedure Oriented Programming
2. Object Oriented Programming
Procedure Oriented Programming: In Procedure Oriented Programming,
program is organized around code. In this method programs are written
around “what is happening”. This approach characterizes a program as a
series of linear steps (that is, code). Procedural languages such as C employ
this model. In Procedure Oriented Programming complex programs are
recursively subdivided into functions until each function is easy to develop.
One function can call another function.

Disadvantages:
Krishnaveni Degree College: Narasaraopet Page No.: 3
Object Oriented Programming using Java UNIT - I

1. In procedure oriented programming more importance is given for


the development of functions, very little attention is given to data.
So procedure oriented programming is code acting on data.
2. In a multi-function program, many important data items are placed
as global so that they can be accessed by all the functions. If one of
the functions misuses the data it is affected by all the functions. Thus
data security is not provided.
3. In a large program it is very difficult to identify what data is used by
which function. So when structure of data is modified we have to
search for all the functions which uses that data and revise the
functions accordingly.
4. Another serious drawback with the procedure oriented
programming is it doesn’t model real world problems very well.
Object Oriented Programming: In Object Oriented Programming, program
is organized around data. In this method programs are written around
“who is being affected”. This approach characterizes a program as data
controlling access to code. Object Oriented languages such as Java
employ this model.

Advantages:
1. Object Oriented Programming allows the reusability of the code.
2. Object Oriented Programming allows the programmer to build
secure programs.

Principles of Object Oriented Languages: All object-oriented


programming languages provide three principles that help to implement
the object-oriented model. They are encapsulation, inheritance, and
polymorphism.
Encapsulation: Encapsulation is the mechanism that binds code and the

Krishnaveni Degree College :: Narasaraopet Page No. : 4


Object Oriented Programming using Java UNIT - I

data together and keeps both data and code safe from outside
interference and misuse. In an object-oriented language, code and data
may be combined as a self-contained "black box". In Java, the basis of
encapsulation is the class. A class defines the structure and behavior (data
and code) that will be shared by a set of objects.

Encapsulation: public methods used to protect private data

Within an object, code, data, or both may be private to that object


or public. Private code or data is known to and accessible only by another
part of the object. That is, private code or data may not be accessed by a
piece of the program that exists outside the object. When code or data is
public, other parts of the program may access it even though it is defined
within an object. Typically, the public parts of an object are used to provide
a controlled interface to the private elements of the object.
Polymorphism: Object-oriented programming languages support
polymorphism, which is characterized by the phrase "one interface, multiple
methods." In simple terms, we can have many methods with the same
name but the number of arguments or type of arguments may differ. For
example, you might have a program that defines three different types of area
methods. One area(int r) is used for calculating area of a circle, and another
area(int l, int b) is used for calculating area of a rectangle and another area

Krishnaveni Degree College :: Narasaraopet Page No. : 5


Object Oriented Programming using Java UNIT - I

(int a, int b, int c ) is used for calculating area of a triangle. Because of


polymorphism, the same area method can be with different arguments to
calculate the area of different objects. The compiler will automatically select
the right function based upon the data being passed to the method.

Polymorphism helps to reduce complexity by allowing the same interface to


be used to access a general class of actions. It is the compiler's job to select
the specific action (i.e., method) as it applies to each situation.
Inheritance: - Inheritance is one of the features of Object-Oriented
Programming (OOPs). It is a process which allows one class to acquire
properties (i.e. methods and attributes ) of another class. In other words, the
derived class inherits the attributes and methods from the base class. The
derived class is also called as subclass and the base class is also known
as super-class. The derived class can add its own additional attributes and
methods. These additional attributes and methods differentiates the derived

Krishnaveni Degree College :: Narasaraopet Page No. : 6


Object Oriented Programming using Java UNIT - I

class from the base class.

Figure : Inheritance
A super-class can have any number of subclasses. But a subclass can have
only one superclass. This is because Java does not support multiple
inheritance. The superclass and subclass have “is-a” relationship between
them.

An Overview of Java: JAVA is a general purpose object-oriented


programming language developed by James Gosling at Sun Microsystems in
1991. It was initially designed for the development of software for consumer
electronic devices like TVs, VCRs, etc. It took 18 months to develop the first
working version. This language was initially called “Oak” but it was renamed
as “JAVA” in 1995. Between 1991 and 1995, many more people contributed
to the design and evolution of the language.
The primary motivation for JAVA was not the internet, rather than the
need for platform independent (i.e. Architecture neutral) language that could
be used to create software to be embedded in various consumer electronic
devices, such as microwave ovens and remote controls. The trouble with C
and C++ (and most other languages) is that they are designed to be
compiled for a specific target. Although it is possible to compile a C++
program for just about any type of CPU, to do so requires a full C++ compiler

Krishnaveni Degree College :: Narasaraopet Page No. : 7


Object Oriented Programming using Java UNIT - I

targeted for that CPU. The problem is that compilers are expensive and time-
consuming to create. An easier and cost-efficient solution was needed. In an
attempt to find such a solution, Gosling and others began work on a portable,
platform independent language that could be used produce code that would
run on a variety of CPUs under differing environments. This effort ultimately
led to the creation of JAVA.

Java Environment: Java Environment known as Java Run-time Environment


(JRE) is the part of the Java Development Kit (JDK). It is a freely available
software distribution which has Java Class Library, specific tools, and a stand-
alone JVM. It is the most common environment available on devices to run
java programs. The source Java code gets compiled and converted to Java
bytecode. If you wish to run this bytecode on any platform, you require JRE.
The JRE loads classes, verify access to memory, and retrieves the system
resources. JRE acts as a layer on the top of the operating system.

Java Virtual Machine: Java solves both the security and the portability
problems by making the output of a Java compiler as bytecode which is not
an executable code. Bytecode is a highly optimized set of instructions
designed to be executed by the Java run-time system, which is called the Java
Virtual Machine (JVM). The original JVM was designed as an interpreter for
bytecode.

Krishnaveni Degree College :: Narasaraopet Page No. : 8


Object Oriented Programming using Java UNIT - I

Translating a Java program into bytecode makes it much


easier to run a program in a wide variety of environments because only the
JVM needs to be implemented for each platform. Once the run-time package
exists for a given system, any Java program can run on it. The JVM will differ
from platform to platform but all of them understand the same Java
bytecode.
Java was initially designed as an interpreted language. Later it provided a
Just-In-Time (JIT) compiler for bytecode. When a JIT compiler is part of the
JVM, selected portions of bytecode are compiled into executable code in real
time, on a piece-by-piece, demand basis.
Furthermore, not all sequences of bytecode are compiled but only those
that will benefit from compilation are compiled. The remaining code is simply
interpreted. Thus the just-in-time approach yields a significant performance
boost, the portability and safety features still apply to dynamic compilation.
Class Library : The Java Class Library (JCL) is a set of dynamically loadable
libraries that Java Virtual Machine (JVM) languages can call at run time.
Development tools: The JRE contains development tools such as user
interface toolkits that can be used to improve the quality of the applications.
Examples:
Swing: Swing is a lightweight graphical user interface (GUI) that offers
flexible, user-friendly customizations.
Abstract Window Toolkit: Abstract Window Toolkit (AWT) is a GUI that can
be used to create UI objects such as buttons, windows, and scroll bars.

Internal Architecture of JVM: JVM performs the operations such as Loading


the code, Verification of code, and provides runtime environment to execute
java programs. The internal architecture of JVM is shown in Figure .

Krishnaveni Degree College :: Narasaraopet Page No. : 9


Object Oriented Programming using Java UNIT - I

It contains classloader, memory area, execution engine etc.


Classloader: Classloader is a subsystem of JVM that is used to find and load
class files.
Memory area: The Java Virtual Machine defines various run-time data areas
that are used during execution of a program. Some of these data areas are
 Class Area: Class Area is a part of JVM that contains the information of
classes loaded by class loader. It contains the static variable, method
body etc.
 Heap: Heap is a part of JVM that contains object. When a new object is
created, memory is allocated to the object from the heap and object is
no longer referenced memory is reclaimed by garbage collector.
 Stack: Stack is a part of JVM that holds local variables and partial results,
and plays a part in method invocation and return.
 Program Counter Register: PC Register is a part of JVM which contains
the address of the Java virtual machine instruction currently being
executed.
 Native Method Stack: As java program can call native methods (A
method written in other language like c). Native method stack contains
these native methods.
Execution Engine: It contains:
 A virtual processor
 An Interpreter which reads bytecode stream and then execute the
instructions.
 A Just-In-Time(JIT) compiler which is used to improve the
performance. JIT compiles parts of the byte code that have similar
functionality at the same time, and hence reduces the amount of time
needed for compilation.

Data Types: Every variable in java has a data type. Data types specify the size
and type of value that can be stored in a variable. Java language is rich in its
data types and there are two types of data types. They are
1. Primitive data types
2. Non-primitive data types
The classification of data types in java are shown in figure below.

Krishnaveni Degree College :: Narasaraopet Page No. : 10


Object Oriented Programming using Java UNIT - I

Figure: Data Types in Java


Primitive Data Types: The primitive data types are also commonly referred to
as simple data types. Primitive data types are classified into two types. They
are
1. Numeric data types
2. Non-numeric data types
Numeric data types: In Java, six of the eight primitive data types are numeric
types. Numeric data types are classified into two types. They are
1. Integer data types
2. Floating point data types
Integer data types: Integer data types are used to store whole numbers that
have no fractional part. Integer data types are classified into four types. They
are
1. byte
2. short
3. int
4. long
byte: byte data type is an 8-bit signed integer number. The negative numbers
are expressed in two‘s complement form. The range accepted by byte is -128

Krishnaveni Degree College :: Narasaraopet Page No. : 11


Object Oriented Programming using Java UNIT - I

to127 i.e. -27 to 27-1. Default value stored in byte variable is 0. byte data type
is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an integer.
Ex: byte a = 100, byte b = -50
short: short data type is a 16-bit signed integer number. The negative
numbers are expressed in two‘s complement form. The range accepted by
byte is -32,768 to 32,767 i.e. -215 to 215 -1. Default value stored in short
variable is 0.
Ex: short s = 10000, short r = -20000
int: int data type is a 32-bit signed integer number. The negative numbers
are expressed in two‘s complement form. The range accepted by int is-
2,147,483,648 to 2,147,483,647 i.e. -231 to 231-1. int is generally used as the
default data type for integer values unless there is a concern about memory.
Default value stored in int variable is 0.
Ex: int a = 100000, int b = -200000
Long: Long data type is a 64-bit signed integer number. The negative
numbers are expressed in two‘s complement form. The range accepted by
long is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 i.e. -263 to
263 -1. This type is used when a wider range than int is needed. Default value
stored in long variable is 0.
Ex: long a = 100000L, long b = -200000L
Floating point data types: Floating point data types are used to store numbers
that have a fractional part. Floating point data types are classified into two
types. They are
1. float
2. double
float: float data type is a single-precision 32-bit floating point number. float
is mainly used to save memory in large arrays of floating point numbers.
Default value stored in float variable is 0.0
Ex: float f1 = 234.5f
double: double data type is a double-precision 64-bit floating point number.
This data type is generally used as the default data type for fractional
numbers. Default value stored in double variable is 0.0
Ex: double d1 = 123.4

Krishnaveni Degree College :: Narasaraopet Page No. : 12


Object Oriented Programming using Java UNIT - I

Non-Numeric data types: In Java, two of the eight primitive data types are
non-numeric types. Non-Numeric data types are classified into two types.
They are
1. char data types
2. boolean data types
char: char data type is a single 16-bit Unicode character. The range accepted
by char is 0 to 65,535 i.e. 0 to 216-1. Char data type is used to store any
character.
Ex: char letterA = 'A'
boolean: boolean data type represents one bit of information. There are only
two possible values i.e. true and false. This data type is used for simple flags
that track true/false conditions. Default value is false
Ex: boolean found = true
Non-Primitive Data Types: The non-primitive data types are also commonly
referred as derived data types. Non-Primitive data types are classified into
three types. They are
1. Classes
2. Arrays
3. Interfaces
Classes: Class is an encapsulation of data along with its method. It is a user
defined data type. It acts as an template for creating objects.
Arrays: An array is a group of similar data items referred to by a common
name.
Interfaces: Interfaces are syntactically similar to classes, but they lack in
instance variables, and their methods are declared without any body.

Variables: The variable is the basic unit of storage in a Java program. A


variable is defined by the combination of an identifier, a type, and an optional
initializer. In addition, all variables have a scope, which defines their visibility,
and a lifetime.
Declaring a Variable: In Java, all variables must be declared before they can
be used. The basic form of a variable declaration is shown below
Syntax:
type identifier [ = value ][, identifier [= value ] …];

Krishnaveni Degree College :: Narasaraopet Page No. : 13


Object Oriented Programming using Java UNIT - I

Here, type is one of Java’s atomic types, or the name of a class or interface.
The identifier is the name of the variable. The variable can be initialized by
specifying an equal sign and a value.
Examples
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.

Constants: Constants in Java are called Literals. Literal can be any number,
text, or other information that represents a value. Depending on the value
the literals are classified into 4 types. They are
1. Integer Literal
2. Floating-Point Literals
3. Boolean Literal
4. Character Literals
5. String Literals
Integer Literals: Any whole number is an integer literal. Examples are 1, 2, 3,
and 42. These are all decimal values, meaning they are describing a base 10
number. There are two other bases which can be used in integer literals, octal
(base eight) and hexadecimal (base 16). Octal values are denoted in Java by
a leading zero. Normal decimal numbers cannot have a leading zero. Thus,
the valid value 09 will produce an error from the compiler, since 9 is outside
of octal‘s 0 to 7 range. A more common base for numbers used by
programmers is hexadecimal. A hexadecimal constant with a leading zero-x,
(0x or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a
through f ) are substituted for 10 through 15.
Floating-Point Literals: Floating-point numbers represent decimal values with
a fractional component. They can be expressed in either standard or scientific
notation. Standard notation consists of a whole number component followed
by a decimal point followed by a fractional component. For example, 2.0,
3.14159, and 0.6667 represent valid standard-notation floating-point
numbers. Scientific notation uses a standard-notation, floating-point
number plus a suffix that specifies a power of 10 by which the number is to
be multiplied. The exponent is indicated by an E or e followed by a decimal
number, which can be positive or negative. Examples include 6.022E23,
314159E–05, and 2e+100. Floating-point literals in Java default to double
precision. To specify a float literal, an F or f must be append to the constant.

Krishnaveni Degree College :: Narasaraopet Page No. : 14


Object Oriented Programming using Java UNIT - I

Boolean Literals: Boolean literals are simple. There are only two logical values
that a boolean value can have, true and false. The values of true and false do
not convert into any numerical representation. The true literal in Java does
not equal 1, nor does the false literal equal 0. In Java, they can only be
assigned to variables declared as boolean, or used in expressions with
Boolean operators.
Character Literals: Characters in Java use the Unicode character set. They are
16-bit values that can be converted into integers and manipulated with the
integer operators, such as the addition and subtraction operators. A literal
character is represented inside a pair of single quotes. Ex: ‘a‘, ‘z‘, and ‘@‘.
String Literals: String literals in Java are a sequence of characters enclosed
between a pair of double quotes. Ex: “Hello World”.

Scope and life time of variables: Java allows variables to be declared within
any block. A block is begun with an opening curly brace and ended by a
closing curly brace. A block defines a scope. Thus, each time you start a new
block, you are creating a new scope. A scope determines what objects are
visible to other parts of the program. It also determines the lifetime of those
objects.
Scopes can be nested. In a nested scope, the outer scope encloses the
inner scope. This means that objects declared in the outer scope will be
visible to code within the inner scope. However, the reverse is not true.
Objects declared within the inner scope will not be visible outside it.
// Demonstrate block scope.
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
System.out.println("x and y: " + x + " " + y); // x and y both known
x = y * 2;
}

Krishnaveni Degree College :: Narasaraopet Page No. : 15


Object Oriented Programming using Java UNIT - I

// y = 100; // Error! y not known here


System.out.println("x is " + x); // x is still known here.
}
}

Operators: An operator is a symbol that tells the computer to perform


certain mathematical operations.
Classification of operators based on number of operands: Depending on
number of operands passed to the operator, the operators can be classified
into three categories. They are
1. Unary Operator
2. Binary Operator
3. Ternary Operator
Unary Operator: When one operand is passed to the operator then such an
operator is called Unary operator.
Ex: unary minus(-), incrementing(++), decrementing(--) etc.
Binary Operator: When two operands are passed to the operator then such
an operator is called Binary operator.
Ex: addition(+), lessthan(<), Bitwise And(&) etc.
Ternary Operator: When three operands are passed to the operator then
such an operator is called ternary operator.
Ex: Conditional Operator ( ? : )
Classification of operators based on operation: Depending on the operation
performed by the operator, the operators can be classified into seven
categories. They are
1. Arithmetic Operators
2. Bitwise Operators
3. Relational Operators
4. Boolean Logical Operators
5. Short Circuit Logical Operators
6. Assignment Operators
7. Conditional Operator
Arithmetic Operators: Arithmetic operators are the operators which take
numerical values as the input and produces numerical values as the output.
The following table lists the arithmetic operators:
Operator Purpose Example Result

Krishnaveni Degree College :: Narasaraopet Page No. : 16


Object Oriented Programming using Java UNIT - I

+ Addition 12 + 4.9 16.9


– Subtraction 12 - 4.9 7.1
* Multiplication 12 * 4.9 58.8
/ Division 12 / 4.9 2.45
% Modulus 12 % 4.9 2.2
++ Increment Take a=10; a++ 11
+= Addition assignment Take a=10; a+=10 20
–= Subtraction assignment Take a=10; a-=10 0
*= Multiplication assignment Take a=10; a*=10 100
/= Division assignment Take a=10; a/=10 11
%= Modulus assignment Take a=10; a%=10 0
Bitwise Operators: Java's bitwise operators operate on individual bits of
integer (int and long) values. If an operand is shorter than an int, it is
promoted to int before doing the operations.
Operator Purpose Example Result
~ Bitwise unary NOT ~0011 1100
& Bitwise AND 0011 & 0110 0010
| Bitwise OR 0011 | 0110 0111
^ Bitwise exclusive OR 0011 ^ 0110 0101
>> Shift right 0011 >> 1 0001
>>> Shift right zero fill 1111>>2 0011
(-1 in 4 bits)
<< Shift left 0011 << 1 0110

Relational Operators: The relational operators determine the relationship that


one operand has to the other. Relational operators are the operators which
take numerical values as the input and produces Boolean values as the
output. The following table lists the relational operators:
Operator Purpose Example Result
== Equal to 4 == 1 false
!= Not equal to 4 != 1 True
> Greater than 4>1 True
< Less than 4<1 False
>= Greater than or equal to 4 >= 1 True
<= Less than or equal to 4 <= 1 False

Krishnaveni Degree College :: Narasaraopet Page No. : 17


Object Oriented Programming using Java UNIT - I

Boolean Logical Operators: Boolean Logical operators are the operators


which take Boolean values as the input and produces Boolean values as the
output. The following table lists the Boolean logical operators:
Operator Purpose Example Result
& Logical AND false && false false
false && true false
true && false false
true && true true
| Logical OR false || false false
false || true true
true || false true
true || true true
^ Logical Ex-OR false ^ false false
false ^ true true
true ^ false true
true ^ true false
! Logical unary NOT ! flase true
! true false

Short-circuit Logical Operators: In Java logical operators, if the evaluation of


a logical expression exits in between before complete evaluation, then it is
known as Short-circuit. A short circuit happens because the result is clear
even before the complete evaluation of the expression, and the result is
returned. Short circuit evaluation avoids unnecessary work and leads to
efficient processing.
Operator Purpose Example Result
&& Short-circuit AND false && true && false
true
|| Short-circuit OR false || true || true true

The Assignment Operator: The assignment operator is the single equal sign,
=. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression. The
assignment operator allows to create a chain of assignments.

Krishnaveni Degree College :: Narasaraopet Page No. : 18


Object Oriented Programming using Java UNIT - I

Ex: int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement.
This works because the = is an operator that yields the value of the right-
hand expression. Thus, the value of z = 100 is 100, which is then assigned to
y, which in turn is assigned to x. Using a chain of assignments it is an easy
way to set a group of variables to a common value.
The ? Operator: Java includes a special ternary (three-way) operator that can
replace certain types of if-then-else statements. ?. is the ternary operator and
its general form is
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value.
If expression1 is true, then expression2 is evaluated; otherwise, expression3
is evaluated. Both expression2 and expression3 are required to return the
same type, which can‘t be void.
Ex: ratio = denom == 0 ? 0 : num / denom;

Type conversion and casting: In Java two types of conversions take place.
They are
1. Java’s Automatic Conversions
2. Type Casting
Java’s Automatic Conversions: When one type of data is assigned to another
type of variable, an automatic type conversion will take place if the following
two conditions are met. They are
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For
example, the int type is always large enough to hold all valid byte values, so
no explicit cast statement is required. For widening conversions, the numeric
types, including integer and floating-point types, are compatible with each
other. However, there are no automatic conversions from the numeric types
to char or boolean. Also, char and boolean are not compatible with each
other. As mentioned earlier, Java also performs an automatic type conversion
when storing a literal integer constant into variables of type byte, short, long,
or char.

Krishnaveni Degree College :: Narasaraopet Page No. : 19


Object Oriented Programming using Java UNIT - I

Type Casting: To create a conversion between two incompatible types, you


must use a cast. A cast is simply an explicit type conversion or Type Casting.
It has this general form
Syntax:
(target-type) value
int i =(int) 3.5;

Accepting Input from the Keyboard: There are many ways to read data
from the keyboard. They are
1. InputStreamReader
2. Console
3. Scanner
4. DataInputStream etc.
InputStreamReader class: InputStreamReader class can be used to read data
from keyboard.It performs two tasks. They are
1. connects to input stream of keyboard
2. converts the byte-oriented stream into character-oriented stream
BufferedReader class: BufferedReader class can be used to read data line by
line by readLine() method. Example of reading data from keyboard by
InputStreamReader and BufferdReader class. In this example, we are
connecting the BufferedReader stream with the InputStreamReader stream
for reading the line by line data from the keyboard.
// Reading data from the keyboard with the InputStreamReader
import java.io.*;
class keyBoardRead
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 20


Object Oriented Programming using Java UNIT - I

Reading Input with Java.util.Scanner Class: Accepting keyboard input in


Java is done using a Scanner object. Consider the following statement
Scanner input = new Scanner(System.in)
This statement declares a reference variable named console. The Scanner
object is associated with standard input device (System.in).
To get input from keyboard, you can call methods of Scanner class. For
example in following statement nextInt() method of Scanner takes an integer
and returns to variable x :
int x = input.nextInt();
// Reading data from the keyboard with the Scanner
import java.io.*;
class ScannerRead
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter your lucky number: ");
int lucknum=input.nextInt();
System.out.println("Lucky Number "+lucknum);
}
}

Displaying Output with System.out: System.out is the standard output


stream that is used to produce the result of a program on an output device
like the computer screen. Here there are 3 print functions that can be used
with System.out. They are
1. print()
2. println()
3. printf()
print(): This method in Java is used to display a text on the console. This text
is passed as the parameter to this method in the form of String. This method
prints the text on the console and the cursor remains at the end of the text
at the console. The next printing takes place from just here.
// Java code to illustrate print()
import java.io.*;
class Demo_print

Krishnaveni Degree College :: Narasaraopet Page No. : 21


Object Oriented Programming using Java UNIT - I

{
public static void main(String[] args)
{
// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
println(): This method in Java is also used to display a text on the console. It
prints the text on the console and the cursor moves to the start of the next
line at the console. The next printing takes place from the next line.
// Java code to illustrate println()
import java.io.*;
class Demo_println
{
public static void main(String[] args)
{
// using println()
// all are printed on
// separate line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
printf(): printf() is the easiest of all methods as this is similar to printf in C.
Note that System.out.print() and System.out.println() take a single argument,
but printf() may take multiple arguments. This is used to format the output
in Java.
// A Java program to demonstrate working of printf() in Java
class JavaFormatter1
{
public static void main(String args[])

Krishnaveni Degree College :: Narasaraopet Page No. : 22


Object Oriented Programming using Java UNIT - I

{
int x = 100;
System.out.printf( "Printing simple" + " integer: x = %d\n", x);
}
}

Displaying Formatted Output with String.format(): The java String.


format() method returns the formatted string by given locale, format and
arguments. If you don't specify the locale in String.format() method, it uses
default locale by calling Locale.getDefault() method. The format() method of
java language is like sprintf() function in c language and printf() method of
java language.
//Java Program to demo String.format()
public class FormatExample
{
public static void main(String args[])
{
String name="sonoo";
String sf1=String.format("name is %s",name);
String sf2=String.format("value is %f",32.33434);
System.out.println(sf1);
System.out.println(sf2);
}
}

Control Statements: Control statements are used to change the flow of


execution of a program. Java‘s control statements can be put into the
following categories. They are
1. Selection statements
2. Iteration statements and
3. Jump statements
Selection statements selects a set of statements for execution based
on the result of condition. Iteration statements enable program execution to
repeat one or more statements until the condition is satisfied. Jump

Krishnaveni Degree College :: Narasaraopet Page No. : 23


Object Oriented Programming using Java UNIT - I

statements allow the program to jump to the required statement within the
block.

Selection Statements: Selection statements allow the program to choose


different paths of execution based upon the outcome of an expression or the
state of a variable. There are various types of if statement in java.
a. if statement
b. if-else statement
c. nested if statement
d. if-else-if ladder
e. switch statement
Simple if Statement: The simple if statement initially tests the condition. If the
condition is true it executes the statement-block and moves to the next
statement. If the condition is false it skips the statement-block and directly
moves to the next statement.

// Program to find the absolute value of the given number


import java.util.Scanner;
public class AbsNum
{
public static void main(String args[])
{
float num;
Scanner input = new Scanner(System.in);
System.out.println("Enter any number: ");
num=input.nextFloat();
float num1=num;

Krishnaveni Degree College :: Narasaraopet Page No. : 24


Object Oriented Programming using Java UNIT - I

if(num<0)
num=-num;
System.out.println("The absolute value of "+num1+" is "+num);
}
}
if-else Statement: The if-else statement is an extension of simple if statement.
If-else statement initially tests the condition. If the condition is true it
executes the true-statement-block and moves to the next statement. If the
condition is false it executes the false-statement-block and moves to the next
statement. In any case , either true-statement-block or false-statement-block
is executed and moves to the next statement.

// Program to check whether the given number is even or odd


import java.util.Scanner;
public class EvenOdd
{
public static void main(String args[])
{
int num;
Scanner input = new Scanner(System.in);
System.out.println("Enter any number: ");
num=input.nextInt();
if(num %2 == 0)
System.out.println(num+" is an even number");
else
System.out.println(num+" is an odd number");

Krishnaveni Degree College :: Narasaraopet Page No. : 25


Object Oriented Programming using Java UNIT - I

}
}
Nested – if: When one if statement is nested in another if statement then it
is called as nested if statement.

// Program to find maximum among three given numbers


import java.util.Scanner;
public class MaxThree
{
public static void main(String args[])
{
float num1,num2,num3, max;
Scanner input = new Scanner(System.in);
System.out.println("Enter any three numbers: ");
num1=input.nextFloat();
num2=input.nextFloat();
num3=input.nextFloat();
if(num1 > num2)
if(num1 > num3)

Krishnaveni Degree College :: Narasaraopet Page No. : 26


Object Oriented Programming using Java UNIT - I

max = num1;
else
max = num3;
else
if(num2 > num3)

max = num2;
else
max = num3;
System.out.println(“Maximum number is "+max);
}
}
else-if ladder : When one if statement is added in the else part of another if
statement then it is called as else – if ladder statement.

// Program to find grade of the student


import java.util.Scanner;
public class GradeSt
{
public static void main(String args[])
{
int marks;
Scanner input = new Scanner(System.in);
System.out.println("Enter marks out of 100: ");
marks=input.nextInt();
if(marks>= 70)
System.out.println("Distinction");

Krishnaveni Degree College :: Narasaraopet Page No. : 27


Object Oriented Programming using Java UNIT - I

else
if(marks>= 60)
System.out.println("First Class");
else
if(marks>= 50)
System.out.println("Second Class");
else
if(marks>= 35)
System.out.println("Third Class");
else
System.out.println("Fail");
}
}
switch statement: The switch statement is a multiway branch statement. It
provides an easy way to select one of the option among several options. It
often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:
switch (expression)
{
case value1: statement1-block;
break;
case value2: statement2-block;
break;
...
case valueN: statementN-block;
break;
default: defaultstatement-block;
}
The expression must be of type byte, short, int, or char. Each of the values
specified in the case statements must be of a type compatible with the
expression. Each case value must be a unique literal that is, it must be a
constant, not a variable. Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is
compared with each of the literal values in the case statements. If a match is
found, the code sequence following that case statement is executed. If none
of the constants matches the value of the expression, then the default

Krishnaveni Degree College :: Narasaraopet Page No. : 28


Object Oriented Programming using Java UNIT - I

statement is executed. However, the default statement is optional. If no case


matches and no default is present, then no further action is taken. The break
statement is used inside the switch to terminate a statement sequence. When
a break statement is encountered, execution branches to the first line of code
that follows the entire switch statement. This has the effect of ―jumping out
of the switch.
// Program to read day no and print name of the day using switch
statement
import java.util.Scanner;
public class DayName
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the day number:");
int dayno=input.nextInt();
switch(dayno)
{
case 1: System.out.println(dayno+"day in the week is Monday");
break;
case 2: System.out.println(dayno+"day in the week is Tuesday");
break;
case 3: System.out.println(dayno+"day in the week is Wednesday");
break;
case 4: System.out.println(dayno+"day in the week is Thursday");
break;
case 5: System.out.println(dayno+"day in the week is Friday");
break;
case 6: System.out.println(dayno+"day in the week is Saturday");
break;
case 7: System.out.println(dayno+"day in the week is Sunday");
break;
default :System.out.println(dayno+"is an Invalid Day Number");
}
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 29


Object Oriented Programming using Java UNIT - I

Iteration Statements: Iteration Statement repeats set of instruction until the


condition for termination is met. These statements appear in the source code
only once, but it execute many times. Such kinds of statements are also called
as loops. Iteration Statement in Java are mainly of three types
1. 'while' Statement
2. 'do while' Statement
3. 'for' Statement
while Statement: The while loop is an entry controlled loop. It tests the
condition before executing the loop body. The condition can be any Boolean
expression. The body of the loop will be executed as long as the conditional
expression is true. When condition becomes false, control passes to the next
line of code immediately following the loop. The curly braces are unnecessary
if only a single statement is being repeated. The general form of the while
statement is
while(condition)
{
// body of loop
}
// Program to print n natural numbers using While Loop
import java.util.Scanner;
public class Print_N_Nat
{
public static void main(String args[])
{
int i, n;
Scanner input = new Scanner(System.in);
System.out.println("Enter how many numbers are to be printed: ");
n = input.nextInt();
System.out.println( n + " natural numbers are as follows….. ");
i=1;
while(i <= n)
{
System.out.println(i);
i=i+1;
}

Krishnaveni Degree College :: Narasaraopet Page No. : 30


Object Oriented Programming using Java UNIT - I

}
}
do-while: The do-while loop is an exit controlled loop. The do-while loop
always executes its body at least once, because its conditional expression is
at the bottom of the loop. Its general form is
do
{
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and
then evaluates the conditional expression. If this expression is true, the loop
will repeat. Otherwise, the loop terminates.
// Program to print the reverse of a given number
import java.util.Scanner;
class RevNum
{
public static void main(String args[])
{
int num,rev,rem ;
Scanner input = new Scanner(System.in);
System.out.print("Enter any integer number :");
num=input.nextInt();
int num1=num;
rev=0;
do
{
rem = num % 10;
rev=rev*10+rem;
num = num /10;
}while(num!=0);
System.out.print("The reverse number of " + num1+"is "+rev);
}
}
for: Beginning with JDK 5, there are two forms of the for loop. The first is the
traditional form that has been in use since the original version of Java. The
second is the new one i.e. for-each form.

Krishnaveni Degree College :: Narasaraopet Page No. : 31


Object Oriented Programming using Java UNIT - I

For loop: For loop executes group of Java statements as long as the boolean
condition evaluates to true. For loop combines three elements which we
generally use: initialization statement, boolean expression and increment or
decrement statement. Here is the general form of the traditional for
statement:
for(initialization; condition; iteration)
{
// body
}
If only one statement is being repeated, there is no need for the curly
braces.
The for loop operates as follows. When the loop first starts, the initialization
portion of the loop is executed. Generally, this is an expression that sets the
value of the loop control variable, which acts as a counter that controls the
loop. It is important to understand that the initialization expression is only
executed once. Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If
this expression is true, then the body of the loop is executed. If it is false, the
loop terminates. Next, the iteration portion of the loop is executed. This is
usually an expression that increments or decrements the loop control
variable. The loop then iterates, first evaluating the conditional expression,
then executing the body of the loop, and then executing the iteration
expression with each pass. This process repeats until the controlling
expression is false.
// Program to print factorial of a number
import java.util.Scanner;
class ReturnFact
{
public static void main(String args[])
{
int n,i ;
long f=1;
Scanner input = new Scanner(System.in);
System.out.print("Enter any number: ");
n=input.nextInt();
for(i=1;i<=n;i++)

Krishnaveni Degree College :: Narasaraopet Page No. : 32


Object Oriented Programming using Java UNIT - I

f*=i;
System.out.println("Factorial of "+n+" is "+f);
}
}
For-Each : A for each style loop is designed to cycle through a collection of
objects, such as an array, in strictly sequential fashion, from start to finish.
The advantage of this approach is that no new keyword is required, and no
preexisting code is broken. The for-each style of for is also referred to as the
enhanced for loop.
The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
statement-block
Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection, one at a time, from
beginning to end.
// Program to read numbers using for and print them using for each
import java.util.Scanner;
class ForEachDemo
{
public static void main(String args[])
{
int i, n;
Scanner input = new Scanner(System.in);
System.out.print("Enter how many numbers: ");
n=input.nextInt();
float num[] = new float[n];
System.out.println("Enter "+n+" numbers one by one: ");
for(i=0;i<n;i++)
num[i] = input.nextFloat();
System.out.println(n+" numbers in an array are as follows: ");
for(float number: num)
System.out.println(number);
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 33


Object Oriented Programming using Java UNIT - I

Nested Loops: Like all other programming languages, Java allows loops to be
nested. That is, one loop may be inside another. For example, here is a
program that nests for loops:
// Program to sort a given list of numbers
import java.util.*;
public class Sort
{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter how many numbers: ");
n=input.nextInt();
System.out.println("Enter "+n+" numbers one by one ");
float number[]= new float[n];
for(int i=0;i<n;i++)
number[i]=input.nextFloat();
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(number[j]>number[j+1])
{
float temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
}
System.out.println("sorted list is as follows");
for(int i=0;i<n;i++)
System.out.print(" "+number[i]);
}
}

Jump Statements: Java supports three jump statements: break, continue,


and return. These statements transfer control of execution to another part of
the program.
break: In Java, the break statement has three uses. First, as you have seen, it
terminates a statement sequence in a switch statement. Second, it can be

Krishnaveni Degree College :: Narasaraopet Page No. : 34


Object Oriented Programming using Java UNIT - I

used to exit a loop. Third, it can be used as a civilized form of goto. The last
two uses are explained here.
// Program to check prime number using break
import java.util.Scanner;
class PrimeChk
{
public static void main(String args[])
{
int i,n;
Scanner input = new Scanner(System.in);
System.out.println("Enter any number: ");
n=input.nextInt();
for(i=2;i<=n/2;i++)
if(n%i==0)
break;
if(i>n/2)
System.out.println(n+" is Prime Number");
else
System.out.println(n+" is not Prime Number");
}
}
Labelled break : The labelled break statement can also be used to construct
a civilized form of the goto statement. The general form of the labeled break
statement is shown here.
break label;
Most often, label is the name of a label that identifies a block of code. But
you cannot use break to transfer control out of a block that does not enclose
the break statement.
// Program to print triangle of stars
import java.util.Scanner;
class BreakStarTri
{
public static void main(String args[])
{
int i,j,n;
Scanner input = new Scanner(System.in);

Krishnaveni Degree College :: Narasaraopet Page No. : 35


Object Oriented Programming using Java UNIT - I

System.out.println("Enter how many rows:");


n=input.nextInt();
outer:
for(i=1;;i++)
{
for(j=1;j<=i;j++)
{
if(i>n)
break outer;
System.out.print(" * ");
}
System.out.println();
}
}
}
Continue: A continue statement causes control to be transferred directly to
the conditional expression that controls the loop.
// Program to check prime number using continue
import java.util.Scanner;
class PrimeChkCont
{
public static void main(String args[])
{
int i,n, cnt=0;
Scanner input = new Scanner(System.in);
System.out.println("Enter any number: ");
n=input.nextInt();
for(i=1;i<=n;i++)
{
if(n%i!=0)
continue;
cnt++;
}
if(cnt==2)
System.out.println(n+"is a Prime number");
else

Krishnaveni Degree College :: Narasaraopet Page No. : 36


Object Oriented Programming using Java UNIT - I

System.out.println(n+"is not a Prime number");


}
}
Labelled continue: Continue may also specify a label to describe which
enclosing loop to continue.
// Program to print triangle of stars
import java.util.Scanner;
class LabContStarTri
{
public static void main(String args[])
{
int i,j,n;
Scanner input = new Scanner(System.in);
System.out.println("Enter how many rows:");
n=input.nextInt();
outer:
for(i=1;i<=n;i++)
{
for(j=1;;j++)
{
System.out.print(" * ");
if(j==i)
{
System.out.println();
continue outer;
}
}
}
}
}
Return: The last control statement is return. The return statement is used to
explicitly return from a method. That is, it causes program control to transfer
back to the caller of the method.
// Program to print factorial of a number
import java.util.Scanner;
class ReturnFact

Krishnaveni Degree College :: Narasaraopet Page No. : 37


Object Oriented Programming using Java UNIT - I

{
public long fact(int n)
{
int i ;
long f=1;
for(i=1;i<=n;i++)
f*=i;
return f;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any number: ");
int n1=input.nextInt();
ReturnFact rf = new ReturnFact();
System.out.println("Factorial of "+n1+" is "+rf.fact(n1));
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 38


Object Oriented Programming using Java UNIT - II

Arrays, Command Line Arguments, Strings-String Class Methods


Classes & Objects: Creating Classes, declaring objects, Methods,
parameter passing, static fields and methods, Constructors, and ‘this’
keyword, overloading methods and access
Inheritance: Inheritance hierarchies, super and subclasses, member
access rules, ‘super’ keyword, preventing inheritance: final classes and
methods, the object class and its methods; Polymorphism: Dynamic
binding, method overriding, abstract classes and methods;

Arrays: An array is a group of similar data items referred to by a common


name. An array element is accessed by specifying the name of the array and
the value of the index within square brackets. Depending on number of
subscripts used to refer an array elements, the arrays can be classified as
1. One Dimensional Arrays
2. Multi-Dimensional Arrays
One-Dimensional Arrays: A one-dimensional array is a list of similar data
items. In one-dimensional array one subscript is used to refer an array
element. The general form of a one-dimensional array declaration is
Syntax: type var-name[ ];
Here, type declares the base type of the array. The base type determines the
data type of each element that comprises the array. Thus, the base type for
the array determines what type of data the array will hold.
EX: int month_days[];
The above example declares an array named month_days which is capable
of storing integer elements.
To link month_days with an actual, physical array of integers new is a special
operator that allocates dynamic memory for arrays. The general form of new
operator to allocate memory for one-dimensional arrays appears is as
follows:
Syntax: array-var = new type[size];
Ex: month_days =new int[12];
It is possible to combine the declaration of the array variable with the
allocation of the array itself, as shown below:
Syntax: type var-name[ ] = new type[size];
Ex: int month_days[] = new int[12];

Krishnaveni Degree College: Narasaraopet Page No.: 39


Object Oriented Programming using Java UNIT - II

// Program to search an element using Linear Search


import java.util.Scanner;
public class LinearSearch
{
public static void main(String args[])
{
int i, n;
float ele;
float number[] = new float[10];
Scanner input = new Scanner(System.in);
System.out.println("Enter how many numbers: ");
n = input.nextInt();
System.out.println("Enter " + n + " numbers one by one ");
for (i = 0; i < n; i++)
number[i] = input.nextFloat();
System.out.println("Enter the element to be searched : ");
ele = input.nextFloat();
for (i = 0; i < n; i++)
if (ele == number[i])
break;
if (i < n)
System.out.println(ele + "is found at " + i+ "position in the list");
else
System.out.println(ele + "is not found in the list");
}
}
Two-Dimensional Arrays: A two-dimensional array is an array of arrays that
contain similar data items. In two -dimensional array two subscripts are used
to refer an array element. The general form of a two-dimensional array
declaration is
Syntax: type var-name[ ][ ]=new type[ ][ ];
Ex: float a[][] = new float[3][3];
// Program to find the sum of two matrices
import java.util.Scanner;
public class MatSum
{
public static void main(String args[])
Krishnaveni Degree College: Narasaraopet Page No.: 40
Object Oriented Programming using Java UNIT - II

{
int i,j,k,m, n,p,q;
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of matrix A: ");
m = input.nextInt();
n=input.nextInt();
System.out.println("Enter the size of matrix B: ");
p = input.nextInt();
q=input.nextInt();
if((m==p) &&(n==q))
{
float a[][] = new float[m][n];
float b[][]=new float[p][q];
float c[][]=new float[m][q];
System.out.println("Enter " + m * n +"numbers of matrix A: ");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
a[i][j] = input.nextFloat();
System.out.println("Enter " + p * q +"numbers of matrix B: ");
for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
b[i][j] = input.nextFloat();
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
c[i][j]=a[i][j]+b[i][j];
System.out.println("The resultant matrix after addition is: " );
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
System.out.print(c[i][j]+" ");
System.out.println();
}
}
else
System.out.println("Matrix addition not possible");
}
}
Krishnaveni Degree College: Narasaraopet Page No.: 41
Object Oriented Programming using Java UNIT - II

Command-Line Arguments: Command-line arguments are used to pass


information into a program while running the program. A command-line
argument is the information that directly follows the program‘s name on the
command line when it is executed. To access the command-line arguments
inside a Java program is quite easy. They are stored as strings in a String array
passed to the args parameter of main( ). The first command-line argument is
stored at args[0], the second at args[1], and so on. All command-line
arguments are passed as strings and must be converted to numeric values
for calculation pupose.
// Program to find sum of two numbers using command line arguments
public class CmdLine
{
public static void main(String args[])
{

int num1=Integer.parseInt(args[0]);
int num2=Integer.parseInt(args[1]);
int sum = num1 +num2;
System.out.println("Sum = "+sum);
}
}

Strings: In Java a string is a sequence of characters. Java implements strings


as objects of type String. When a String object is created, then a string
created cannot be changed. That is, once a String object has been created,
characters that comprise that string cannot be changed. At first, this may
seem to be a serious restriction but still perform all types of string operations.
The difference is that each time sting is modified an altered version of an
existing string, a new String object is created that contains the modifications.
The original string is left unchanged. This approach is used because fixed,
immutable strings can be implemented more efficiently than changeable
ones. For those cases in which a modifiable string is desired, Java provides
two options: StringBuffer and StringBuilder. Both hold strings that can be
modified after they are created.
The String Constructors
The String class supports several constructors. To create an empty String, call
the default constructor.
Krishnaveni Degree College: Narasaraopet Page No.: 42
Object Oriented Programming using Java UNIT - II

Ex:
String s = new String();
S will be created with no characters in it.
To create a String initialized by an array of characters, use the constructor
shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string "abc".
To specify a subrange of a character array as an initializer using the following
constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and
numChars specifies the number of characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters “cde”.
To construct a String object that contains the same character sequence as
another String object using this constructor:
String(String strObj)
Here, strObj is a String object.
String snew = new String(s);
This initializes snew with the characters “cde” that are contained in strng s.

// Java Program to demo String Constructors.


class DemoString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s= new String();
String s1 = new String(c);
String s2 = new String(c,1,2);
String s3= new String(s1);
System.out.println(“Empty String is “+s);
System.out.println(“String created from character array is “+s1);
Krishnaveni Degree College: Narasaraopet Page No.: 43
Object Oriented Programming using Java UNIT - II

System.out.println(“Sub String from character array is “+s2);


System.out.println(“String created from string is “+s3);
}
}

String Class Methods: The String class has a set of built-in methods that can
be used on strings. They are
Method Description Example Result
charAt() Returns the String s1 = new ‘e’
character at the String("Hello");
specified index s1.charAt(1)
(position)
compareTo() Compares two String s1 = new 4
strings String("Hello");
lexicographically String s2 =
new String("Hai");
int
res=s1.compareTo(s2);
concat() Appends a String s1 = "one"; “Onetwo”
string to the end String s2 =
of another string s1.concat("two");
length() Returns the String s1 = "one"; 3
length of a Len=s1.length()
specified string
split() Splits a string Pattern pat = “one”
into an array of Pattern.compile("[ ,.!]"); “two”
substrings String strs[] = “alpha9”
pat.split("one “12”
two,alpha9 12!done."); “done”
substring() Returns a new String s1 = "Hello"; “He”
string which is
the substring of String result =
a specified s1.substring(0, 2);
string
toLowerCase() Converts a S1.toLowerCase() “hello”
string to lower
case letters
Krishnaveni Degree College: Narasaraopet Page No.: 44
Object Oriented Programming using Java UNIT - II

// Java Program to demo String Methods.


import java.util.regex.*;
class StringMethods
{
public static void main(String args[])
{

String s1 = new String("Hello");


System.out.println("charAt(1) before = " + s1.charAt(1));
String s2 = new String("Good Morning");
System.out.println("Length of "+s2+" is "+ s2.length());
int res=s1.compareTo(s2);
System.out.println("Result="+res);
if(res==0)
System.out.println(s1+"is same as "+s2);
else
System.out.println(s1+"is not same as "+s2);
String s3 = s1.concat(s2);
System.out.println("String after concatenation is"+s3);
Pattern pat = Pattern.compile("[ ,.!]");
String strs[] = pat.split("one two,alpha9 12!done.");
for(int i=0; i < strs.length; i++)
System.out.println("Next token: " + strs[i]);
String result = s1.substring(0, 2);
System.out.println("Substring is "+result);
String results = s1.toLowerCase();
System.out.println("String in Lower case "+results);
}
}

Classes: - Class is the logical construct upon which the entire Java language
is built. A class is the basic building block of an object-oriented language
such as Java. It is a template that describes the data and behaviour
associated with instances of that class.
Every class in Java can be composed of the following elements:

Krishnaveni Degree College :: Narasaraopet Page No. : 45


Object Oriented Programming using Java UNIT - II

 fields, member variables or instance variables: Fields are variables that


hold data specific to each object. For example, an employee might have
an ID number and Name.
 member methods or instance methods: Member methods perform
operations on an object. For example, an employee might have a
method to get his Name and set his Name.
 static fields or class fields: Static fields are common to all object and
they belong to entire class not to an individual object. For example, a
static field EmpCnt within the Employee class could keep track of the
number of objects created for Employee class. Each static field exists
only once in the class, regardless of how many objects are created for
that class.
 static methods or class methods: Static methods are methods that do
not affect a specific object.
 inner classes: Sometimes it is useful to contain a class within another
class. Inner class is useless outside of the class or it cannot be accessed
outside the class.
 Constructors: A special method that is called automatically when a new
object is created.
A simplified general form of a class definition is as shown below:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)

Krishnaveni Degree College :: Narasaraopet Page No. : 46


Object Oriented Programming using Java UNIT - II

{
// body of method
}
}
Ex 1:
class Stud1
{
int studno;
String name;
}
Ex2:
class StudDet
{
int studno;
String name;
void getDet()
{
-----
}
void printDet()
{
------
}
}

Object: A class is a template for an object, and an object is an instance of a


class.
Declaring objects: When a class is created a new data type is created.
Obtaining objects of a class is a two-step process. First, declare a variable of
the class type. This variable does not define an object. Instead, it is simply a
variable that can refer to an object. Second, an actual and physical copy of
the object should be achieved by using the new operator and assign it to
that variable. The new operator dynamically allocates (that is, allocates at run
time) memory for an object and returns a reference to it. This reference is the
address of the object in memory. Thus, in Java, all class objects must be
dynamically allocated.

Krishnaveni Degree College :: Narasaraopet Page No. : 47


Object Oriented Programming using Java UNIT - II

class Box
{
double width;
double height;
double depth;
}
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box. After
this line executes, mybox contains the value null, which indicates that it does
not yet point to an actual object. Any attempt to use mybox at this point will
result in a compile-time error. The next line allocates an actual object and
assigns a reference to it to mybox.
After the second line executes, use mybox to refer to the Box object. But in
reality, mybox simply holds the memory address of the actual Box object. The
two step process of Decaling an object can be combined as
Box mybox = new Box();
// Program to demonstrate class with only data members
import java.util.*;
class Stud1
{
int studno;
String name;
}
public class StudDetails
{
public static void main(String args[])
{
Stud1 s1=new Stud1();
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
s1.studno = input.nextInt();
s1.name = input.next();
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+s1.studno);
System.out.println("Name : "+s1.name);

Krishnaveni Degree College :: Narasaraopet Page No. : 48


Object Oriented Programming using Java UNIT - II

}
}

Methods: Classes usually consist of two things. They are instance variables
and methods. The general form of a method is
type name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any
valid type, including class types that are already created. If the method does
not return a value, its return type must be void. The name of the method can
be any legal identifier other than those already used by other items within
the current scope. The parameter-list is a sequence of type and identifier
pairs separated by commas. Parameters are essentially variables that receive
the value of the arguments passed to the method when it is called. If the
method has no parameters, then the parameter list will be empty.
// Program to use class that contains data members and methods
import java.util.*;
class StudDet
{
private int studno;
private String name;
void getDet()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
studno = input.nextInt();
name = input.next();
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}

Krishnaveni Degree College :: Narasaraopet Page No. : 49


Object Oriented Programming using Java UNIT - II

}
public class Stud
{
public static void main(String args[])
{
StudDet s1=new StudDet();
s1.getDet();
s1.printDet();
}
}
Parameter Passing: In general, there are two ways to pass argument to a
method. They are
1. call-by-value
2. call-by-reference
call-by-value: call-by-value approach copies the value of an argument into
the formal parameter of the method. Therefore, changes made to the
parameter in the called method have no effect on the argument in the calling
method. When you pass a primitive type to a method, it is call by value.
call-by-reference: In call-by-reference approach, a reference to an argument
(not the value of the argument) is passed to the parameter. Inside the called
method, this reference is used to access the actual argument specified in the
call. This means that changes made to the parameter in the called method
will affect the argument in the calling method. When you pass objects to a
method, it is call by reference.
// Program to demonstrate call by value technique.
import java.util.Scanner;
class Test
{
void swap(float i, float j)
{
float temp;
temp=i;
i=j;
j=temp;
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 50


Object Oriented Programming using Java UNIT - II

class CallByValue
{
float a , b;
public static void main(String args[])
{
Test ob = new Test();
CallByValue cbr = new CallByValue();
Scanner input = new Scanner(System.in);
System.out.println("Enter any two numbers : ");
cbr.a = input.nextFloat();
cbr.b = input.nextFloat();
System.out.println("a and b before swaping: " + cbr.a + " " + cbr.b);
ob.swap(cbr.a, cbr.b);
System.out.println("a and b after swaping: " + cbr.a + " " + cbr.b);
}
}

// Program to demonstrate call by reference technique.


import java.util.Scanner;
class Test1
{
void swap( CallByReference cbr)
{
float temp;
temp=cbr.a;
cbr.a=cbr.b;
cbr.b=temp;
}
}
class CallByReference
{
float a , b;
public static void main(String args[])
{
Test1 ob = new Test1();
CallByReference cbr = new CallByReference();

Krishnaveni Degree College :: Narasaraopet Page No. : 51


Object Oriented Programming using Java UNIT - II

Scanner input = new Scanner(System.in);


System.out.println("Enter any two numbers : ");
cbr.a = input.nextFloat();
cbr.b = input.nextFloat();
System.out.println("a and b before swaping: " + cbr.a + " " + cbr.b);
ob.swap(cbr );
System.out.println("a and b after swaping: " + cbr.a+ " " + cbr.b);
}
}

Static Fields and Methods : Class variables and methods will be used
independently of any object of that class. These are called as static variables
and methods.
static variable:
 It is a variable which belongs to the class and not to object(instance)
 Static variables are initialized only once , at the start of the execution .
These variables will be initialized first, before the initialization of any
instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and
doesn‘t need any object
 Syntax : <class-name>.<variable-name>

// Program using static variable


import java.util.Scanner;
class StudDet
{
private int studno;
private String name;
static int cnt;
void getData(int studno, String name)
{
this.studno = studno;
this.name = name;
cnt++;
}

Krishnaveni Degree College :: Narasaraopet Page No. : 52


Object Oriented Programming using Java UNIT - II

void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
System.out.println("Number of Objects Created : "+cnt);
}
}
public class StudentStatic
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet s1=new StudDet();
s1.getData(sno,sname);
s1.printDet();
System.out.println("Enter Student no and name : ");
sno = input.nextInt();
sname = input.next();
StudDet s2=new StudDet();
s2.getData(sno,sname);
s2.printDet();
}
}
Static Method:
 It is a method which belongs to the class and not to the
object(instance)
 A static method can access only static data. It can not access non-static
data (instance variables)
 A static method can call only other static methods and can not call a
non-static method from it.
 A static method can be accessed directly by the class name and doesn‘t
need any object

Krishnaveni Degree College :: Narasaraopet Page No. : 53


Object Oriented Programming using Java UNIT - II

 Syntax : <class-name>.<method-name>
 A static method cannot refer to "this" or "super" keywords in anyway

// Program using static variable and method


import java.util.Scanner;
class StudDet5
{
private int studno;
private String name;
static int cnt;
void getDet(int studno, String name)
{
this.studno = studno;
this.name = name;
cnt++;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
static void printCnt()
{
System.out.println("Number of Objects Created : "+cnt);
}
}
public class StudentStaticM
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet5 s1=new StudDet5();

Krishnaveni Degree College :: Narasaraopet Page No. : 54


Object Oriented Programming using Java UNIT - II

s1.getDet(sno,sname);
s1.printDet();
System.out.println("Enter Student no and name : ");
sno = input.nextInt();
sname = input.next();
StudDet5 s2=new StudDet5();
s2.getDet(sno,sname);
s2.printDet();
StudDet5.printCnt();
}
}
Static Block: Static block is mostly used for changing the default values of
static variables. This block gets executed when the class is loaded in the
memory. A class can have multiple Static blocks, which will execute in the
same sequence in which they have been written into the program.
class StaticBlock
{
static int num;
static String mystr;
static
{
num = 97;
mystr = "Static Block in Java";
}
public static void main(String args[])
{
System.out.println("Value of num="+num);
System.out.println("Value of mystr="+mystr);
}
}

Constructor: A constructor is a special method that is used to initialize a


newly created object and is called just after the memory is allocated for the
object. It can be used to initialize the objects ,to required ,or default values
at the time of object creation. It is not mandatory for the coder to write a
constructor for the class

Krishnaveni Degree College :: Narasaraopet Page No. : 55


Object Oriented Programming using Java UNIT - II

If no user defined constructor is provided for a class, compiler initializes


member variables to its default values.
 numeric data types are set to 0
 char data types are set to null character(“\0”)
 reference variables are set to null
Rules for create a Java Constructor
1. It has the same name as the class
2. It should not return a value not even void
// Program using constructor with no arguments
import java.util.Scanner;
class StudDet1
{
private int studno;
private String name;
StudDet1()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
studno = input.nextInt();
name = input.next();
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class StudentDetails
{
public static void main(String args[])
{
StudDet1 s1=new StudDet1();
s1.printDet();
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 56


Object Oriented Programming using Java UNIT - II

Parameterized Constructors: The parameters can also be passed to


constructors.
// Program using parametrized constructor
import java.util.Scanner;
class StudDet12
{
private int studno;
private String name;
StudDet12(int sno1, String sname1)
{
studno = sno1;
name = sname1;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class StudentDetails1
{
public static void main(String args[])throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet12 s1=new StudDet12(sno,sname);
s1.printDet();
}
}

Java "THIS" Keyword: Sometimes a method will need to refer to the object
that invoked it. To allow this, Java defines the this keyword. this can be used

Krishnaveni Degree College :: Narasaraopet Page No. : 57


Object Oriented Programming using Java UNIT - II

inside any method to refer to the current object. That is, this is always a
reference to the object on which the method was invoked. when a local
variable has the same name as an instance variable, the local variable hides
the instance variable. To avoid this problem this keyword can be used.
Keyword 'THIS' in Java is a reference variable that refers to the current object.
The various usage of keyword Java 'THIS' in Java is as per the below.
 It can be used to refer current class instance variable
 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance

// Program using this keyword


import java.util.Scanner;
class StudDet123
{
private int studno;
private String name;
StudDet123(int studno, String name)
{
this.studno = studno;
this.name = name;
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class StudentThis
{
public static void main(String args[])throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");

Krishnaveni Degree College :: Narasaraopet Page No. : 58


Object Oriented Programming using Java UNIT - II

int sno = input.nextInt();


String sname = input.next();
StudDet123 s1=new StudDet123(sno,sname);
s1.printDet();
}
}

Overloading methods and access: Method overloading supports


polymorphism because it is one way that Java implements the “one interface,
multiple methods” paradigm. When you overload a method, each version of
that method can perform different activity. Depending on no of arguments
or type of arguments the system dynamically decides which method to
access and get it executed.
// Java program to demonstrate method overloading in Java
public class SumNum
{
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, int y, int z)
{
return (x + y + z);
}
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
SumNum s = new SumNum();
System.out.println("Sum of two integers is "+s.sum(10, 20));
System.out.println("Sum of three integers is "+s.sum(10, 20, 30));
System.out.println("Sum of two doubles is "+s.sum(10.5, 20.5));
}

Krishnaveni Degree College :: Narasaraopet Page No. : 59


Object Oriented Programming using Java UNIT - II

Inheritance: Inheritance is one of the cornerstones of object-oriented


programming because it allows the creation of hierarchical classifications.
The mechanism of deriving a new class from old one is called inheritance. In
the terminology of Java, a class that is inherited is called a superclass. The
class that does the inheriting is called a subclass. Therefore, a subclass is a
specialized version of a superclass. It inherits all of the instance variables and
methods defined by the superclass and add its own, unique elements.
The general form of a class declaration that inherits a superclass is shown
here:
Syntax:
Class Sub-classname extends Super-classname
{
Declaration of variables;
Declaration of methods;
}
Ex:
class B extends A
{
------
--------
}

Types of Inheritance: Depending upon how many super classes are used
to derive subclasses and how many sub classes are derived the inheritance
is classified into 4 categories. They are
1). Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
4). Multiple Inheritance
5) Hybrid Inheritence

Krishnaveni Degree College :: Narasaraopet Page No. : 60


Object Oriented Programming using Java UNIT - II

Single Inheritance: Inheritance which uses one super class to derive new sub
class is said to be Single Inheritance.
Multilevel Inheritance: Inheritance which uses one derived class as super
class to derive new subclass is said to be Multilevel Inheritance.
Hierarchical Inheritance: Inheritance which uses one super class to derive
more than one sub class is said to be Hierarchical Inheritance.

Krishnaveni Degree College :: Narasaraopet Page No. : 61


Object Oriented Programming using Java UNIT - II

Multiple Inheritance: Inheritance which uses more than one super class to
derive new subclass is said to be Multiple Inheritance. Java doesnot directly
implement multiple interfaces. It can be done by using interfaces.
Hierarchical Inheritance: Inheritance which uses one super class to derive
more than one sub class is said to be Hierarchical Inheritance.
Hybrid Inheritnce: In Java, the hybrid inheritance is the composition of two or
more types of inheritance. The above hybrid inheritance is the composition
of Hierarchical and Multiple Inheritence.

super and subclasses: In Java, it is possible to inherit attributes and methods


from one class to another. According to the "inheritance concept" class fall
into two categorie. They are:
1. subclass
2. superclass
subclass: subclass is also called as child class. Subclass is the class that inherits
attributes and methods from another class.
superclass: superclass is also called as the parent class. The class being
inherited from is called super class. To inherit from a class, use
the extends keyword.

// Program to demonstrate Single Inheritance


import java.util.Scanner;
class Room
{
float length;
float breadth;
void getlb(float l, float b)
{
length=l;
breadth=b;
}
float area()
{
return length*breadth;
}

Krishnaveni Degree College :: Narasaraopet Page No. : 62


Object Oriented Programming using Java UNIT - II

}
class BedRoom extends Room
{
float height;
void getlbh(float l, float b, float h)
{
getlb(l,b);
height=h;
}
float volume()
{
return length*breadth*height;
}
}
public class SingleInher
{
public static void main(String args[])
{
Scanner input1 = new Scanner(System.in);
System.out.print("Enter the length of the room: ");
float l1=input1.nextFloat();
System.out.print("Enter the breadth of the room: ");
float b1=input1.nextFloat();
System.out.print("Enter the height of the room: ");
float h1=input1.nextFloat();
BedRoom room1 = new BedRoom();
room1.getlbh(l1,b1,h1);
float area1 = room1.area();
float vol1=room1.volume();
System.out.println("Area of the room: "+area1);
System.out.println("Volume of the room: "+vol1);
}
}
// Program to demonstrate Hirarchical Inheritance
import java.util.Scanner;
class Figure

Krishnaveni Degree College :: Narasaraopet Page No. : 63


Object Oriented Programming using Java UNIT - II

{
double dim1;
}
class Circle extends Figure
{
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any radius: ");
dim1=input.nextDouble();
}
double area()
{
return dim1*dim1*3.1415;
}
}
class Rectangle extends Figure
{
double dim2;
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and breadth of the Rectangle: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
class Triangle extends Figure
{
double dim2,dim3;
void getdim()
{

Krishnaveni Degree College :: Narasaraopet Page No. : 64


Object Oriented Programming using Java UNIT - II

Scanner input = new Scanner(System.in);


System.out.print("Enter the three sides of triangle: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
dim3=input.nextDouble();
}
double area()
{
double s=(dim1+dim2+dim3)/2;
return Math.sqrt(s*(s-dim1)*(s-dim2)*(s-dim3));
}
}
public class FigureAreas
{
public static void main(String args[])
{
Circle c = new Circle();
c.getdim();
System.out.println("Area of circle is " + c.area());
Rectangle r = new Rectangle();
r.getdim();
System.out.println("Area of rectangle is " + r.area());
Triangle t = new Triangle();
t.getdim();
System.out.println("Area of trinagle is " + t.area());
}
}
// Program to demonstrate Multi Level Inheritance
import java.util.Scanner;
class Fig
{
double dim1;
}
class Cir extends Fig
{
void getdim()

Krishnaveni Degree College :: Narasaraopet Page No. : 65


Object Oriented Programming using Java UNIT - II

{
Scanner input = new Scanner(System.in);
System.out.print("Enter any radius: ");
dim1=input.nextDouble();
}
double area()
{
return dim1*dim1*3.1415;
}
}
class Rec extends Cir
{
double dim2;
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and breadth: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class MultiLevelInher
{
public static void main(String args[])
{
Circle c = new Circle();
c.getdim();
System.out.println("Area of circle is " + c.area());
Rectangle r = new Rectangle();
r.getdim();
System.out.println("Area of rectangle is " + r.area());
}

Krishnaveni Degree College :: Narasaraopet Page No. : 66


Object Oriented Programming using Java UNIT - II

Member access rules: Member access rules determine whether other


classes can use a particular field or invoke a particular method. At the
member level we can use access specifiers public and private.
At the member level, when we use the public modifier or no modifier
then that data members or methds can be accessed by all the objects of the
same class or other class. For members, there are two additional access
modifiers: private and protected. The private modifier specifies that the
member can only be accessed in its own class. The protected modifier
specifies that the member can only be accessed within its own package (as
with package-private) and, in addition, by a subclass of its class in another
package.
The following table shows the access to members permitted by each
modifier.
Modifier Class Subclass World
public Y Y Y
protected Y Y N
no modifier Y N N
private Y N N
The first column indicates that a class always has access to its own members
without caring about the access modifier used. The second column indicates
that object of the subclass can access pulic and protected variables but no
modifier or private variables cat e accessed. The third column indicates
objects of other classes can only access public variables but no
modifier,protected and private variables cant be accessed.

super keyword in java: The super keyword in java is a reference variable


that is used to refer immediate parent class object.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.

Krishnaveni Degree College :: Narasaraopet Page No. : 67


Object Oriented Programming using Java UNIT - II

//Program to use super to refer immediate parent class instance variable.


class Parentclass
{
int num=100;
}
class Subclass extends Parentclass
{
int num=110;
void printNumber()
{
System.out.println("Value of num in super class: "+super.num);
System.out.println("Value of num in sub class: "+num);
}
public static void main(String args[])
{
Subclass obj= new Subclass();
obj.printNumber();
}
}
// Program to use super() to invoke immediate parent class constructor.
import java.util.Scanner;
class Fig2
{
Scanner input = new Scanner(System.in);
double dim1;
}
class Cir2 extends Fig2
{
Cir2()
{
dim1=input.nextDouble();
}
double area()
{
return dim1*dim1*3.1415;

Krishnaveni Degree College :: Narasaraopet Page No. : 68


Object Oriented Programming using Java UNIT - II

}
}
class Rec2 extends Cir2
{
double dim2;
Rec2()
{
super();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class SuperEx2
{
public static void main(String args[])
{
System.out.print("Enter any radius: ");
Cir2 c = new Cir2();
System.out.println("Area of circle is " + c.area());
System.out.print("Enter the length and breadth of rectangle : ");
Rec2 r = new Rec2();
System.out.println("Area of rectangle is " + r.area());
}
}
//Program to use super to refer immediate parent class method.
import java.util.Scanner;
class Cir1
{
Scanner input = new Scanner(System.in);
double dim1;
void getdim()
{
dim1=input.nextDouble();

Krishnaveni Degree College :: Narasaraopet Page No. : 69


Object Oriented Programming using Java UNIT - II

}
double area()
{
return dim1*dim1*3.1415;
}
}
class Rec1 extends Cir1
{
double dim2;
void getdim()
{
super.getdim();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class SuperEx
{
public static void main(String args[])
{
Circle c = new Circle();
System.out.print("Enter any radius: ");
c.getdim();
System.out.println("Area of circle is " + c.area());
Rectangle r = new Rectangle();
System.out.print("Enter the length and breadth: ");
r.getdim();
System.out.println("Area of rectangle is " + r.area());
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 70


Object Oriented Programming using Java UNIT - II

Final Keyword In Java: The final keyword in java is used to restrict the user
for preventing its contents from being modified.. The java final keyword can
be used with the following components. They are
1. variable
2. method
3. class
The meaning of final varies from context to context, but the essential idea is
the same.
A final variable becomes a constant and its value can not be changed.
A final method may not be overridden.
A final class can not be inherited

// Program to demonstrate Final Keyword before the instance variable


import java.util.Scanner;
class CircleNew
{
Scanner input = new Scanner(System.in);
final double PI = 3.1415;
double dim1;
void getdim()
{
System.out.print("Enter any radius: ");
dim1=input.nextDouble();
}
double area()
{
return PI*Math.pow(dim1,2);
}
}
public class FinalEx
{
public static void main(String args[])
{
CircleNew c = new CircleNew();
c.getdim();

Krishnaveni Degree College :: Narasaraopet Page No. : 71


Object Oriented Programming using Java UNIT - II

System.out.println("Area of circle is " + c.area());


}
}
// Program to demonstrate Final Keyword before the instance method
import java.util.Scanner;
class CircleNews
{
Scanner input = new Scanner(System.in);
final double PI = 3.1415;
double dim1;
void getdim()
{
dim1=input.nextDouble();
}
double area()
{
return PI*Math.pow(dim1,2);
}
final void printArea()
{
System.out.println("The Area is " + area());
}
}
class Rectangles extends CircleNews
{
double dim2;
void getdim()
{
super.getdim();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 72


Object Oriented Programming using Java UNIT - II

public class FinalEx1


{
public static void main(String args[])
{
CircleNews c = new CircleNews();
System.out.print("Enter any radius: ");
c.getdim();
c.printArea();
Rectangles r = new Rectangles();
System.out.print("Enter the length and breadth of the rectangle: ");
r.getdim();
r.printArea();
}
}
// Program to demonstrate Final Keyword before the class
import java.util.*;
final class Base
{
public void displayMsg()
{
System.out.println("I'm displayMsg() in Base class.");
}
}
public class FinalClassExample
{
public void displayMsg()
{
System.out.println("I'm displayMsg() in Final class.");
}
public static void main(String []s)
{
Base base = new Base();
base.displayMsg();
FinalClassExample fce = new FinalClassExample();
fce.displayMsg();
}

Krishnaveni Degree College :: Narasaraopet Page No. : 73


Object Oriented Programming using Java UNIT - II

Object Class: t is a superclass of all other classes. Object defines the methods
which are available to every object.
Method Description
boolean equals(Object object) Returns true if the invoking
object is equivalent to object.
final Class<?>getClass() Obtains the class object that
describes the invoking object.
int hashCode( ) Returns the hash code associated
with the invoking object.

// Program to demonstrate Object class


public class DemoObjectClass
{
public String toString()
{
return "DemoObjectClass";
}
public int hashCode()
{
return 12345;
}
public static void main(String args[])
{
DemoObjectClass obj = new DemoObjectClass();
DemoObjectClass obj1 = new DemoObjectClass();
DemoObjectClass obj2;
obj2=obj;
System.out.println("The object creted is : "+obj);
System.out.println("The hashcode is : "+obj.hashCode());
if(obj.equals(obj1))
System.out.println("The both objects are same");
else
System.out.println("The both objects are not same");
if(obj.equals(obj2))

Krishnaveni Degree College :: Narasaraopet Page No. : 74


Object Oriented Programming using Java UNIT - II

System.out.println("The both objects are same");


else
System.out.println("The both objects are not same");
System.out.println("The class is : "+obj.getClass());
}
}

Binding: Connecting a method call to the method body is known as binding.


There are two types of binding
1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).
Static Binding: Static Binding is also known as Early Binding. When the type
of the object is determined at compile time then it is known as static binding.
Dynamic Binding: Dynamic Binding is also known as Late Binding. When the
type of the object is determined at run time then it is known as dynamic
binding.

Method Overriding : If subclass has the same method as declared in the


parent class and if subclass provides the different implementation of the
method that is provided in its parent class then it is known as method
overriding.
// Program to demonstrate Method Overriding
import java.util.Scanner;
class Circle
{
double dim1;
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any radius: ");
dim1=input.nextDouble();
}
double area()
{
return dim1*dim1*3.1415;

Krishnaveni Degree College :: Narasaraopet Page No. : 75


Object Oriented Programming using Java UNIT - II

}
}
class Rectangle extends Circle
{
double dim2;
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and breadth of the Rectangle: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class MethodOverrideEx
{
public static void main(String args[])
{
Circle c = new Circle();
c.getdim();
System.out.println("Area of circle is " + c.area());
Rectangle r = new Rectangle();
r.getdim();
System.out.println("Area of rectangle is " + r.area());
}
}

Abstract class: A class which contains the abstract keyword in its declaration
is known as abstract class. Abstract classes may or may not contain abstract
methods, i.e., methods without body ( public void get(); ) But, if a class has at
least one abstract method, then the class must be declared abstract. If a class
is declared abstract, it cannot be instantiated i.e object cant be created for

Krishnaveni Degree College :: Narasaraopet Page No. : 76


Object Oriented Programming using Java UNIT - II

abstract class. To use an abstract class, it must be inherited it from another


class, provide implementations to the abstract methods in it.
// Program to demonstrate abstract methods and classes.
abstract class Figgur
{
double dim1;
double dim2;
Figgur(double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area();
}
class Rectang extends Figgur
{
Rectang(double a, double b)
{
super(a, b);
}
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triang extends Figgur
{
Triang(double a, double b)
{
super(a, b);
}
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;

Krishnaveni Degree College :: Narasaraopet Page No. : 77


Object Oriented Programming using Java UNIT - II

}
}
class AbstractAreas
{
public static void main(String args[])
{
Rectang r = new Rectang(9, 5);
System.out.println("Area of Rectangle is " + r.area());
Triang t = new Triang(10, 8);
System.out.println("Area of triangle is " + t.area());
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 78


Object Oriented Programming using Java UNIT - III

Interface: Interfaces VS Abstract classes, defining an interface,


implement interfaces, accessing implementations through interface
references, extending interface;
Packages: Defining, creating and accessing a package, understanding
CLASSPATH, importing packages.
Exception Handling: Benefits of exception handling, the classification of
exceptions, exception hierarchy, checked exceptions and unchecked
exceptions, usage of try, catch, throw, throws and finally, rethrowing
exceptions, exception specification, built in exceptions, creating own
exception sub classes.

Interfaces: An interface is defined much like a class. It has static constants


and abstract methods only. The interface in java is a mechanism to achieve
fully abstraction. The general form of an interface is
interface interface_name
{
type final-varname1 = value;
type final-varname2 = value;
// ...
type final-varnameN = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
}
Points to remember:
1. An interface does not contain any constructors.
2. All of the methods in an interface are abstract.
3. An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final.
4. An interface is not extended by a class; it is implemented by a class.
5. An interface can extend multiple interfaces.

Interfaces VS Abstract classes: Abstract class and interface both are used
to achieve abstraction where we can declare the abstract methods. Abstract
Krishnaveni Degree College: Narasaraopet Page No.: 79
Object Oriented Programming using Java UNIT - III

class and interface both can't be instantiated. But there are many differences
between abstract class and interface that are given below.
S.No Interface Abstract class
1) Interface can have only abstract Abstract class can have abstract
methods. Since Java 8, it can and non-abstract methods.
have default and static methods
also.
2) Interface supports multiple Abstract class doesn't support
inheritance. multiple inheritance.
3) Interface has only static and final Abstract class can have final,
variables. non-final, static and non-static
variables.
4) Interface can't provide the Abstract class can provide the
implementation of abstract class. implementation of interface.

5) The interface keyword is used toThe abstract keyword is used to


declare interface. declare abstract class.
6) An interface can extend another An abstract class can extend
Java interface only. another Java class and
implement multiple Java
interfaces.
7) An interface can be implemented An abstract class can be
using keyword "implements". extended using keyword
"extends".
8) Members of a Java interface are A Java abstract class can have
public by default. class members like private,
protected, etc.
9) Example: Example:
public interface Drawable public abstract class Shape
{ {
void draw(); public abstract void draw();
} }

Implementing Interfaces: Once an interface has been defined, one or more


classes can implement that interface. To implement an interface, include the
implements clause in a class definition, and then create the methods required

Krishnaveni Degree College :: Narasaraopet Page No. : 80


Object Oriented Programming using Java UNIT - III

by the interface. The general form of a class that includes the implements
clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated
with a comma. If a class implements two interfaces that declare the same
method, then the same method will be used by clients of either interface. The
methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type
signature specified in the interface definition.
// Java program to implement interface
import java.io.*;
interface In1
{
final int a = 10;
void display();
}
class TestClass implements In1
{
public void display()
{
System.out.println("Geek");
}
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}

Accessing Implementations Through Interface References: We can


declare variables as object references that use an interface rather than a class.

Krishnaveni Degree College :: Narasaraopet Page No. : 81


Object Oriented Programming using Java UNIT - III

Any instance that implements the declared interface can be referred to by


such a variable. When you call a method through one of these references,
the correct version will be called based on the actual instance of the interface
being referred to. This process is similar to using a superclass reference to
access a subclass object. The following example calls the callback() method
via an interface reference variable:
//Java Program to access implementations through Interface References
interface Callback
{
void callback(int param);
}
class Client implements Callback
{
public void callback(int p)
{
System.out.println("callback called with " + p);
}
void aa()
{
System.out.println("hi.");
}
}
public class Main
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}

Interfaces Can Be Extended: One interface can inherit another by use of the
keyword extends. The syntax is the same as for inheriting classes. When a
class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance
chain. // Program to demonstrate one interface extending another interface.
import java.util.Scanner;

Krishnaveni Degree College :: Narasaraopet Page No. : 82


Object Oriented Programming using Java UNIT - III

interface DimInter2
{
void getDim();
}
interface AreaInter2 extends DimInter2
{
double areas();
}
class ExtendInter implements AreaInter2
{
double dim1;
double dim2;
public void getDim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any two dimensions: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
public double areas()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
public static void main(String args[])
{
ExtendInter r = new ExtendInter();
r.getDim();
System.out.println("Area is " + r.areas());
}
}

Packages: Packages are containers for classes that are used to keep the class
name space compartmentalized.

Defining a Package: To create a package simply include a package


command as the first statement in a Java source file. Any classes declared

Krishnaveni Degree College :: Narasaraopet Page No. : 83


Object Oriented Programming using Java UNIT - III

within that file will belong to the specified package. The package statement
defines a name space in which classes are stored. If the package statement
is omitted, the class names are put into the default package, which has no
name. The general form of the package statement is
Syntax: package pkg;
Here, pkg is the name of the package.
Ex: package MyPackage;
The above statement creates a package called MyPackage.

creating and accessing a package: Java uses file system directories to store
packages. For example, the .class files for any classes to be part of MyPackage
must be stored in a directory called MyPackage. Remember the directory
name must match the package name exactly. More than one file can include
the same package statement. The package statement simply specifies to
which package the classes defined in a file belong. To create a hierarchy of
packages simply separate each package name from the one above it by use
of a period. The general form of a multileveled package statement is
Syntax: package pkg1[.pkg2[.pkg3]];
Ex: package java.awt.image;
A package hierarchy must be reflected in the file system of the computer. For
example, a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment. Be sure to
choose your package names carefully. Package name cannot be renamed
without renaming the directory in which the classes are stored.
// Program to demonstrate Simple Package
package MyPack1;
import java.util.Scanner;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}

Krishnaveni Degree College :: Narasaraopet Page No. : 84


Object Oriented Programming using Java UNIT - III

void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the name and balance: ");
String name=input.next();
float bal =input.nextFloat();
Balance current = new Balance(name, bal);
current.show();
}
}
To compile java program which contains package statement
javac –d . demo.java
To
java -cp . MyPack1/AccountBalance1

understanding CLASSPATH: CLASSPATH specifies to Java run-time system


where to look for packages that are created. It can e done in 3 ways. They
are
1. By default, the Java run-time system uses the current working directory
as its starting point. Thus, if your package is in a subdirectory of the
current directory, it will be found easily.
2. The directory path or paths can be specified by setting the CLASSPATH
environmental variable.
3. The -classpath option with java and javac to specify the path to your
classes.

Krishnaveni Degree College :: Narasaraopet Page No. : 85


Object Oriented Programming using Java UNIT - III

Importing Packages: Packages are a good mechanism for separating


diferent classes from each other. All of the built-in Java classes are stored
in packages. No core Java classes are stored in the unnamed default package
and all of the standard classes are stored in some named package. The
import statement is used in the program when classes defined in the other
package are to be accessed. In a Java source file, import statements occur
immediately following the package statement if it exists and before any class
definitions. This is the general form of the import statement is
import pkg1 [.pkg2].(classname | *);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subpackage inside the outer package separated by a dot (.). There is no
practical limit on the depth of a package hierarchy, except that imposed by
the file system. Finally, specify either an explicit classname or a star (*), which
indicates that the Java compiler should import the entire packageor a
particular class. This code fragment shows both forms in use:
import java.util.Date;
import java.io.*;
All of the standard Java classes included with Java are stored in a package
called java. The basic language functions are stored in a package inside of
the java package called java.lang. Normally, you have to import every
package or class that you want to use, but since Java is useless without much
of the functionality in java.lang, it is implicitly imported by the compiler for
all programs. This is equivalent to the following line being at the top of all of
your programs:
import java.lang.*;

Exception Handling: Errors are mistakes in programs which may produce


incorrect output or may terminate the execution of the program abruptly or
even cause the system to crash. Depending upon when the errors are
detected the errors are broadly classified into two categories. They are
1. Compile time errors.
2. Run time errors.
Compile time errors: All syntax errors will be detected and displayed by the
java compiler, thus such errors are called Compile time errors. Common
Compile time Errors are
1. Missing semicolons

Krishnaveni Degree College :: Narasaraopet Page No. : 86


Object Oriented Programming using Java UNIT - III

2. Missing or mismatch of brackets in classes and methods


3. Misspelling of identifiers and keywords
4. Missing double quotes in strings
5. Use of undeclared variables
6. Incompatible types in assignments
7. Bad reference to objects
8. Use of = inplace of == operator
Run time errors: Although programs get compiled successfully they may
not execute. Such errors which occur at run time are identified by JVM and
they are called Run time Errors. Common Run time Errors are
Dividing an integer by zero
1. Accessing an element that is out of bounds of an array.
2. Trying to store a value into an array of an incomapatible class or type.
3. Trying to cast an instance of a class to one of its subclasses.
4. Attempting to use a negative size for an array
5. Accessing a character that is out of bounds of a string.

Benefits of Exception Handling: Following are the benefits of exception


handling
1. Using exception the main application logic can be separated out from
the code which may cause some unusual conditions.
2. When calling method encounters some error then the exception can
be thrown. This avoids crashing of the entire application abruptly.
3. The working code and the error handling code can be separated out
due to exception handling mechanism. Using exception handling,
various types of errors in the source code can be grouped together.
4. Due to exception handling mechanism, the errors can be propagated
up the method call stack i.e. problems occurring at the lower level can
be handled by the higher up methods.

The classification of exceptions: Java defines several types of exceptions


that relate to its various class libraries. Java also allows users to define their
own exceptions.

Krishnaveni Degree College :: Narasaraopet Page No. : 87


Object Oriented Programming using Java UNIT - III

Built-in Exceptions: Built-in exceptions are the exceptions that are available
in Java libraries. These exceptions are suitable to explain certain error
situations.
User-Defined Exceptions: Sometimes, the built-in exceptions in Java are not
able to describe a certain situation. In such cases, the user can also create
exceptions which are called ‘user-defined Exceptions’. The following steps
are followed for the creation of a user-defined Exception.
1. The user should create an exception class as a subclass of the Exception
class. Since all the exceptions are subclasses of the Exception class, the
user should also make his class a subclass of it. This is done as:
class MyException extends Exception
2. We can write a default constructor in his own exception class.
MyException(){}
3. We can also create a parameterized constructor with a string as a
parameter. We can use this to store exception details. We can call the
superclass(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
To raise an exception of a user-defined type, we need to create an object to
his exception class and throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;

Exception hierarchy: Java is an object-oriented language, and it has a lot of


built-in classes and packages. The lang package of Java provides classes that
are fundamental to the design of the Java language. For example,
the Object class is part of this package, which is the default parent class of
all Java classes. The root class of the Java exception is Throwable, which is a
subclass of the Object class. Exception and Error both the classes are derived

Krishnaveni Degree College :: Narasaraopet Page No. : 88


Object Oriented Programming using Java UNIT - III

from the Throwable class. Refer to the diagram given below to understand
the hierarchy of exceptions in Java along with their category of checked and
unchecked exceptions.

Checked exceptions and Unchecked exceptions: There are two types of


exceptions
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions: All exceptions other than Runtime Exceptions are known
as Checked exceptions as the compiler checks them during compilation to
see whether the programmer has handled them or not. If these exceptions
are not handled/declared in the program, it will give compilation error.
Examples of Checked Exceptions are
1. ClassNotFoundException
2. I/O Exception
3. SQLException
4. FileNotFoundException etc.
Unchecked Exceptions: Runtime Exceptions are also known as Unchecked
Exceptions as the compiler do not check whether the programmer has
handled them or not but it’s the duty of the programmer to handle these
exceptions and provide a safe exit. These exceptions need not be included in
any method’s throws list because compiler does not check to see if a method
handles or throws these exceptions.
Examples of Unchecked Exceptions:-
1. ArithmeticException
2. ArrayIndexOutOfBoundsException
3. NullPointerException
4. NegativeArraySizeException etc.

Krishnaveni Degree College :: Narasaraopet Page No. : 89


Object Oriented Programming using Java UNIT - III

Exception Handling Techniques: An exception is a problem that arises


during the execution of a program. When an Exception occurs the normal
flow of the program is disrupted and the program terminates abnormally.
The exception handling in java is one of the powerful mechanism to handle
the runtime errors so that normal flow of the application can be maintained.

The exception handling mechanism should perform the following tasks. They
are
The above tasks are divided into segments., one to detect errors and throw
exceptions and the other to catch exceptions and to take appropriate actions.
The pictorial representation is shown below

try Block: The try block contains a block of program statements within which
an exception might occur. A try block is always followed by a catch block,
which handles the exception that occurs in associated try block. Syntax of try
block
try{

Krishnaveni Degree College :: Narasaraopet Page No. : 90


Object Oriented Programming using Java UNIT - III

//statements that may cause an exception


}
catch Block: A catch block must be associated with a try block. The
corresponding catch block executes if an exception of a particular type
occurs within the try block. For example if an arithmetic exception occurs in
try block then the statements enclosed in catch block for arithmetic
exception executes.
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception-type e
{
//error handling code
}
Flow of try catch block
1. If an exception occurs in try block then the control of execution is passed
to the catch block from try block. The exception is caught up by the
corresponding catch block.
2. After the execution of catch blocks, the control of execution returns to
the next statement after the catch block.

//Program to demonstrate an example of Try catch in Java


class Example1
{
public static void main(String args[])
{
int a=10, b=5, c=5,x,y;
try
{
x=a/(b-c);
System.out.println("Try block message");
}
catch (ArithmeticException e)
{
System.out.println("Error: Don't divide a number by zero");

Krishnaveni Degree College :: Narasaraopet Page No. : 91


Object Oriented Programming using Java UNIT - III

}
System.out.println("I'm out of try-catch block in Java.");
y=a/(b+c);
System.out.println("y=”+y ;
}
}
OUTPUT:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.
y=1
Multiple catch blocks in Java: A try block can have any number of catch
blocks.
Syntax
try
{
// Protected code
}
catch(ExceptionType1 e1)
{
// Catch block of error e1
}
catch(ExceptionType2 e2)
{
// Catch block of error e2
}
catch(ExceptionType3 e3)
{
// Catch block of error e3
}
1. A catch block that is written for catching the class Exception can catch all
other exceptions.

Syntax:
catch(Exception e){
//This catch block catches all the exceptions
}

Krishnaveni Degree College :: Narasaraopet Page No. : 92


Object Oriented Programming using Java UNIT - III

2. If multiple catch blocks are present in a program then the above


mentioned catch block should be placed at the last as per the exception
handling best practices.
3. If the try block is not throwing any exception, the catch block will be
completely ignored and the program continues.
4. If the try block throws an exception, the appropriate catch block (if one
exists) will catch it.
 catch(ArithmeticException e) is a catch block that can catch
ArithmeticException
 catch(NullPointerException e) is a catch block that can catch
NullPointerException
5. All the statements in the catch block will be executed and then the
program continues.

// Program to demonstrate multiple catch blocks


public class MulCatchBlocks
{
public static void main(String args[])
{
int a[] = {2, 5};
int b=5;
try
{
int x =a[0]/(b-a[1]);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
System.out.println("exceptioon:"+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index error ");
System.out.println("exception:"+e);
}
int y = a[1]/a[0];

Krishnaveni Degree College :: Narasaraopet Page No. : 93


Object Oriented Programming using Java UNIT - III

System.out.println("y="+y);
}
}
OUTPUT:
Division by Zero
exceptioon:java.lang.ArithmeticException: / by zero
y=2
Nested try catch: The try catch blocks can be nested. One try-catch block
can be present in the another try’s body. This is called Nesting of try catch
blocks. Each time a try block does not have a catch handler for a particular
exception, the parent try block’s catch handlers are inspected for a match. If
no catch block matches, then the java run-time system will handle the
exception.
//Program to demonstrate an example of nested Try catch in Java
class Example1
{
public static void main(String args[])
{
int a[] = {5,5 };
int x,y,z;
try
{
try
{
x=a[0]/(a[1]-a[2]);
System.out.println("x="+x);
System.out.println("Inner Try block message");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array elements out of bounds");
}
System.out.println("I am out of inner try-catch block ");
y=a[0]/(a[1]-a[0]);
System.out.println("y="+y);
System.out.println("Outer Try block message");
}

Krishnaveni Degree College :: Narasaraopet Page No. : 94


Object Oriented Programming using Java UNIT - III

catch (ArithmeticException e)
{
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I am out of outer try-catch block");
z=a[0]/(a[0]+a[1]);
System.out.println("z="+z);
}
}
OUTPUT:
Array elements out of bounds
I am out of inner try-catch block
Error: Don't divide a number by zero
I am out of outer try-catch block
z=0

throw keyword: The Java throw keyword is used to explicitly throw an


exception. The throw keyword is mainly used to throw custom exception.
Syntax: throw exception;
//Program to demonstrate usage of throw keyword
class Exception2
{
public static void main(String args[])
{
int num1=12, num2=0;
try
{
if (num2 == 0)
throw new ArithmeticException("Denominator cant be zero");
else
System.out.println("Result="+num1/num2);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 95


Object Oriented Programming using Java UNIT - III

User defined exception in java: User defined exceptions in java are also
known as Custom exceptions. Most of the times when we are developing
an application in java, we often feel a need to create and throw our own
exceptions. These exceptions are known as User defined or Custom
exceptions.
//Program to demonstate user defined exception
class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}
class CustomException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z = (float)x/(float)y;
if (z<0.01)
throw new MyException("Number is too small");
}
catch(MyException e)
{
System.out.println("Hi this is my custom catch block") ;
System.out.println(e) ;
}
}
}

throws: If a method is capable of causing an exception that it does not


handle, it must specify this behavior so that callers of the method can
handle themselves against that exception. This can be done by including a

Krishnaveni Degree College :: Narasaraopet Page No. : 96


Object Oriented Programming using Java UNIT - III

throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw. All other exceptions that a method
can throw must be declared in the throws clause. If they are not, a compile-
time error will result.
This is the general form of a method declaration that includes a throws
clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.
//Program to demonstrate checked exceptions
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FileNotFound_Demo
{
public static void main(String args[]) throws FileNotFoundException
{
File file = new File("C:\\CallByValue.java");
FileReader fr = new FileReader(file);
}
}
//Program to demonstrate checked exceptions
public class Unchecked_Demo
{
public static void main(String args[])
{
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
finally: When an exception is thrown we teriminate the method abruptly
without completing it. For example, if a method opens a file upon entry and
closes it upon exit, then you will not want the code that closes the file to be
bypassed by the exception-handling mechanism. The finally keyword is

Krishnaveni Degree College :: Narasaraopet Page No. : 97


Object Oriented Programming using Java UNIT - III

designed to address this problem. finally creates a block of code that will
be executed after a try/catch block has completed and before the code
following the try/catch block. The finally block will execute whether or not
an exception is thrown. If an exception is thrown, the finally block will
execute even if no catch statement matches the exception. The finally
clause is optional. However, each try statement requires at least one catch
or a finally clause.
try{
//block of statements
}
finally
{
}
Or
try
{
//block of statements
}
catch()
{
}
finally
{
}
// program used to show the use of finally block
public void division(int num1, int num2)
{
try
{
System.out.println(num1/num2);
}
catch(ArithmeticException e)
{
. System.out.println(e);
}
finally
{

Krishnaveni Degree College :: Narasaraopet Page No. : 98


Object Oriented Programming using Java UNIT - III

System.out.println("Finally will always execute.");


}
System.out.println("Remaining code after exception handling.");
}
}
public class FinallyExceptionExample2
{
public static void main(String args[])
{
ArithmaticTest obj = new ArithmaticTest();
obj.division(20, 0);
}
}
OUTPUT:
java.lang.ArithmeticException: / by zero
Finally will always execute.
Remaining code after exception handling.

Rethrowing exceptions: Sometimes we may need to rethrow an exception


in Java. If a catch block cannot handle the particular exception it has caught,
we can rethrow the exception. The rethrow expression causes the originally
thrown object to be rethrown. When expection is rethrown from the catch
block then any catch blocks for the enclosing try block have an opportunity
to catch the exception.
Syntax
catch(Exception e)
{
System.out.println("An exception was thrown");
throw e;
}
Example
public class RethrowException
{
public static void test1() throws Exception
{
System.out.println("The Exception in test1() method");

Krishnaveni Degree College :: Narasaraopet Page No. : 99


Object Oriented Programming using Java UNIT - III

throw new Exception("thrown from test1() method");


}
public static void test2() throws Throwable
{
try
{
test1();
}
catch(Exception e)
{
System.out.println("Inside test2() method");
throw e;
}
}
public static void main(String[] args) throws Throwable
{
try
{
test2();
}
catch(Exception e)
{
System.out.println("Caught in main");
}
}
}

Exception specification: An exception specification is a contract between


the function and the rest of the program. It is a guarantee that the function
will not throw any exception not listed in its exception specification.
The exception specification uses an additional keyword, throws,
followed by a list of all the potential exception types. So your method
definition might look like this:
void f() throws TooBig, TooSmall, DivZero
{
---
}

Krishnaveni Degree College :: Narasaraopet Page No. : 100


Object Oriented Programming using Java UNIT - III

//Program to demonstate exception specification


class TooBig extends Exception
{
public TooBig(String s)
{
super(s);
}
}
class TooSmall extends Exception
{
public TooSmall(String s)
{
super(s);
}
}
class DivZero extends Exception
{
public DivZero(String s)
{
super(s);
}
}
class ExcepSpec
{
void f(int x, int y) throws TooBig, TooSmall, DivZero
{
if(y==0)
throw new DivZero("Denominator is Zero");
else
if(y<0.00001)
throw new TooSmall("Denominator is too Small");
else
if(y>10000)
throw new TooBig("Denominator is too Large");
else
{

Krishnaveni Degree College :: Narasaraopet Page No. : 101


Object Oriented Programming using Java UNIT - III

float res = x/y;


System.out.println("Result after Division"+res);
}
}
public static void main(String args[])
{
ExcepSpec es=new ExcepSpec();
try
{
int x=100, y=10;
es.f(x,y);
}
catch(Exception e)
{
System.out.println("Hi this is my custom catch block") ;
System.out.println(e) ;
}
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 102


Object Oriented Programming using Java UNIT - IV

Multithreading: Differences between multiple processes and multiple


threads, thread states, thread life cycle, creating threads, interrupting
threads, thread priorities, synchronizing threads, inter thread
communication.
Stream based I/O (java.io) – The Stream classes-Byte streams and
Character streams, Reading console Input and Writing Console Output,
File class, Reading and writing Files, The Console class, Serialization

Multithreading: Java provides built-in support for multithreaded


programming. A multithreaded program contains two or more parts that can
run concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
Multitasking is the ability to run several programs simultaneously. All modern
operating systems support multitasking. There are two distinct types of
multitasking. They are
1. Process-based multitasking( known as multitasking)
2. Thread-based multitasking( known as multithreading)

Differences between multiple processes and multiple threads


S.No. Multiple processes Multiple threads
1. An executing program is called a A thread is a small part of a
process. program which can run
concurrently.
2. In process based multitasking two In thread based multitasking
or more processes can be run two or more threads can be
concurrently. run concurrently.
3. In process based multitasking a In thread based multitasking a
program is the smallest unit. thread is the smallest unit.
4. Processes are referred as Threads are referred
heavyweight tasks since each as lightweight processes since
process requires its own address all threads in a program share
space. same address space.
5. Process to Process communication Thread to Thread
is expensive communication is not
expensive.
6. Process based Multitasking is Thread based Multitasking is
controlled by operating System. controlled by Java(JVM)
Krishnaveni Degree College: Narasaraopet Page No.: 103
Object Oriented Programming using Java UNIT - IV

7. Multitasking is a generalized form Multithreading is a specialized


of multithreading. form of multitasking
8. Typing a program in a text editor, Calculating sum of matrices,
printing another text file, Playing difference of matrices and
music using windows media player finding product of matrices
are three processes which can be can be done by executing
executed concurrently. three threads in parallel.

Threads States: A thread can exist in a number of different statesThe current


state of a thread is obtained by calling the getState( ) method defined by
Thread.
Thread.State getState( )
S.No. State Description
1. BLOCKED A thread that has suspended execution
because it is waiting to acquire a lock.
2 NEW A thread that has not begun execution.
3. RUNNABLE A thread that either is currently executing or
will execute when it gains access to the CPU.
4. TERMINATED A thread that has completed execution.
5. TIMED_WAITING A thread that has suspended execution for a
specified period of time, such as when it has
called sleep( ). This state is also entered
when a timeout version of wait( ) or join( ) is
called.
6. WAITING A thread that has suspended execution
because it is waiting for some action to
occur. For example, it is waiting because of a
call to a non-timeout version of wait( ) or
join( ).

Thread life cycle: The life cycle of a thread in Java refers to the various states
of a thread that a thread goes through. The figure below shows multiple
states of the thread t under goes during its lifecycle.

Krishnaveni Degree College :: Narasaraopet Page No. : 104


Object Oriented Programming using Java UNIT - IV

New Thread: When a new thread is created, it is in the new state. When a
thread lies in the new state, its code is yet to be run and hasn’t started to
execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In
this state, a thread might actually be running or it might be ready to run at
any instant of time. It is the responsibility of the thread scheduler to give the
thread, time to run.
Blocked: The thread will be in blocked state when it is trying to acquire a lock
but currently the lock is acquired by the other thread. The thread will move
from the blocked state to runnable state when it acquires the lock.
Waiting state: The thread will be in waiting state when it calls wait() method
or join() method. It will move to the runnable state when other thread will
notify or that thread will be terminated.
Timed Waiting: A thread lies in a timed waiting state when it calls a method
with a time-out parameter. A thread lies in this state until the timeout is
completed or until a notification is received. For example, when a thread calls
sleep or a conditional wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following
reasons:
 Because it exits normally. This happens when the code of the thread
has been entirely executed by the program.
 Because there occurred some unusual erroneous event, like a
segmentation fault or an unhandled exception.

Krishnaveni Degree College :: Narasaraopet Page No. : 105


Object Oriented Programming using Java UNIT - IV

Creating a Thread: Java defines two ways by which new threads can be
created.
1. By extending the Thread class.
2. By implementing the Runnable interface.
Extending Thread class: A new Thread can be created by a new class that
extends Thread class and create an object of that class. The extending class
must override run() method which is the entry point of new thread.
// Program demonstrating creation of new thread by extending Thread class
class ExtendThread extends Thread
{
ExtendThread(String name)
{
super(name);
}
public void run()
{
System.out.println(this.getName()+" started running..");
}
}
class MyThreadDemo
{
public static void main( String args[] )
{
ExtendThread et = new ExtendThread("New Thread");
et.start();
}
}
Implementing the Runnable Interface: The easiest way to create a thread is
to create a class that implements the runnable interface. After implementing
runnable interface, the class needs to implement the run() method.
// Program demonstrating creation of new thread by implements Runnable
Interface
class RunnableThread implements Runnable
{
String thname;
RunnableThread(String name)
{

Krishnaveni Degree College :: Narasaraopet Page No. : 106


Object Oriented Programming using Java UNIT - IV

thname=name;
}
public void run()
{
System.out.println(thname+" started running..");
}
}
class MyThreadDemo
{
public static void main( String args[] )
{
RunnableThread rt = new RunnableThread("New Thread");
Thread t = new Thread(rt);
t.start();
}
}

Interrupting Threads: If any thread is in sleeping or waiting state (i.e. sleep()


or wait() is invoked), calling the interrupt() method on the thread, breaks out
the sleeping or waiting state throwing InterruptedException. If the thread is
not in the sleeping or waiting state, calling the interrupt() method performs
normal behaviour and doesn't interrupt the thread but sets the interrupt flag
to true. There are 3 methods provided by the Thread class for thread
interruption. They are
1. public void interrupt()
2. public static boolean interrupted()
3. public boolean isInterrupted()

// Java Program to demo Interrupting a Thread


class InterruptingThread extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("Task is being performed");

Krishnaveni Degree College :: Narasaraopet Page No. : 107


Object Oriented Programming using Java UNIT - IV

}
catch(InterruptedException e)
{
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[])
{
InterruptingThread t1=new InterruptingThread1();
t1.start();
try
{
t1.interrupt();
}
catch(Exception e)
{
System.out.println("Exception handled "+e);}
}
}

Thread Priorities: Thread priorities are used to decide which thread should
be allowed to run first. In theory, higher-priority threads get more CPU time
than lower-priority threads. In practice, the amount of CPU time that a thread
gets often depends on several factors besides its priority. To set a thread’s
priority, the setPriority( ) method is used and obtain the current priority
setting by calling the getPriority( ) method of Thread. The syntax of these
methods are
final void setPriority(int level)
final int getPriority( )
// Program demonstrating Setting and getting priorities of Threads
class MyThread extends Thread
{
MyThread(String name)
{
super(name);
System.out.println("Default Priority of "+this.getName() + ": " +
this.getPriority());

Krishnaveni Degree College :: Narasaraopet Page No. : 108


Object Oriented Programming using Java UNIT - IV

}
public void run()
{
System.out.println(this.getName()+" started running..");
System.out.println("Priority of "+this.getName() + "is set to: " +
this.getPriority());
System.out.println(this.getName() + " exiting.");
}
}
class MyThreadDemo
{
public static void main( String args[] )
{
MyThread et1 = new MyThread("Thread1");
et1.start();
et1.setPriority(10);
MyThread et2 = new MyThread("Thread2");
et2.start();
et2.setPriority(5);
MyThread et3 = new MyThread("Thread3");
et3.start();
et3.setPriority(1);
}
}

Synchronizing Threads: 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 is achieved is called
synchronization. Synchronization in java is the capability to control the
access of multiple threads to any shared resource. It is a better option when
only one thread has to access the shared resource at a time. Java uses the
concept of monitor to implement synchronization. A monitor can be
assumed as a very small box that can hold only one thread at a time. Once a
thread enters a monitor, all other threads must wait until that thread exits
the monitor. In Java there is no class “Monitor” but each object has its own
implicit monitor that is automatically entered when one of the object’s
synchronized methods is called. Once a thread is inside a synchronized

Krishnaveni Degree College :: Narasaraopet Page No. : 109


Object Oriented Programming using Java UNIT - IV

method, no other thread can call any other synchronized method on the
same object.
Synchronization of threads in java can be achieved in two ways. They are
1. Synchronized method.
2. Synchronized block.
Both of these ways use the synchronized keyword.
Synchronized method: If any method is prefixed with a word synchronized
then it is known as synchronized method. When a thread invokes a
synchronized method, it automatically calls its implicit monitor for that object
and releases it only when the thread completes its task.
// Program to demonstrate Synchronized method
import java.util.*;
class Reserve extends Thread
{
int available;
int wanted=1;
Reserve(int n)
{
available=n;
}
synchronized public void run()
{
String name= Thread.currentThread().getName();
System.out.println("Total no of seats available="+available);
if(available>=wanted)
{
System.out.println(wanted+ "breath is allocated to "+name);
available--;
}
else
System.out.println(wanted+ "breaths are not available for "+name);
}
}
public class SynMethod
{
public static void main(String args[]) throws Exception
{

Krishnaveni Degree College :: Narasaraopet Page No. : 110


Object Oriented Programming using Java UNIT - IV

int n;
Scanner input = new Scanner(System.in);
System.out.print ("Enter No of seats availalabe for reservation:");
n=input.nextInt();
Reserve obj=new Reserve(n);
Thread t1 =new Thread(obj,"A");
Thread t2 =new Thread(obj,"B");
t1.start();
t2.start();
}
}

Synchronized block: Synchronized block can be used only when part of the
method is to be synchronized. If all the code of a method is placed in the
synchronized block then it will work same as the synchronized method.
Scope of synchronized block is smaller than the method.
// Program to demonstrate Synchronized method
import java.util.*;
class Reserve extends Thread
{
int available;
int wanted=1;
Reserve(int n)
{
available=n;
}
synchronized public void run()
{
String name= Thread.currentThread().getName();
System.out.println("Total no of seats available="+available);
synchronized(this)
{
if(available>=wanted)
{
System.out.println(wanted+ "breath is allocated to "+name);
available--;
}

Krishnaveni Degree College :: Narasaraopet Page No. : 111


Object Oriented Programming using Java UNIT - IV

else
System.out.println(wanted+ "breaths are not available for "+name);
}
}
}
public class SynBlock
{
public static void main(String args[]) throws Exception
{
int n;
Scanner input = new Scanner(System.in);
System.out.print("Enter No of seats availalabe for reservation:");
n=input.nextInt();
Reserve obj=new Reserve(n);
Thread t1 =new Thread(obj,"A");
Thread t2 =new Thread(obj,"B");
t1.start();
t2.start();
}
}

Inter thread communication: Modern way of suspending and resuming


threads uses the concept of Inter Thread Communication. Inter-thread
communication in java is the feature which allows synchronized threads to
communicate with each other. The wait(), notify(), notifyAll() of Object class
are used for Inter-thread communication. These methods can be called only
within a synchronized block or synchronized method .
 wait() tells calling thread to give up monitor and go to sleep until some
other thread enters the same monitor and call notify.
 notify() wakes up a thread that called wait() on same object.
 notifyAll() wakes up all the thread that called wait() on same object.

Stream based I/O (java.io): A simple Java program uses variables, arrays or
objects for storing data. This approach works fine for small data. The
problems with this approach are
1. The data is lost when the program is terminated.
2. It is difficult to handle large amounts of data.

Krishnaveni Degree College :: Narasaraopet Page No. : 112


Object Oriented Programming using Java UNIT - IV

The solution to above two problems is to store large data in a file. File stores
the data permanently on a secondary storage device. Java provides a
standard way of reading data from file and writing data to files. The java.io
package contains all classes that are need to perform input and output
operations on files.
A file is a collection of related records on the disk. A record is a group
of logically related fields. A field is a group of characters. Characters in java
are Unicode characters which uses two bytes to store each character. Storing
and managing data on files is known as file processing.

Data Representation in java


Stream: A stream can be defined as a sequence of data flowing form source
to destination. In java, 3 streams are created for us automatically. All these
streams are attached with console.
1) System..out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
//Program to demonstrate standard Streams
import java.io.*;
public class StreamEx
{
public static void main(String args[]) throws IOException
{
System.out.print("Enter any character: ");

Krishnaveni Degree College :: Narasaraopet Page No. : 113


Object Oriented Programming using Java UNIT - IV

int i=System.in.read();//returns ASCII code of 1st character


if(i!=-1)
System.out.println("Entered character is : "+(char)i);
else
System.err.println("Error message: Cant Read");
}
}

The Stream classes: A stream can be defined as a sequence of data flowing


form source to destination. Java defines two types of stream. They are
1. Byte Streams and
2. Character Streams.

Byte Streams: Byte streams provide a convenient means for handling input
and output of bytes. Byte streams are used while reading or writing binary
data. Byte Stream Classes are divided into InputStream and OutputStream.
These are defined as abstract classes and has several concrete subclasses.
The abstract classes InputStream and OutputStream define several key
methods that the other stream classes implement. Subclasses of InputStream
and OutputStream are

Krishnaveni Degree College :: Narasaraopet Page No. : 114


Object Oriented Programming using Java UNIT - IV

Character Streams: Character streams provide a convenient means for


handling input and output of characters. They use Unicode and, therefore,
can be internationalized. When text files are to be processed character
streams are more efficient than byte streams. The original version of Java
(Java 1.0) does not include character streams. Character Stream Classes are
divided into Reader and Writer. These are defined as abstract classes and
have several concrete subclasses. The abstract classes Reader and Writer
define several key methods that the other stream classes implement.
Subclasses of Reader and Writer are

Krishnaveni Degree College :: Narasaraopet Page No. : 115


Object Oriented Programming using Java UNIT - IV

Reading console Input and Writing Console Output: Creates a Scanner


object to read from the standard input (console). Prints a message to the
console using System.out.println().
// Java Program to read Console Input and write Console Output
import java.util.Scanner;
public class ConsoleIOExample
{
public static void main(String[] args)
{
// Reading input from console
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read a line of input
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer input
// Writing output to console
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Closing the scanner

Krishnaveni Degree College :: Narasaraopet Page No. : 116


Object Oriented Programming using Java UNIT - IV

scanner.close();
}
}

File class: The File class in Java is used to handle operations related to files
and directories. It provides methods to create, delete, query, and manipulate
files and directories on the file system.
// Java Program to Demo File Class Usage
import java.io.File;
import java.io.IOException;
public class FileExample
{
public static void main(String[] args)
{
File file = new File("example.txt");
try
{
if (file.createNewFile())
System.out.println("File created: " + file.getName());
else
System.out.println("File already exists.");
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
}
catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Console class: In Java, the Console class provides methods for reading input
and writing output directly from the console, which is typically used in

Krishnaveni Degree College :: Narasaraopet Page No. : 117


Object Oriented Programming using Java UNIT - IV

command-line based applications where interaction with the user occurs


through the terminal or command prompt.
// Java Program to Demo Console Class Usage
import java.io.Console;
public class ConsoleExample
{
public static void main(String[] args)
{
Console console = System.console();
if (console != null)
{
String name = console.readLine("Enter your name: ");
char[] password = console.readPassword("Enter your password: ");
console.printf("Hello, %s!\n", name);
console.printf("Your password is: %s\n", new String(password));
} else
{
System.out.println("Console is not available.");
}
}
}

Serialization: Serialization in Java refers to the process of converting an


object into a stream of bytes so that it can be easily stored into a file, sent
over a network, or persisted in a database. At a later time, you may restore
these objects by using the process of deserialization.
Serialization is also needed to implement Remote Method Invocation
(RMI). RMI allows a Java object on one machine to invoke a method of a Java
object on a different machine. An object may be supplied as an argument to
that remote method. The sending machine serializes the object and transmits
it. The receiving machine deserializes it.

import java.io.*;
class Employee implements Serializable
{
private String name;
private int age;

Krishnaveni Degree College :: Narasaraopet Page No. : 118


Object Oriented Programming using Java UNIT - IV

private transient double salary;


public Employee(String name, int age, double salary)
{
this.name = name;
this.age = age;
this.salary = salary;
}
public String toString()
{
return "Employee{name='" + name + "', age=" + age + ", salary="
+ salary + '}';
}
}
public class SerializationExample
{
public static void main(String[] args)
{
Employee emp = new Employee("John Doe", 30, 50000.0);
try {
FileOutputStream fileOut =
new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(emp);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser");
} catch (IOException e)
{
e.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee empFromFile = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Employee:");

Krishnaveni Degree College :: Narasaraopet Page No. : 119


Object Oriented Programming using Java UNIT - IV

System.out.println(empFromFile);
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 120


Object Oriented Programming using Java UNIT - IV

GUI Programming with Swing- Introduction, MVC architecture,


components, containers. Understanding Layout Managers - Flow
Layout, Border Layout, Grid Layout, Card Layout, Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources,
Event Listeners, Event classes, Handling mouse and keyboard events,
Adapter classes, Inner classes, Anonymous Inner classes.

GUI Programming in Java: Graphical user Interface Applications in java can


be created using two frame works. They are
1. Abstract Window Toolkit(AWT)
2. Swings
Difference between AWT and Swing in java
S.No AWT Swing
1. AWT stands for Abstract Swing is a part of Java
Window Toolkit. Foundation Class (JFC).
2. AWT components are heavy Swing components are light
weight. weight.
3. AWT components are Swing components are
platform dependent so there platform independent so
look and feel there look and feel remains
changes according to OS. constant.
4. Awt components requries Swing components requries
java.awt package javax.swing package
5. AWT is not based upon Swing is based upon
MVC(Model View Controller) MVC(Model View Controller)
6. AWT components are not very Swing components are better
good in look and feel as in look and feel as compared
compared to Swing to AWT.
components.

Introduction: Java's original graphical user interface (GUI) system was called
the Abstract Window Toolkit (AWT). The main issue with AWT was that it
relied on platform-specific components. This approach led to several
problems. They are
1. Components looked and behaved differently on different platforms.
2. The appearance of components could not be easily changed.
3. Heavyweight components (those using native code) had limitations,
such as always being opaque.
Krishnaveni Degree College: Narasaraopet Page No.: 121
Object Oriented Programming using Java UNIT – V

These problems conflicted with Java's goal of "write once, run anywhere."
Swings was developed to overcome the deficiencies of AWT. It was
introduced in 1997 as part of the Java Foundation Classes (JFC). Swings
allowed more flexible and consistent GUIs in Java.

MVC Architecture: In java visual components have three parts:


1. How it looks.
2. How it reacts to users.
3. The information it holds.
MVC architecture is used to implement a component. The full form of MVC
is Model-View-Controller. The Model-View-Controller architecture manages
these parts:
 Model: Stores the component's information (like if a checkbox is
checked).
 View: Controls how it looks on the screen.
 Controller: Handles user actions and updates the model.
When you click a checkbox, the controller updates the model, and the view
changes. In Swing, the view and controller are combined into one unit called
the UI delegate. This is called the Model-Delegate or Separable Model
architecture. Swing is based on MVC but uses this simpler version.

Components and Containers: A Swing GUI consists of two key items:


components and containers. However, this distinction is mostly conceptual
because all containers are also components. The difference between the two
is found in their intended purpose: As the term is commonly used, a
component is an independent visual control, such as a push button or slider.
A container holds a group of components. Thus, a container is a special type
of component that is designed to hold other components. Furthermore, in
order for a component to be displayed, it must be held within a container.
Thus, all Swing GUIs will have at least one container. Because containers are
components, a container can also hold other containers. This enables Swing
to define what is called a containment hierarchy, at the top of which must be
a top-level container.

Components: In general, Swing components are derived from the


JComponent class. JComponent provides the functionality that is common

Krishnaveni Degree College :: Narasaraopet Page No. : 122


Object Oriented Programming using Java UNIT – V

to all components. For example, JComponent supports the pluggable look


and feel. JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT
component. All of Swing’s components are represented by classes defined
within the package javax.swing. Examples of class names for Swing
components are JApplet, JButton , JCheckBox etc. All component classes
begin with the letter J. For example, the class for a label is JLabel; the class
for a push button is JButton; and the class for a scroll bar is JScrollBar.

Containers: Swing defines two types of containers.


1. The first are top-level containers. Examples of top-level containers are
JFrame, JApplet, JWindow, and JDialog. These containers do not inherit
JComponent. They inherit from AWT classes such as Component and
Container. These are heavyweight components since they use native
resources. As the name implies, a top-level container must be at the
top of a containment hierarchy i.e. it is not contained within any other
container. The one most commonly used for applications is JFrame. The
one used for applets is JApplet.
2. The second type of containers supported by Swing are lightweight
containers. Lightweight containers do inherit JComponent. An example
of a lightweight container is JPanel, which is a general-purpose
container. Lightweight containers are often used to organize and
manage groups of related components because a lightweight
container can be contained within another container. Thus lightweight
containers such as JPanel can be contained within other containers,
allowing for nested layouts.

LayoutManagers: The LayoutManagers are used to arrange components in


a particular manner. LayoutManager is an interface that is implemented by
all the classes of layout managers. Java has several predefined
LayoutManager classes. They are
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout

Krishnaveni Degree College :: Narasaraopet Page No. : 123


Object Oriented Programming using Java UNIT – V

FlowLayout: FlowLayout is the default layout manager of an applet. This is a


simple layout style. In this layout by default, components are laid out line-
by-line beginning at the upper-left corner. When a line is filled, layout
advances to the next line. A small space is left between each component,
above and below, as well as left and right.

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.

GridLayout: GridLayout arranges the components in a two-dimensional grid.


When an object of GridLayout is created, the number of rows and columns
are to be specified.

Krishnaveni Degree College :: Narasaraopet Page No. : 124


Object Oriented Programming using Java UNIT – V

CardLayout: The class CardLayout arranges each component in the


container as a card. Only one card is visible at a time, and the container acts
as a stack of cards.

GridBagLayout: GridBagLayout layout manager is the most powerful and


flexible of all the predefined layout managers but more complicated to use.
In GridLayout the components are arranged in a rectangular grid and each
component in the container is forced to be the same size. But in
GridBagLayout, components are arranged in rectangular grid but can have
different sizes and can occupy multiple rows or columns.

Krishnaveni Degree College :: Narasaraopet Page No. : 125


Object Oriented Programming using Java UNIT – V

Event Delegation Model: The event delegation model is a modern


approach to handling events in Java. Its concept is quite simple: a source
generates an event and sends it to one or more listeners. In this scheme, the
listener simply waits until it receives an event. Once an event is received, the
listener processes the event and then returns.
Advantages:
1. Event processing logic is separate from the user interface logic.
2. Only registered listeners receive notifications, avoiding unnecessary
event handling.
Listeners must register with a source to receive event notifications.
Notifications are sent only to listeners that have registered, making event
handling more efficient. This model provides a clean, efficient way to handle
events in Java applications.
Components of Event Handling:- Event handling has three main
components,
1. Events : An event is a change of state of an object.
2. Events Source : Event source is an object that generates an event.
3. Event Listeners : A listener is an object that listens to the event. A
listener gets notified when an event occurs.

Events: In the delegation model, an event is an object that describes a state


change in a source. An event can be generated when a person interacting
with the elements in a graphical user interface. Some of the activities that
cause events to be

Krishnaveni Degree College :: Narasaraopet Page No. : 126


Object Oriented Programming using Java UNIT – V

generated are pressing a button, entering a character via the keyboard,


selecting an item in a list, and clicking the mouse. Events may also occur that
are not directly caused by interactions with a user interface. For example, an
event may be generated when a timer expires, a counter exceeds a value, a
software or hardware failure occurs, or an operation is completed.

Event Sources: A source is an object that generates an event. Event occurs


when the internal state of that object changes in some way. Sources may
generate more than one type of event. A source must register listeners in
order for the listeners to receive notifications about a specific type of event.
Each type of event has its own registration method. For example, the method
that registers a keyboard event listener is called addKeyListener( )

Event Listeners: 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 about specific types of events.
Second, it must implement methods to receive and process these
notifications. The methods that receive and process events are defined in a
set of interfaces found in java.awt.event. For example, the
MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved.

Event Classes: At the root of the Java event class hierarchy is EventObject,
which is in java.util. It is the superclass for all events. The class AWTEvent,
defined within the java.awt package, is a subclass of EventObject. It is the
superclass (either directly or indirectly) of all AWT-based events used by the
delegation event model.
Main Event Classes in java.awt.event are
1. KeyEvent Generated when input is received from the keyboard.
2. MouseEvent Generated when the mouse is dragged, moved, clicked,
pressed, or released also generated when the mouse enters or exits a
component
The KeyEvent Class: A KeyEvent is generated when keyboard input occurs.
There are three types of key events, which are identified by these integer
constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two
events are generated when any key is pressed or released. The last event
occurs only when a character is generated. Remember, not all keypresses

Krishnaveni Degree College :: Narasaraopet Page No. : 127


Object Oriented Programming using Java UNIT – V

result in characters. For example, pressing SHIFT does not generate a


character.
The MouseEvent Class: There are different types of mouse events. The
MouseEvent class defines the following integer constants that can be used
to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a
component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.

//Program to demonstrate keyboard events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*< applet code="Test" width=300, height=100 > */
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{

Krishnaveni Degree College :: Narasaraopet Page No. : 128


Object Oriented Programming using Java UNIT – V

msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}

//Program to demonstrate Mouse events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse1" width=500 height=500>
</applet>
*/
public class Mouse1 extends Applet
implements MouseListener,MouseMotionListener
{
String msg="Mouse Events";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent m)
{
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)

Krishnaveni Degree College :: Narasaraopet Page No. : 129


Object Oriented Programming using Java UNIT – V

{
showStatus("Mouse Pressed");
repaint();
}
public void mouseReleased(MouseEvent m)
{
showStatus("Mouse Released");
repaint();
}
public void mouseMoved(MouseEvent m)
{
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
showStatus("Mouse Dragged to "+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{

showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,20);
}
}

Adapter Classes: Java provides a special feature, called an adapter class, that
can simplifies the creation of eventhandlers. An adapter class provides an
empty implementation of all methods in an event listener interface. Adapter
classes are useful when the user want to receive and process only some of
the events that are handled by a particular event listener interface. For such
a case the user can define a new class to act as an event listener by extending

Krishnaveni Degree College :: Narasaraopet Page No. : 130


Object Oriented Programming using Java UNIT – V

one of the adapter classes and implementing only those events in which user
is interested. The commonly used Adapter Classes along with its equivalent
Listener is given in the table below

S.No. Adapter Class Listener Interface


1. ComponentAdapter ComponentListener
2. ContainerAdapter ContainerListener
3. FocusAdapter FocusListener
4. KeyAdapter KeyListener
5. MouseAdapter MouseListener
6. MouseMotionAdapter MouseMotionListener
7. WindowAdapter WindowListener

// Program to demonstrste key Events using KeyAdapter


import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*< applet code="MyKeyEventsAdp" width=300, height=100 > </applet> */
public class MyKeyEventsAdp extends Applet
{
String msg="User Typed: ";
public void init()
{
addKeyListener(new MyKeyAdp(this));
}
public void paint(Graphics g)
{
g.drawString(msg,20,30);
}
}
class MyKeyAdp extends KeyAdapter
{
MyKeyEventsAdp adapterDemo;
public MyKeyAdp(MyKeyEventsAdp adapterDemo)
{
this.adapterDemo = adapterDemo;
}

Krishnaveni Degree College :: Narasaraopet Page No. : 131


Object Oriented Programming using Java UNIT – V

public void keyTyped(KeyEvent ke)


{
adapterDemo.showStatus("Key Typed");
adapterDemo.msg+=ke.getKeyChar();
adapterDemo.repaint();
}
}

Inner Classes: - An inner class is a class defined within another class, or even
within an expression. Inner classes can be used to simplify the code when
using event adapter classes.
// Program to demonstrste key Events using Inner Classes
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*< applet code="MyKeyEventsIner" width=300, height=100 > </applet> */
public class MyKeyEventsIner extends Applet
{
String msg="User Typed: ";
public void init()
{
addKeyListener(new MyKeyAdpIn());
}
public void paint(Graphics g)
{
g.drawString(msg,20,30);
}
class MyKeyAdpIn extends KeyAdapter
{
public void keyTyped(KeyEvent ke)
{
showStatus("Key Typed");
msg+=ke.getKeyChar();
repaint();
}
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 132


Object Oriented Programming using Java UNIT – V

Anonymous Inner Classes: An anonymous inner class is one that is not


assigned a name. Anonymous inner class can be used to facilitate the writing
of event handlers.
// Program to demonstraste key Events using anonymous inner class
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*< applet code="MyKeyEventsAnon" width=300, height=100 > </applet>
*/
public class MyKeyEventsAnon extends Applet
{
String msg="User Typed: ";
public void init()
{
addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent ke)
{
showStatus("Key Typed");
msg+=ke.getKeyChar();
repaint();
}
}
);
}
public void paint(Graphics g)
{
g.drawString(msg,20,30);
}
}

Krishnaveni Degree College :: Narasaraopet Page No. : 133

You might also like