You are on page 1of 215

Book ID: ANU-CS8392-001-2017-V1-210718

Object Oriented Programming CS8392

This book has been prepared as per Anna University syllabus, 2017 regulation.
CS8392 OBJECT ORIENTED PROGRAMMING

OBJECTIVES:

• To understand Object Oriented Programming concepts and basic characteristics of Java

• To know the principles of packages, inheritance and interfaces

• To define exceptions and use I/O streams

• To develop a java application with threads and generics classes

• To design and build simple Graphical User Interfaces

UNIT I INTRODUCTION TO OOP AND JAVA FUNDAMENTALS


Object Oriented Programming - Abstraction – objects and classes - Encapsulation-Inheritance
-Polymorphism- OOP in Java – Characteristics of Java – The Java Environment - Java Source File
-Structure – Compilation. Fundamental Programming Structures in Java – Defining classes in Java
– constructors, methods -access specifiers - static members -Comments, Data Types, Variables,
Operators, Control Flow, Arrays,Packages - Java Doc comments.
1.1 Object Oriented Programming-Abstraction – Objects and Classes - Encapsulation-Inheritance
-Polymorphism
Object–Oriented Programming Concepts

Object means a real word entity such as pen, chair, table etc. Object Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

a) Objects
b) Classes
c) Inheritance
d) Data Abstraction
e) Data Encapsulation
f) Polymorphism
g) Dynamic binding
h) Message passing

a) Objects

Objects are the basic run-time entities in an object oriented system. They represent a person,
place, a bank account, a table of data or item that a program has to handle. When a program is
executed, objects interact by passing messages to each other.

In other words, an object is a collection of data members and its associated member functions
also known as methods. Example: Customer and account are two objects,then the customer
object sends a message to the account object requesting for the bank balance.
Objects

b) Classes

A Class is collection of objects of similar type. Objects are variables of the type class. Classes are
user defined data-types and they behave like a built in types of a programming language. Class is
basically a blueprint for object. It declare & defines what data variables that the object will have
and what operations can be performed on the class's object.

Example: Apple, Mango, Orange are the members of the same class fruits.

If fruit has been defined as class,then the syntax will be

Syntax: fruit mango;

Object mango gets created belonging to class fruit.

c) Inheritance

Inheritance is the process of acquiring properties of an object in a new class from an existing
class or base class.
It is also known as parent class or super class. The class which is inherited from the base class are
called derived class or a subclass.

Inheritance helps in reducing the overall code size of the program, which is an important concept
in the object-oriented programming.

Syntax:

class subclass_name : access_mode base_class_name

//body of subclass

};

Here, subclass_name is the name of the sub class, access_mode is the mode in which you want
to inherit this sub class for example: public, private etc. and base_class_name is the name of the
base class from which you want to inherit the sub class.
d) Data Abstraction

Data Abstraction increases the power of a programming language by creating the user defined
data types. Abstraction refers to the act of representing essential features without including the
background details or explanations. Since classes use the concept of data abstraction, they are
known as Abstract data types (ADT).

e) Data Encapsulation

Wrapping up of data and functions into a single unit is known as Encapsulation.In Encapsulation,
data is not accessed directly, it is only accessible through the functions present inside the class.
Data hiding is an important feature in encapsulation.

f) Polymorphism

Polymorphism refers to a single function or multi-functioning operator performing in different


ways. It is the ability of an object to respond differently to different messages.The behaviour
depends upon the types of data used in the operation.

g) Dynamic binding

Dynamic binding occurs when a pointer or reference is associated with a member function based
on the dynamic type of an object.It is an object that is pointed to or referred to rather than the
static type of its pointer or reference.

The member function that is dynamically bound must override a virtual function declared in a
direct or indirect base class. Since the dynamic binding occurs at run time, it is also called run
time binding.

h) Message passing

Message Passing involves sending or receiving of information by the objects, as people exchange
information. This helps in building systems which simulates real life.Message passing is a form of
communication for parallel programming and object -oriented programming.

Following are the basic steps in message passing.


1. Creating classes that define objects and its behavior.

2. Creating objects from class definitions.

3. Establishing communication among the objects.

In object-oriented programming, message passing involves specifying the name of objects, the
name of the function and the information to be sent.

1.2 OOP in Java


Object-oriented programming popularly known as OOPs, is used in a modern programming
language like Java.

Object Oriented Programming is a programming paradigm that works on the principle that
objects are the most important part of a program. It allows users create the objects and then the
methods to handle those objects. Manipulation of these objects to get results is the goal of
Object Oriented Programming.

The basic unit of OOP is a class, which encapsulates both the static properties and dynamic
operations within a "box", and specifies the public interface for using these boxes. Since classes
are well-encapsulated, it is easier to reuse these classes. In other words, OOP combines the data
structures and algorithms of a software entity inside the same box.

Advantages of Object Oriented Programming:

Modularity

Object-oriented languages are modular,in which a module can be changed without affecting the
other module.

Information-hiding

Information is hidden from the other objects and it is easy to change the internal state without
affecting the external interface.

Code re-use

Object oriented programming promotes the code reuse.


Extensibility

Extensibility in an object oriented programming is easy. New functionality is easy to add without
affecting existing functionality.

Some minor disadvantages of object oriented programming:

1. Object oriented programs are hard to develop. Real world problems don’t always fit into the
objects.

2. For smaller programs, it may be easier to use the list of commands rather than a full blown
object oriented program.

3. Functional languages and the Structured Query Languages (SQL) are some of the alternatives
and they are better suited for certain problems over the object oriented paradigms.

4. One needs to be rational, as it is very important to learn the basics of an object oriented
design and carefully chose the approach.

1.2.1 Characteristics of Java


The main objective of Java programming language creation was to make it portable, simple and
secure programming language. Apart from this, there are also some features which play
important role in the popularity of this language. The features of java are also known as java
buzzwords.

The following are some important features of java programming language:

• Simple
• Platform Independent
• Architectural Neutral
• Dynamic and Extensible
• Portable
• Multi Threading
• Distributed
• Networked
• Robust
• Secured
• High Performance
• Object Oriented

Simple

The java language is easy to learn and its coding style is easy to read and write. It contains many
features of other languages like C and C++ and java removes complexity because it doesn't use
pointers and doesn't support Multiple Inheritance.

Platform Independent

This is where the "Write Once, run anywhere" motto for java comes in. It means that we can
develop on one environment(Operating System) and run on another environment without doing
any modification of the code.

Architectural Neutral

Java application runs the same byte codes regardless of any environment (Operating System). To
enable a Java application to execute anywhere on the network, the compiler generates an
architecture-neutral object file format.

Dynamic and Extensible

Java has dynamic and extensible means with the help of OOPS we can add classes and plug in
new methods to classes, creating new classes through sub classes. This makes Java very easy to
augment with our own classes or even to modify.

Portable

Java programs can execute in any environment (Linux,Window,Mac etc.) for which there is a Java
run-time system (JVM). That really means there is no implementation dependent features.

Multi Threading

A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.

Networked

Java is mainly designed for web based applications. Java makes lot of complexity by providing
classes for we that already implements the hard parts, such as creating socket connections,
reading the contents of the URL as a file etc. Moreover, J2EE is used for developing network
based applications.

Robust

Robust simply means strong. Its capability to handle Run-time Error, automatic garbage
collection, the lack of pointer concept, Exception Handling etc. makes java robust.

Secured

The Java platform is designed with security features built into the language and runtime system
such as Byte code verification for distrusted code, support for authentication and privacy etc.
Java program always runs in Java runtime environment with almost null interaction with OS,
hence it is more secure.

High Performance

Although Java is an interpreted language, it was designed to support "just-in-time" compilers,


which dynamically compile byte codes to machine code. Byte codes are highly optimized, so Java
Virtual Machine can executed them much faster.

Object Oriented

Java supports Inheritance, encapsulation and polymorphism, the three major object oriented
constructs that distinguish a language as Object-Oriented.

1.2.2 The Java Environment


The JRE is the software environment in which programs compiled for a typical JVM
implementation can run. The runtime system includes:
• Code necessary to run Java programs, dynamically link native methods, manage memory, and
handle exceptions.

• Implementation of the JVM.

The below figure shows the JRE and its components, including a typical JVM implementation's
various modules and its functional position with respect to the JRE and class libraries.

Typical
JVM's

Implementation: Functional Relationship to JRE and Class Libraries

1.3 Java Source File -Structure


A Java source file can have the following elements that, if present, must be specified in the
following order:

• An optional package declaration to specify a package name.

• Zero or more import declarations.

• Any number of top-level type declarations. Class, enum, and interface declarations are
collectively known as type declarations.

• In java, at the most one public class declaration per source file can be defined. If a public class
is defined, the file name must match this public class.
Java
Source
File

Structure

1.3.1 Compilation
The Java virtual machine (VM) can run a java program, the program's java source code must be
compiled into byte-code using the javac compiler. Java byte-code is a platform independent
version of machine code. The target machine is the java VM rather than the underlying
architecture. To compile a java source code file Foo.java

We should follow the below:

% javac -g Foo.java

The -g command line option is optional, but we recommend using it as it makes debugging
easier.

If there are no errors in our source file, the java compiler will produce one or more .class files
(one .class file for each class defined in the Foo.java source file). For example, the results of a
successful compile of Foo.java will produce a byte-code version of the class in a file named
Foo.class.
Every public class that we write must be in a separate .java file where the first part of the file
name is identical to the class name. The .java file additionally can contain code for protected and
private classes.

1.4 Fundamental Programming Structures in Java


A java program involves the following sections:

1. Documentation Section
2. Package Statement
3. Import Statements
4. Interface Statements
5. Class Definitions
6. Main Method Class

General structure
of java program

Documentation
Section

It comprises of a
comment line
which gives the
names program,
the programmer’s name and some other brief details. In addition to the 2 other styles of
comments i.e., /**/ and //, java also provides another style of comment i.e., /**….*/

Package Statement

The first statement allowed in java file is the package statement which is used to declare a
package name. It informs the compiler that the classes defined within the program belong to this
package.

It is declared as:

package package_name;
Import Statements

The next is the number of import statements, which is equivalent to #include statement in C++.

Example:

import calc.add;

Interface Statements

An interface is like a class but includes a group of method declarations. This is also an optional
section and it is used only when we wish to implement the multiple inheritance feature in the
program.

Class Definitions

A Java program may contain multiple class definitions. Classes are the primary and essential
elements of a java program. These classes are used to map the objects of real-world problems.
The number of classes used depends on the complexity of the problem.

Main Method Class

Since every java stand alone program requires a main method as its starting point, this class is
the essential part of a java program. A simple java program may contain only this part. The main
method creates the objects of various classes and establishes communications between them.
On reaching the end of main, the program terminates and the control passes back to the
operating system.

Example of a simple java program:

public class Hello

public static void main(String[] args)

System.out.println("Hello Java");
}

Output: Hello java

1.5 Defining classes in Java


A class is nothing but a blueprint or a template for creating different objects which defines its
properties and behaviors. Java class objects exhibit the properties and behaviors defined by its
class. A class can contain fields and methods to describe the behavior of an object.

Methods are nothing but members of a class that provide a service for an object or perform
some business logic. Java fields and member functions names are case sensitive. Current states
of a class’s corresponding object are stored in the object’s instance variables. Methods define
the operations that can be performed in java programming.

A class has the following general syntax:

<class modifiers>class<class name>

<extends clause> <implements clause>

// Dealing with Classes (Class body)

<field declarations (Static and Non-Static)>

<method declarations (Static and Non-Static)>

<Inner class declarations>

<nested interface declarations>

<constructor declarations>

<Static initializer blocks>

}
Below is an example showing the Objects and Classes of the Cube class that defines 3 fields
namely length, breadth and height. Also the class contains a member function getVolume().

public class Cube

int length;

int breadth;

int height;

public int getVolume()

return (length * breadth * height);

1.5.1 Constructors

The main use of constructors is to initialize objects. The function of initialization is automatically
carried out by use of a special member function called a constructor.

General Syntax of Constructor

A constructor is a special member function that takes same name as the class name. The default
constructor for a class X has the form X::X()

In the above example, the arguments are optional. The constructor is automatically named when
an object is created.

Constructor is named whenever an object is defined or dynamically allocated using the “new”
operator.

Characteristics of a constructor:
• They must be declared in the public section.

• They are invoked automatically when objects are created.

• They do not have return types.

• They can also have default arguments.

• It cannot be virtual.

• They cannot be inherited.

• They cannot be inherited.

• We cannot refer to their addresses.

There are many forms in which a constructor can take its shape namely:

* Default Constructor

* Copy constructor

* Parameterized constructor

1.6 Methods - Access specifiers

Members of a class can acquire access attributes in one of 2 ways: by default or through the use
of the access specifiers public, private and protected.

Syntax:

public: <declarations>

private: <declarations>

protected <declarations>

Public:
If a member is public, it may be used by any function. In C++, members of a struct or the union
are public by default.

Private:

If a member is private, it can only be used by member functions and friends of the class in which
it is declared. Members of a class are private by default.

Protected:

If a member is protected, its access is the same as for the private.

In addition, the member can be used by member functions and friends of classes derived from
declared class but only in objects of the derived type.

Scope Resolution Operator(::)

This operator could be used to refer to any member in the class explicitly.

Sample c++ program

#include<iostream.h> // include files

class student // the class declarations

char name[30];

int age1;

public:

void getdata(void);

void display(void);
}

void student:: getdata(void) // member functions definitions

cout << "Enter name ";

cin >> name;

cout << "enter age"

cin >> age1;

void student::display(void) // member function definitions

cout << " name " << name;

cout << " age " <<, age1;

void main() // main function program

student s1; // s1 is an object for the class student

s1.getdata();

s1.display();

}
1.6.1 Static members

Usage of a static member:

The static data member give information to the compiler that only one copy of the data member
exit and all objects of the class should share that variable without duplicating it for each instance
of the class.

Static Members:

The Static Data Member of a class is similar to a global variable. Once it is defined the static
member will be initialized to zero.

When the static member is declared inside the class it must be defined outside of the class.
Static Data Member of a class will be common to all objects which are declared in the class.

Syntax:

class stat1

static int count; //static Data Member Declaration

int stat::count; //static Data member Definition

Example Program:

#include<iostream.h>

#include<conio.h>

class count

{
public:

static int count1;

void dispcount()

count1++;

cout<<"Object\t"<<count1<<"\n";

};

int count::count1;

void main()

count c1,c2,c3,c4,c5;

clrscr();

c1.dispcount();

c2.dispcount();

c3.dispcount();

c4.dispcount();

c5.dispcount();

getch();
}

In this example the class count has a static data member count. This code is used for counting
the number of objects which is declared in the class.

So when an object c1 access the function dispcount() the static variable has the value 1.when s5
access the function the value will be incremented by 5.

Output:

Object 1

Object 2

Object 3

Object 4

Object 5

1.6.2 Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class
or any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

Single Line Comment


Multi Line Comment
Documentation Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:
//This is single line comment //

Example:

public class CommentExample1

public static void main(String[] args)

int i=10; //Here, i is a variable //

System.out.println(i);

Output:

10

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

/* This is multi line comment */

Example:

public class CommentExample2

public static void main(String[] args)

/* Let's declare and print variable in java. */

int i=10;

System.out.println(i);

}
}

Output:

10

3) Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation


API, we need to use javadoc tool.

Syntax:

/** This is documentation comment */

Example:

/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/

public class Calculator

/** The add() method returns addition of given numbers.*/

public static int add(int a, int b){return a+b;}

/** The sub() method returns subtraction of given numbers.*/

public static int sub(int a, int b){return a-b;}

Compile it by javac tool:

javac Calculator.java

Create Documentation API by javadoc tool:

javadoc Calculator.java

1.7 Data Types


Based on the data type of the variable, the operating system allocates the memory and decides
what can be stored in the reserved memory. Therefore by assigning different data types to
variables, we can store integers, decimals or characters in these variables.

The below are two data types available in Java:


1. Primitive Data Types
2. Reference/Object Data Types

1. Primitive Data Types:

There are eight primitive data types supported by java. Primitive data types are predefined by
the language and named by a keyword.

Eight primitive data types are:

Byte:

Byte data type is an 8-bit signed 2’s complement integer.

Minimum value : -128 (-2^7)

Maximum value : 127 (inclusive)(2^7 -1)

Default value : 0

Byte data type is used to save space in large arrays mainly in the place of integers, since a byte is
four times smaller than an int.

Example: byte a = 100 , byte b = -50.

Short:

Short data type is a 16-bit signed 2’s complement integer.

Minimum value : -32,768 (-2^15)

Maximum value : 32,767 (inclusive) (2^15 -1)

Short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an int.

Default value = 0.

Example: short s = 10000, short r = -20000


Int:

Int data type is 32-bit signed 2's complement integer.

Minimum value : - 2,147,483,648.(-2^31)

Maximum value : 2,147,483,647(inclusive).(2^31 -1)

Int is generally used as a default data type for integral values unless there is a concern about
memory.

Default value = 0.

Example: int a = 100000, int b = -200000

Long:

Long data type is a 64-bit signed 2’s complement integer.

Minimum value : -9,223,372,036,854,775,808.(-2^63)

Maximum value : 9,223,372,036,854,775,807 (inclusive). (2^63 -1)

This type is used when a wider range than int is needed.

Default value = 0L.

Example: long a = 100000L, int b = -200000L

Float:

Float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save
memory in large arrays of floating point numbers.

Default value = 0.0f.

Float data type is never used for precise values such as currency.

Example: float f1 = 234.5f

Double:
Double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally
used

as the default data type for decimal values. Double data type should never be used for precise
values such as currency.

Default value is 0.0d.

Example: double d1 = 123.4

Boolean:

Boolean data type represents one bit of information. There are only two possible values: true
and false. This data type is used for simple flags that track true/false conditions. Default value is
false.

Example: boolean one = true

Char:

Char data type is a single 16-bit Unicode character.

Minimum value : '\u0000' (or 0).

Maximum value : '\uffff' (or 65,535 inclusive).

Char data type is used to store any character.

Example: char letterA ='A'

Reference Data Types:

Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type which cannot be changed.
For example, Employee, Puppy, etc. Class objects and various types of array variables comes
under reference data type. The default value of any reference variable is null. A reference
variable can be used to refer any object of the declared type or any compatible type.

Example: Animal animal = new Animal("giraffe");


Java Literals:

A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation. Literals can be assigned to any primitive type variable.

For example:

byte a = 68;char a = 'A'

byte a = 68;

char a = 'A'.

1.7.1 Variables
A variable provides us with the named storage that our programs can manipulate. Each variable
in java has a specific type, which determines the size and layout of the variable's memory, the
range of values that can be stored within that memory and the set of operations that can be
applied to the variable.

int a, b, c; // Declares three integers a, b and c.

int a = 10, b = 10; // Example of initialization byte.

B = 22; // Initializes a byte type variable B.

double pi = 3.14159; // Declares and assigns a value of PI.

char a = 'a'; // Char variable a is initialized with value 'a'.

Types of variables

• Local variables
• Instance variables
• Class/static variables

Local variables:

Local variables are declared in methods, constructors or blocks. Local variables are created when
the method, constructor or block is entered and the variable will be destroyed once it exits the
method, constructor or block. The access modifiers cannot be used for local variables. Local
variables are visible only within the declared method, constructor or block. Local variables are
implemented at stack level internally. There is no default value for local variables so, the local
variables should be declared and an initial value should be assigned before the first use.

Example

Here age is a local variable.

This is defined inside pupAge() method and its scope is limited to this method only.

public class Test

public void pupAge()

int age = 0;

age = age + 7;

System.out.println("Puppy age is : " + age);

public static void main(String args[])

Test test = new Test(); test.pupAge();

Output:

Puppy age is: 7

Instance variables:
Instance variables are declared in a class but outside a method, constructor or any block. When a
space is allocated for an object in the heap, a slot for each instance variable value is created.
Instance variables can be declared in class level before or after use. Access modifiers can be
given for instance variables.

1.7.2 Operators
Operators in java:

It is a symbol that is used to perform operations. There are many types of operators in java such
as unary operator, arithmetic operator, relational operator, shift operator, bitwise operator,
ternary operator and assignment operator.

Arithmetic Operators

Operator Operation

+ Additive operator(also used for string


concatenation)

- Subtraction operator

* Multiplication operator

/ Division operator

% Remainder operator

Unary Operator

Operator Operation

+ Unary plus operator; indicates positive value


(numbers are positive without this, however)

- Unary minus operator; negates an expression

++ Increment operator; increments a value by 1

-- Decrement operator; decrements a value by 1

! Logical complement operator; inverts the value


of a boolean
Relational Operators

Operator Operation

== Equal to

!= Not equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

Conditional Operator

&& Conditional-AND

|| Conditional-OR

Ternary (shorthand for if-then-else statement)

Java has well-defined rules for specifying the order in which the operators in an expression are
evaluated when the expression has several operators. For example, the multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.

Precedence order

When two operators share an operand the operator with the higher precedence goes first. For
example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas the 1 * 2 + 3 is treated as (1 * 2) + 3 since the
multiplication has a higher precedence than addition.

Associativity

When an expression has two operators with the same precedence, the expression is evaluated
according to its associativity. For example: x = y = z = 17 is treated as x = (y = (z = 17)), leaving all
three variables with the value 17, since the = operator has right-to-left associativity. On the other
hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity.
Order of evaluation of sub expressions

Associativity and precedence determine in which order java applies operators to subexpressions
but they do not determine in which order the subexpressions are evaluated. In Java, the
subexpressions are evaluated from left to right. So, for example in the expression A() + B() *
C(D(), E()), the subexpressions are evaluated in the order A(), B(), D(), E() and C(). Although, C()
appears to the left of both D() and E(), we need the results of both the D() and E() to evaluate
C(). It is considered poor style to write the code that relies upon this behavior.

Short circuiting: When using the conditional and & or operators (&& and ||), Java does not
evaluate the second operand unless it is necessary to resolve the result. This allows the
statements like if (s != null && s.length() < 10) to work reliably. Programmers rarely use the non
short-circuiting versions (& and |) with the boolean expressions.

Precedence order gone awry.

Sometimes the precedence order defined in a language do not conform with the mathematical
norms. For example, in Microsoft Excel, -a^b is interpreted as (-a)^b instead of -(a^b). So , -1^2 is
equal to 1 instead of -1, which is the value most mathematicians would expect. Microsoft
acknowledges this as a "design choice".

One wonders whether the programmer is relying on the C precedence order in which the unary
operators have higher precedence than the binary operators. This rule agrees with the
mathematical conventions for all C operators, but fails with the addition of the exponentiation
operator. Once the order was established in Microsoft Excel 2.0, it could not easily be changed
without breaking the backward compatibility.

1.7.3 Control Flow


The control flow statements are used to control the flow of execution of the program.

In Java programming language, there are three types of control flow statements. They are:

1. Decision making or selection statement (if, if-else, switch)


2. Looping or Iteration statement (while, for, do-while)
3. Breaking or Jumping statement (break, continue)
Decision Making Statements

Decision making statement is also called selection statement. If the condition is "true",
statement block will be executed, if condition is "false", then statement block will not be
executed.

In java, there are three types of decision making statement. They are:

• If
• If-else
• Switch

if-then statement

If-then is the most basic statement of the decision making statement. A program executes a
certain part of code only if a particular condition or test is true.

Syntax:

if(condition)

Statement(s)

Constructing the body is


always optional, so it is
recommended to create
the body when we are
having multiple
statements. For a single
statement, it is not
required to specify the body. If the body is not specified, then automatically condition parts will
be terminated with semicolon (;).

else
● It is a keyword. By using this keyword, we can create an alternative block for "if" part.

● Using else is always optional i.e., it is recommended to use when we are having alternate block
of condition.

● When we are working with if else, among those two block at any given point of time, only one
block will be executed.

● When if condition is false, then else part will be executed and if the if part is executed, then
automatically else part will be ignored.

If-else statement

In general, it can be used to execute one block of statement among two blocks . In java language,
if and else are the keyword in java.

Syntax:

if(condition)

Statement(s)

else

Statement(s)

......

In the above syntax, whenever the condition is true,only if block statement are executed by
neglecting else block statement. If the condition is false, else block statement are executed by
neglecting if block statements.
Switch Statement

A switch statement work with byte, short, char and int primitive data type. It also works with
enumerated types and string.It is a multiple branching statement where,based on the
condition,control is transferred to one of the many types.

Syntax:

switch(expression/variable)

case value: //statements

break; //optional

default: //optional
}

Looping Statement

Looping statement are the statements execute one or more statement repeatedly number of
times.

In java programming language, there are three types of loops. They are:

● While
● For
● Do-while

While loop

In while loop, first check the condition. If condition is true, then control goes inside the loop
body otherwise goes outside of the body. While loop will be repeats in clock wise direction.

Syntax

while(condition)

Statement(s)

Increment /
decrements (++ or
--);

For loop

For loop is a
statement which
allows code to be repeatedly executed. For loop contains three parts such as initialization,
condition and increment or decrement.

Syntax

for ( initialization; condition; increment )

statement(s);

Initialization:

This step is
executed first
and this is
execute only
once when
we are
entering into the loop first time. This step is allow to declare and initialize any loop control
variables.
Condition:

This is next step after initialization step. If it is true, the body of the loop is executed, if it is false ,
then the body of the loop does not execute. Flow of control goes outside of the for loop.

Increment or Decrement:

After completion of initialization and condition steps, loop body code is executed and then
increment or decrement steps is execute. This statement allows to update any loop control
variables.

Do-while

A do-while loop is similar to a while loop, except that a do-while loop is execute at least one
time. A do-while loop is a control flow statement that executes a block of code at least once, and
then repeatedly executes the block, or not, depending on a given condition at the end of the
block (in while).

Syntax

do

Statement(s)
increment/decrement (++ or --)

}while();

Breaking or Jumping statement

Java jump statements are break, continue, and return. These statements transfer control to
another part of the program.

1. Break
2. Continue
3. Return

The break statement

This statement is used to jump out of a loop. On encountering a break statement within a loop,
the execution continues with the next statement outside the loop. The remaining statements
which are after the break and within the loop are skipped. Break statement can also be used
with the label of a statement.

Example of break statement:

class break1

public static void main(String args[])

int i = 1;

while (i<=10)

System.out.println("\n" + i);

i++;
if (i==5)

break;

Output :

Continue statement

This statement is used only within looping statements. When the continue statement is
encountered, the next iteration starts. The remaining statements in the loop are skipped. The
execution starts from the top of loop again.

The program below shows the use of continue statement.

class continue1

public static void main(String args[])

{
for (int i=1; i<1=0; i++)

if (i%2 == 0)

continue;

System.out.println("\n" + i);

Output :

The return statement

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. The return statement immediately
terminates the method in which it is executed.

The program below shows the use of return statement.

class Return1

public static void main(String args[])


{

boolean t = true;

System.out.println("Before the return.");

if(t)

return; // return to caller

System.out.println("This won't execute.");

Output :

Before the return.

1.8 Arrays
Array

Array is a collection of similar data type values that share a common name. Each element in an
array can be accessed by using the index number or sub script. In java, array is an object.Arrays
are of two types : one dimensional and multi dimensional

Creating arrays

An array must be created just before using it in a program. Creating an array consists of the
following steps.

• Declaration
• Initialization

Array declaration

An array can be declared by specifying the data type followed by [] with array name. Array
declaration only declares the name of an array. No memory space is allocated. So we cannot use
it before Initialization. Size should not be given to an array at the time of declaration.
General form of array declaration

Method 1: data_type array_name[];

Method 2: data_type [] array_name;

Example:

int mark[];

The same can be also declared as mark Null.

int [] mark;

Array Initialization

An array can be initialized after declaration or at the time of declaration. Initialization is nothing
but allocating space to an array. This is done by using new operator. Once an array is Initialized,
its size cannot be changed.

General form of array Initialization,

array_name=new data_type[size];

Array size may be any valid integer value. Zero is also valid size.

Example

mark=new int[5];

Initializing arrays

Initializing an array is the process of giving initial values to the array elements. It can be done in
two ways.

Method 1: Initial values are given to the elements at the time of declaration.

In this method, there is no need to use new operator to allocate space to the array.

Syntax: data_type array_name[]={initial values};

Example: int mark[]={1,2,3,4,5};


Here, there is no need to use new operator to allocate space.

Because, memory space will be allocated based on the number of the values in the list. The
values must be separated by commas.

Method 2: Initial values are given to the elements by accessing each element using the index
number.

Here, the maximum size of array must be stated in advance.

Syntax: array_name[index]=initial_value;

Example: mark[3]=4;

Array length

Size of an array can be obtained by accessing the attribute length.

Syntax: array_name.length

Example: size=mark.length;

Let us see a sample code for one dimensional array

import java.io.*;

class Sample

int Num[];

Sample()

Num=new int [10];

for(int i=0;i<Num.length;i++)

Num[i]=i+1;
}

void Print()

System.out.print(“Number are “);

for(int i=0;i<Num.length;i++)

System.out.print(“ “+Num[i]+” “);

public static void main(String s[])

Sample S=new Sample();

S.Print();

}}

Anonymous Arrays

An anonymous array is an array created without any name. It is used to reinitialize an array
without creating a new variable.

General form

array_name=new data_type[]{values_list};

Example

mark=new int[]{10,20,30,40,50};

Array copying

An array can be copied into another array in two ways:

Method 1:
One method is by directly copying the array reference into another array. In this method, both
arrays point to the same memory location. So changes in one array will affect the other.

General form

destination_array=source_array;

Example

import java.io.*;

class Sample

intNum[];

Sample()

Num=new int[5];

int N[]={1,2,3,4,5};

Num=N; //both are pointing to the same location

void Print()

System.out.print(“Number are “);

for(int i=0;i<Num.length;i++)

System.out.print(“ “+Num[i]+” “);

public static void main(String s[])


{

Sample S=new Sample();

S.Print();

}
Method 2:

This method copies the values into another using copyOf() or arraycopy() methods.

copyOf() method

This method copies the values from the specified array. This method is normally used to increase
the size of an array. This static method is defined in the arrays class. It returns the array
reference.

General form

array_name = Arrays.copyOf(existing_array,array_size);

Example

Num = Arrays.copyOf(Num, 10);

If the array size specified is greater than the elements available in the existing array, remaining
elements are initialized to 0.

arraycopy() method

This also does the same job as copyOf method. But it does not return any reference. It just
copies the content of one array in another. But the destination must have sufficient memory
space to hold the source values.

General form

System.arraycopy(source,source_index,destination,destination_index,count);

Example

System.arraycopy(Num,2,newNum, 1,3);

Above instruction copies 3 elements starting from the index 2 from the source array into the
destination from index 1.

Enhanced for () loop


For loop is enhanced to work on the arrays or collections by retrieving each element one by one.
If only the value of each element is to be referred , this loop can be used. This loop is also known
as the for each loop, which keeps track of the index and assigns successive values to a variable.
The for each loop only gets the values.

General form

for(Type variable:Identifier)

Statements;

Example

int a[]={10,20,30,40,50};

int sum=0;

for(int i: a)

sum=sum+i;

Method syntax Process

It returns a string with the elements of array,


static String toString(type[] arr)
enclosed in brackets and delimited by commas.

static type copyOf(type[] arr, int length) (or) It returns an array of the same type as arr -
static type copyOf(type[] arr, int start, int end) filled with the values of arr.

It sorts the array, using a tuned Quicksort


static void sort(type[] arr)
algorithm

static int binarySearch (type[] arr, type val) (or) It uses the binary search algorithm to search for
static int binary Search (type[] arr, int start, int the value val. If it is found, its index is returned.
end type val) Otherwise, a negative value r is returned;-r -1 is
the spot at which val should be inserted to keep
arr sorted.

static void fill(type[] arr, type val) It sets all elements of the array to val.

It returns true if the arrays have the same


static boolean equals(type[] a, type[] b) length,if the elements in corresponding indexes
catch.

static void arraycopy (Object from, int It copies elements from the first array to the
fromIndex, Object to, int toIndex, int count) second array.

Methods available in Arrays class

Multi dimensional arrays

Multi dimensional arrays are represented using multiple-indexes. It is the collection of one
dimensional arrays.

Example

Array declaration-two dimensional

int [][]a;

(or)

int a[][];

Array initialization-two dimensional

int a[][]=new int[2][2];

(or)

Array initialization-two dimensional

int a[][] = { {10,20},{30,40} };

1.9 Packages

A package is grouping of related types providing access protection and namespace management.
Package names are dot separated, e.g., java.lang.Package names have correspondence with the
directory structure. Packages avoid name space collision. There cannot be two classes with the
same name in a same Package. But two packages can have a class with same name.

Exact Name of the class is identified by its package structure.

<< Fully Qualified Name>>java.lang.String ;

java.util.Arrays;

java.io.BufferedReader ;

java.util.Date;

Packages are mirrored through directory structure.

To create a package, first we have to create a directory /directory structure that matches the
package hierarchy. Package structure should match the directory structure also. To make a class
which belongs to a particular package include the package statement as the first statement of
source file.

In the above diagram, the package ABC and IJK have classes with same name.
• A class in ABC has name mypackage.mypackageA.ABC.A

• A class in IJK has name mypackage.mypackageB.IJK.A

Advantages of using packages

• Classes can be easily reused.

• Two classes in different packages can have same name.

• Packages provide way to hide classes.

Reasons for using packages

• To group related classes.

• To prevent name conflicts.

• To allow effective use of default package visibility.

• To limit the scope of class names.

• To make package access more usable.

Importing classes

Packages are organized in a hierarchical structure in java. All classes from own package and all
public classes from other packages can be used by a class. There are two ways to access public
classes in another package.

Method 1

First approach is to give fully qualified class name. That is, full package name has to be placed
before the class name. In this method, packages and classes are separated by commas.

This approach is suitable only when a class is used only once in the program.
Example

java.util.Date birthday = new java.util.Date();

util is the package within the package java. Date is the class name.

Method 2

Second approach uses the import statements to import the classes. Import statements are
placed at the top of the program file.

Specific class or the whole package can be imported using these statements. These are suitable
when a class or classes from a particular package is used more than once.

Syntax:

import package 1 [.package2]... [.class_name];

Example:

import java.awt.*; // * imports all class in that package and also imports all classes from java.awt
package, Packages within packages require additional imports.

Steps to create and use a package in MS-DOS environment

To create and use our own packages, the following steps are to be followed.

Type the following command in DOS prompt to enter into the Java.

cd java\JDKl .6.0\bin

We will get the prompt like this...C:\Java\JDKl.6.0\bin>

If JDK is installed in another directory, use appropriate command.

• Create a sub-directory in the name of the package.


For example, to create a package in the name MyPackage, first create the directory by using the
following command,

md MyPackage

Enter into the created directory by using the following command,

cd MyPackage

We will get the prompt like the following,

C:\Java\JDKl .6.0\bin\MyPackage>

• Create a java file inside the created directory with the classes that are to be inserted into the
package by declaring the package statement at the top of the file.

For example, to create the java file (MyClass.java) inside MyPackage, first go into the editor by
using following command,

edit MyClass.java

• We will get into the editor. Type the following code.

package MyPackage;

public class MyClass

public void print(Object obj)

System.out.println(“Value:”+obj);

}
}

• Save it and exit from the editor.

• Come back to the bin using the following command cd.

• Compile the java file and .class file is created and stored in the same directory(package).

For example, compile using the following command

Javac MyPackage\MyClass.java

MyClass.class file will be stored in the same package.

• Use the created package in the program given below:

For example:

import MyPackage.*;

class MyProg

public static void main(String s[])

MyClass MyObj=new MyClassQ;

MyObj.print(10);

MyObj .print( 1.23 E-4);

MyObj.print(“Sunil kumar”);

}
}

Output:

Value is: 10

Value is: 1.23E-4

Value is: Sunil kumar

1.9.1 Java Doc comments


Javadoc is the Sun Microsystems tool for generating application programming interface (API)
documentation in HTML format from document comments in source code. In the code, we use
special comment characters starting with /** and ending with */ to indicate that the javadoc
tool should process the comment to produce HTML-formatted documentation.

Writing javadoc comments can become an entire project in itself, and we need to be thorough
because Sun does review code comments. There are several approaches to javadoc commenting.
We do not have to worry about it, however. Just be sure to add comments that are enclosed in
the multiline comment for every major declaration. The text is written in HTML and must
precede a class, field, constructor, or method declaration. These comments are structured as a
description followed by special javadoc tags, such as @param @return and @see.

Every class and method should be commented in such a way that the javadoc tool can grab it. To
see how to do this please refer to Sun's guide-lines on writing javadoc comments in code at
http://java.sun.com/ javadoc/writingdoccomments/index.hug. For detailed reference material
on Javadoc tags please refer to http: //java.sun.com/j2se/javadoc/ index
.html#javadocclocusents.

The following is an example of how to comment a method that results in proper javadoc
documentation:

/**

• Returns a Blob object that represents a customer.

• The id argument must specify a single customer. The last_name


• argument is a description that will be displayed later.

• <p>

• This method will either return a Blob or a null if the

• Blob doesn't exist.

• @param id the customer unique identifier

last_name the customer's last name

• @return the customer Blob

• @see Blob .1

public Blob getBlob(int id, String last_name)

try

Blob blob = getCustomer(id);

if(blob 1= null)

blob.setLastName(last_name);

return blob;

} catch (NoBlobException e)

return null;

}
}
UNIT II INHERITANCE AND INTERFACES
Inheritance – Super classes- sub classes –Protected members – constructors in sub classes- the
Object class – abstract classes and methods- final methods and classes –Interfaces – defining an
interface, implementing interface, differences between classes and interfaces and extending
interfaces - Object cloning -inner classes, Array Lists -Strings.
2.1 Inheritance
Inheritance is the process by which objects of one class acquires the properties of objects of
another classes. It supports concept of hierarchical classification.

In other words, Inheritance is the concept that when a class of object is defined, any subclass
that is defined could inherit the definitions of one or more general classes.

Base classes and derived classes

The class from which other class is derived is called as base class or superclass. The new class is
known as derived class or sub class.

Types

1. Single Level Inheritance


2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical inheritance
5. Hybrid Inheritance

Single Inheritance:

In this type of inheritance, one derived class inherits from only one base class. It is most simplest
form of Inheritance.

Single Inheritance in
C++
Example program

#include
<iostream>

Class B

int a;

public:
int b;

void get_ab();

int get_a();

void show_a();

};

Class D: public B

int c;

public:

void mul();

void display();

};

void B :: get_ab()

{ a=5;b=10; }

Int B :: get_a()

{ return a;}

void B :: show_a()

cout<< “a=”<<a<< “\n” ;

Void D :: mul()

{
c=b*

get_a();

void D :: display()

cout<< “a=”<<get_a();

cout<< “b=”<<b;

cout<< “c=”<<c;

int main()

D d;

d.get_ab();

d.mul();

d.show_a();

d.display();

d.b=20;

d.mul();

d.display();

return 0

Multiple Inheritance:
In this type of the inheritance, a single derived class may inherit from two or more than two
base classes.

Multiple Inheritance in C+
+
Example program

#include<iostream>

#include<conio.h>

class student

protected:

int rno,m1,m2;

public:

void get()

cout<<"Enter the Roll no :";

cin>>rno;

cout<<"Enter the two marks:";

cin>>m1>>m2;

};

class sports

protected:
int sm; // sm = Sports mark

public:

void getsm()

cout<<"\n Enter the sports mark :";

cin>>sm;

};

class statement:public student,public sports

int tot,avg;

public:

void display()

tot=(m1+m2+sm);

avg=tot/3;

cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;

cout<<"\n\tAverage : "<<avg;

};

void main()

{
clrscr();

statement obj;

obj.get();

obj.getsm();

obj.display();

getch();

Output:

Enter the Roll no: 100

Enter two marks

90

80

Enter the Sports Mark: 90

Roll No: 100

Total : 260

Average: 86.66

Hierarchical Inheritance:

In this type of the inheritance, multiple derived classes inherits from a single base class.

Hierarchical
Inheritance in C++

Example program
#include <iostream>

#include <conio.h>

using namespace std;

class person

char name[100],gender[10];

int age;

public:

void getdata()

cout<<"Name: ";

fflush(stdin); /*clears input stream*/

gets(name);

cout<<"Age: ";

cin>>age;

cout<<"Gender: ";

cin>>gender;

void display()

cout<<"Name: "<<name<<endl;

cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;

};

class student: public person

char institute[100], level[20];

public:

void getdata()

person::getdata();

cout<<"Name of College/School: ";

fflush(stdin);

gets(institute);

cout<<"Level: ";

cin>>level;

void display()

person::display();

cout<<"Name of College/School: "<<institute<<endl;

cout<<"Level: "<<level<<endl;
}

};

class employee: public person

char company[100];

float salary;

public:

void getdata()

person::getdata();

cout<<"Name of Company: ";

flush(stdin);

gets(company);

cout<<"Salary: Rs.";

cin>>salary;

void display()

person::display();

cout<<"Name of Company: "<<company<<endl;

cout<<"Salary: Rs."<<salary<<endl;

}
};

int main()

student s;

employee e;

cout<<"Student"<<endl;

cout<<"Enter data"<<endl;

s.getdata();

cout<<endl<<"Displaying data"<<endl;

s.display();

cout<<endl<<"Employee"<<endl;

cout<<"Enter data"<<endl;

e.getdata();

cout<<endl<<"Displaying data"<<endl;

e.display();

getch();

return 0;

Output:

Student

Enter data

Name: John Wright


Age: 21

Gender: Male

Name of College/School: Abc Academy

Level: Bachelor

Displaying data

Name: John Wright

Age: 21

Gender: Male

Name of College/School: Abc Academy

Level: Bachelor

Employee

Enter data

Name: Mary White

Age: 24

Gender: Female

Name of Company: Xyz Consultant

Salary: $29000

Displaying data

Name: Mary White

Age: 24

Gender: Female
Name of Company: Xyz Consultant

Salary: $29000

Multilevel Inheritance:

In this type of inheritance, derived class inherits from a class, which in turn inherits from some
other class. The Super class for one is the sub class for other.

Multilevel
Inheritance in C++
Example Program

#include
<iostream.h>

using namespace
std;

class A

public:

void display()

cout<<"Base class content.";

};

class B : public A

};
class C : public B

};

int main()

C c;

c.display();

return 0;

Output

Base class content.

Hybrid (Virtual) Inheritance:

Hybrid Inheritance is combination of the Hierarchical and Mutilevel Inheritance.

Hybrid Inheritance
in C++
Example Program

#include<iostream.h>

class stud
{

Protected:

int rno;

Public:

void getno(int n)

rno=n;

void display_rno()

Cout<<“Roll_no=”<<rno<<”\n”;

};

Class test: Public stud

Protected:

Int sub1,sub2;

Public:

void get_mark(int m1,int m2)

Sub1=m1;

Sub2=m2;
}

void display_mark()

Cout<<”sub1”<<sub1<<”\n”; Cout<<”sub2”<<sub2<<”\n”;

};

class sports

Protected:

Float score;

Public :

void get_score(float s)

Score=s;

void put_score()

cout<<”Sort :”<<score<<”\n”;

};

class result: public test ,public sports

{
Float total;

Public:

Void display();

};

void result::display()

Total=sub1+sub2+score;

display_rno();

display_mark();

put_score();

cout<<” total score:”<<total<<”\n”;

int main()

Result s r1;

r1. getno(123);

r1. get_mark(60,80)

r1.get_score(6);

r1.display();

2.1.1 Super classes- sub classes


Superclass and subclass:
• When a class is created which inherits the members from an existing class, the new class is
referred to as the subclass and the existing class is the superclass (also called the derived and
base class in C++).

• The subclasses are more specific than superclasses and superclasses more general. They
inherit the methods and data fields from the superclass and define their own, creating more
specialized objects.

• One superclass can have several subclasses and the set of objects represented by a superclass
is larger than the collection of objects represented by any of its subclasses. An example would be
class Animals shows that all types of animals,Cats, Dogs, Horses, Cows, where as the class Dog is
a smaller, more specific group of Animals.

Direct Super-class

It is the superclass from which a subclass explicitly inherits. In the figure on the following page,
the direct superclass of the class Faculty is an Employee.

Indirect Super-class

It is any class above the direct superclass in the class hierarchy.

Class Hierarchy and Inheritance

• The class hierarchy refers the inheritance relationship between the classes. The root of the
class hierarchy is the class Object.

• In single inheritance, a class is derived from one direct superclass.

Class Relationships

1. is-a Relationships

• Objects of one class can be subclasses (members) of another class. For example, a Dog is an
Animal.
• The table below illustrates some is-a relationships. A GradStudent is-a Student. A Temporary
employee is- an Employee. It is correct to assume that a Rectangle is a specific type of shape, but
it is not correct that every Shape is a Rectangle.

SuperClass SubClass

Student GradStudent, UnderGradStudent

Shape Circle, Triangle, Rectangle

Loan CarLoan, HomeLoan, BusinessLoan

Employee Part-Time, Full-Time, Temporary

BankAccount CheckingAccount, SavingsAccount

2. has-a Relationships

• Not every class relationship is an inheritance relationship. Class relationships can be has-a
relationships, meaning classes have members that are references to the objects of other class
types.

• For example, if an Employee has an Office, this denotes that the object office is a data member
of the Employee class. It would not be correct to say that Office is-a Employee, because which
shares no data or methods with the Employee class.

Class Hierarchy Example


The arrows in the hierarchy illustrates is-a relationships. There are a number of direct superclass
relationships and indirect superclass relationships.

Creating Subclasses using extends keyword

• The files below show examples of subclass/superclass relationships.

• To denotes a class is a subclass of another, we use the extends keyword.

• Usage: public class Dog extends Animal

Visibility of Inherited Members

• Visibility modifiers are public and private.

• A public member means that it can be accessed from any class, whereas a private member was
only accessible from inside the class in which it was declared.

• When we have an inheritance relationship, we can add another modifier, the protected
modifier. This modifier means that a super classes protected members can be accessed by
members of its subclasses and by members of classes in the same package.

2.2 Protected members

If members are declared as protected then these are accessible to all classes in the package and
to all subclasses of its class in any package where this class is visible.
Example:

#include <iostream>

using namespace std;

class Box

protected:

double wi;

};

class SmallBox:Box // SmallBox is the derived class.

public:

void setSmallWidth( double wid );

double getSmallWidth( void );

};

// Member functions of child class

double SmallBox::getSmallWidth(void)

return wi ;

void SmallBox::setSmallWidth( double wid )

wi = wid;
}

// Main function for the program

int main( )

SmallBox box;

// set box width using member function

box.setSmallWidth(5.0);

cout << "Width of box : "<< box.getSmallWidth() << endl;

return 0;

2.2.1 Constructors in sub classes


Look at the PlaneCircle() constructor method of example:

public PlaneCircle(double r, double x, double y)

super(r); // Invoke the constructor of the superclass, Circle()

this.cx = x; // Initialize the instance field cx

this.cy = y; // Initialize the instance field cy

This constructor explicitly initializes the cx and cy fields newly defined by PlaneCircle, but it relies
on the superclass Circle() constructor to initialize the inherited fields of the class. To invoke the
superclass constructor, our constructor calls super(). super is a reserved word in java. One of its
uses is to invoke the constructor method of a superclass from within the constructor method of
a subclass.
This use is analogous to the use of this() to invoke one constructor method of a class from within
another constructor method of the same class. Using super() to invoke a constructor is subject to
the same restrictions as using this() to invoke a constructor:

• super() can be used in this way only within a constructor method.

• The call to the superclass constructor must appear as the first statement within the constructor
method, even before local variable declarations.

The arguments passed to super() must match the parameters of the superclass constructor. If the
superclass defines more than one constructor, super() can be used to invoke any one of them,
depending on the arguments passed.

2.2.2 The Object class


Properties of one class could be used in another class using inheritance or using the object of a
class as a member in another class. Declaring the object as a class data member in another class
is also known as delegation. When a class has an object of an another class as its member, such a
class is known as a container class.

In inheritance, the derived class can use members of the base class. Here, the derived class is a
kind of base class. The programmer can also add new members to derived class. In delegation,
the class consists of objects from other classes. The composed class uses the properties of other
classes through their objects. This kind of a relationship is known as has-a relationship or
containership.

class I

******// members

*******

} class II

I j; // object of class I as member

**********
}

A program use object of one class in another class as a member.

#include<iostream.h>

#include<conio.h>

class I

public: int x;

I()

cout<<"\n Constructor of class I";

x=20;

}; class II

public:

int k;

I y;

II()

{ k=30;

cout<<"\n Constructor of class II"; }

void show()

{ cout<<"\n x="<<y.x <<" k="<<k;

}; int main()
{

clrscr();

ii. show();

return 0;

OUTPUT

Constructor of class I

Constructor of class II

x= 20 k = 30

Explanation:

In the above program, the class II contains integer k and object y of class I. In function main(),
object ii is an object of class II. The constructor of the class I is executed first, because when the
compiler reaches the class II, it finds an object of class I. We know that object declaration always
executes the constructor of that class. Thus, the object of class I is declared and constructor of
class I is executed.

The constructor of class II is executed and variable of class II is initialized. The member function
show()displays the contents of x and k. The contents of class I member is obtained from object y.
The dot (.) operator is used to access the elements of class I.

Access (using) Scope Public Private Protected

Access :: operator Possible Not Possible Possible

Object Possible Not Possible Not Possible

Direct Possible Not Possible Possible

1. The first way is to use scope access operators as per the following statements:

cin>>A1::name;
cin>>A1::age;

In the above statements, A1 is a class name and name and age are member variables of class A1.
When an access specifier is public or protected, the above statements are valid.

2. The second method is to use an object of base class, as per the following statements:

cin>>a.name;

cin>>a.age;

In the above statement, the member variables of the class A1 are accessed using an object of the
same class, who is the member of the derived class. This is possible only when member variables
of class A1 are public and is not possible if the member variables of class A1 are the protected or
private.

3. The third method directly uses the member variables. Direct access is possible when the
access specifier is public or protected, as per the following statements:

cin>>name;

cin>>age;

2.2.3 Abstract classes and methods

Abstract class:

A class is said to be an abstract class if it satisfies the following conditions:

• It should act as a base class.

• It should not be used to create any objects.

The use of an abstract class (often referred to as an ABC) is to provide an appropriate base class
from which other classes can inherit. Abstract classes can’t be used to instantiate the objects and
serves only as an interface. Attempting to instantiate, an object of an abstract class causes a
compilation error. Thus, if a subclass of an ABC requires to be instantiated, it has to implement
each of virtual functions, which means that it supports the interface declared by ABC.
If there is a failure to override a pure virtual function in a derived class, then attempting to
instantiate objects of that class is a compilation error.

Classes that can be used to instantiate the objects are called concrete classes. An interface
describes the behavior or capabilities of a C++ class without committing to a particular
implementation of that class.

The C++ interfaces are implemented using abstract classes. A class is made abstract by declaring
at least one of its functions as a pure virtual function.

A pure virtual function is specified by placing "= 0" in its declaration as follows:

class Box

public:

// pure virtual function

virtual double getVolume() = 0;

private:

doublelength; // Length of a box

doublebreadth; // Breadth of a box

doubleheight; // Height of a box

};

Example:

Let us consider the following example where parent class provides an interface to the base class
to implement a function called getArea():
#include <iostream.h>

using namespace std;

// Base class

classShape

{ public:

// pure virtual function providing interface framework.

virtualintgetArea() = 0;

voidsetWidth(intw)

width=w;

voidsetHeight(inth)

height= h;

protected:

intwidth;

intheight;

};
// Derived classes

classRectangle: public Shape

{ public:

intgetArea()

return(width * height);

};

classTriangle: public Shape

{ public:

intgetArea()

return(width * height)/2;

};

intmain(void)

Rectangle Rect;

Triangle Tri;
Rect.setWidth(5);

Rect.setHeight(7);

// Print the area of the object.

cout<<"Total Rectangle area: " <<Rect.getArea() <<endl;

Tri.setWidth(5);

Tri.setHeight(7);

// Print the area of the object.

cout<<"Total Triangle area: " <<Tri.getArea() <<endl;

return0;

When the above code is compiled and executed, it produces the following result:

Total Rectangle area: 35

45

Total Triangle area: 17

Abstract base class:

A class that serves only as a base class from which derived classes are derived. No objects of an
abstract base class are created. A base class that contains pure virtual function is an abstract
base class.

2.2.4 Final methods and classes


Final methods:
Final methods are variables that cannot be changed i.e. constant. It is really good practice to use
final methods using uppercase letters and underscores as separator

Similar to final variables, we can have final method. Means method that cannot be changed.
Behaviour of a method can only be changed by overriding it in another class. So, final methods
are not allowed to override.

Example:

Car.java

public class Car

final int WHEELS = 4;

public final int getNoOfWheels()

return WHEELS;

Van.java

public class Van extends Car

Main.java

public class Main

public static void main(String[] args){

Van van = new Van();

System.out.println("no of wheels of a Van "+van.getNoOfWheels());

}
}

In the above example we have one Car class with one final method getNoOfWheels() that
returns 4. We have created one new class ‘Van’ extending ‘Car’. In ‘Main’ class, we are able to
access the final method ‘getNoOfWheels’ from ‘van’ object. i.e. it is inheriting the method from
its parent class. But if we try to override it inside ‘Van’ class, one compile-time error will be
thrown mentioning that a final method cannot be overriden.

Final Class:

Final class is a class that cannot be extended i.e. it cannot be inherited. e.g. Int and Float are final
classes.

public final class Car

final int WHEELS = 4;

public final int getNoOfWheels()

return WHEELS;

Now, if we try to create another class by extending class ‘Car’, it will show one compile time error
message.

2.3 Interfaces – defining an interface, Implementing interface

Interfaces

Interfaces are similar to abstract classes but all methods are abstract and all properties are static

final. Interfaces can be inherited. As with classes the extends keyword is used for inheritance.
Java does not allow multiple inheritance for classes (i.e. A subclass is being the extension of
more than one superclass). An interface is used to tie elements of several classes together.

Interfaces are also used to separate design from coding as class method headers are specified
but not their bodies. This allows compilation and parameter consistency testing prior to the
coding phase. Interfaces are also used to set up unit testing frameworks.

As an example, we will build a Working interface for the subclasses of Animal. Since this interface
has the method called work(), that method must be defined in any class using the Working
interface.

public interface Working

public void work();

When we create a class that uses an interface, we refer the interface with the phrase
implements Interface_list. Interface_list is one or more interfaces as multiple interfaces are
allowed. Any class that implements an interface must include the code for all methods in the
interface. This ensures commonality between interfaced objects.

Implementing Interfaces

A class definition, in addition to whatever else it does, implement one or more interfaces. Once a
class states that it implements an interface, it must supply all the methods defined for that
interface, complete with executable code.

It actually does not have to implement all of them, but in that case the class cannot be
instantiated, it must be declared as an abstract class that can only be used as a base class (where
some derived class would then fully implement the interface).

To implement an interface:
• Add the class that implements the interface to the class declaration.

• Add the methods specified by the interface to the body of the class. Note that we do need to
specify the access terms on methods in a class that implements an interface.

General form

class class_name implements interface name 1 ,interface_name2...

// implementation code and code for the methods of the interfaces

It is important to note that a class may implement an interface in addition to whatever else it
might do, so it could have additional properties and methods not associated with the interface.

A class may implement more than one interface that merely adds to the list of required
methods. Comma is used to separate list for the interface names.

Example:

interface Super

final int x= 10;

void print();

class Sub implements Super

{
int y=20;

public void print()

System.out.println(“x = “+x);

System.out.println(“y = “+y);

class Sample

public static void main(String s[])

Sub SubObj=new Sub();

SubObj.print();

Super SupObj=new Sub();

SubObj.print();

Output:

x = 10
y = 20

x = 10

y = 20

2.3.1 Differences between classes and interfaces


Class and Interface both are used to create new reference types. A class is a collection of fields
and methods that operate on fields. An interface has fully abstract methods i.e. methods with
nobody. An interface is syntactically similar to the class but there is a major difference between
class and interface that is a class can be instantiated, but an interface can never be instantiated.
So let us learn some more difference between a class and interface with the help of a
comparison chart shown below.

Class Interface

Supports only multilevel and hierarchical Supports all types of inheritance are multilevel,
inheritances but not multiple inheritance. hierarchical and multiple.

"extends" keyword should be used to inherit. "implements" keyword should be used to


inherit.

Should contain only concrete methods (methods Should contain only abstract methods (methods
with body). without body).

The methods can be of any access specifier (all The access specifier must be public only.
the four types).

Methods can be final and static. Methods should not be final and static.

Variables can be private. Variables should be public only.

Classes can have constructors, Interface cannot have constructors.

It can have main() method, It cannot have main() method as main() is a


concrete method,

2.3.2 Extending interfaces


An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods
of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.

Example

// Filename: Sports.java

public interface Sports

public void setHomeTeam(String name);

public void setVisitingTeam(String name);

// Filename: Football.java

public interface Football extends Sports

public void homeTeamScored(int points);

public void visitingTeamScored(int points);

public void endOfQuarter(int quarter);

// Filename: Hockey.java

public interface Hockey extends Sports

public void homeGoalScored();

public void visitingGoalScored();

public void endOfPeriod(int period);

public void overtimePeriod(int ot);


}

The Hockey interface has four methods, but it inherits two from Sports thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.

2.3.2 Object cloning


Object Cloning is the process of creating an exact copy of the object. The clone() method which
belongs to the object class is used for this purpose.

Method Signature:

protected Object clone() throws CloneNotSupportedException

The class whose object’s copy has to be created must implement the marker interface,
Cloneable. If the class doesn’t implements the interface and when the clone operation is carried
out, then ‘CloneNotSupportedException’ is thrown.

Example:

class Employee implements Cloneable

The general intent of the clone method for any object x is,

clone ! = x;

i.e. The cloned object and the original object will have separate memory address.

clone.getClass() == x.getClass();

i.e. The cloned object should have the same class type as that of the original.

clone().equals(x);

i.e The cloned object and the original object are equal.

All the above statements will be true but are not the exact requirements.
2.4 Inner classes
Inner class means one class which is a member of another class. There are basically four types of
inner classes in java. They are,

1) Nested Inner class


2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes

Nested Inner class:

It access any private instance variable of outer class. Like any other instance variable, we can
have access modifier private, protected, public and default modifier. Interface can also be nested
and can have access specifiers.

Example demonstrates a nested class.

class Outer

// Simple nested inner class

class Inner

public void show()

System.out.println("In a nested class method");

class Main

public static void main(String[] args) {

Outer.Inner in = new Outer().new Inner();

in.show();
}

Output: In a nested class method

Note: we can’t have static method in a nested inner class because an inner class is implicitly
associated with an object of its outer class so it cannot define any static method for itself. For
example the following program doesn’t compile.

class Outer

void outerMethod()

System.out.println("inside outerMethod");

class Inner

public static void main(String[] args){

System.out.println("inside inner class Method");

Output:

Error illegal static declaration in inner class

Outer.Inner public static void main(String[] args)

modifier ‘static’ is only allowed in constant


variable declaration

Method-Local Inner Class

In Java, we can write a class within a method and this will be a local type. Local variables, the
scope of the inner class is restricted within the method.

A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.

Example

Live Demo

public class Outerclass

// instance method of the outer class

void my_Method()

int num = 23;

// method-local inner class

class MethodInner_Demo

public void print()

System.out.println("This is method inner class "+num);

} // end of inner class

// Accessing the inner class

MethodInner_Demo inner = new MethodInner_Demo();

inner.print();
}

public static void main(String args[])

Outerclass outer = new Outerclass();

outer.my_Method();

If you compile and execute the above program, you will get the following result −

Output:

This is method inner class 23

Static nested classes

Static nested classes are not technically an inner class. They are like a static member of outer
class.

Example:

class Outer

private static void outerMethod()

System.out.println("inside outerMethod");

// A static inner class

static class Inner

{
public static void main(String[] args)

System.out.println("inside inner class Method");

outerMethod();

Output:

inside inner class Method

inside outerMethod

Anonymous inner classes

Anonymous inner classes are declared without any name at all. They are created in two ways.

a) As subclass of specified type

class Demo

void show()

System.out.println("i am in show method of super class");

class Flavor1Demo

// An anonymous class with Demo as base class

static Demo d = new Demo()


{

void show()

super.show();

System.out.println("i am in Flavor1Demo class");

};

public static void main(String[] args)

d.show();

Output

i am in show method of super class

i am in Flavor1Demo class

In the above code, we have two class Demo and Flavor1Demo. Here demo act as super class and
anonymous class acts as a subclass, both classes have a method show(). In anonymous class
show() method is overridden.

b) As implementer of the specified interface

class Flavor2Demo

// An anonymous class that implements Hello interface

static Hello h = new Hello()

public void show()


{

System.out.println("i am in anonymous class");

};

public static void main(String[] args)

h.show();

interface Hello

void show();

Output:

i am in anonymous class

In above code we create an object of anonymous inner class but this anonymous inner class is an
implementer of the interface Hello. Any anonymous inner class can implement only one
interface at one time. It can either extend a class or implement interface at a time.

2.5 Array Lists


Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

The important points about Java ArrayList class are:

• Java ArrayList class can contain duplicate elements.

• Java ArrayList class maintains insertion order.

• Java ArrayList class is non synchronized.


• Java ArrayList allows random access because array works at the index basis.

• In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.

Constructors in Java ArrayList:

ArrayList(): This constructor is used to build an empty array list.

ArrayList(Collection c): This constructor is used to build an array list initialized with the elements
from collection c.

ArrayList(int capacity): This constructor is used to build an array list with initial capacity being
specified.

Methods of Java ArrayList:


void add(int index, Object element) - It is used to insert the specified element at the specified
position index in a list.

boolean addAll(Collection c) - It is used to append all of the elements in the specified collection
to the end of this list, in the order that they are returned by the specified collection's iterator.

void clear() - It is used to remove all of the elements from this list.

int lastIndexOf(Object o) - It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.

Object[] toArray() - It is used to return an array containing all of the elements in this list in the
correct order.

Object[] toArray(Object[] a) - It is used to return an array containing all of the elements in this
list in the correct order.

boolean add(Object o) - It is used to append the specified element to the end of a list.

boolean addAll(int index, Collection c) - It is used to insert all of the elements in the specified
collection into this list, starting at the specified position.

Object clone() - It is used to return a shallow copy of an ArrayList.


int indexOf(Object o) - It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.

void trimToSize() - It is used to trim the capacity of this ArrayList instance to be the list's current
size.

2.6 Strings

Strings are widely used in Java programming which are the sequence of characters. In Java
programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes.

For Example: String s= "welcome";

2) By new keyword

String s=new String("Welcome"); //Creates two objects and one reference variable.

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of
char values.

char charAt(int index) - Returns char value for the particular index.
int length() - Returns string length.

static String format(String format, Object... args) - Returns formatted string.

static String format(Locale l, String format, Object... args) - Returns formatted string with given
locale.

String substring(int beginIndex)- Returns substring for given beginIndex.

String substring(int beginIndex, int endIndex) - Returns substring for given beginIndex and
endIndex.

boolean contains(CharSequence s) - Returns true or false after matching the sequence of char
value.

static String join(CharSequence delimiter, CharSequence... elements) - returns a joined string.

static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) - Returns


a joined string.

boolean equals(Object another) - Checks the equality of string with object.

boolean is Empty() - Checks if string is empty.

String replace(char old, char new) - Replaces all occurrences of specified char value.

String replace(CharSequence old, CharSequence new) - Replaces all occurrences of specified


CharSequence.

String trim() - Returns trimmed string omitting leading and trailing spaces.

String split(String regex) - Returns splitted string matching regex.

Operations on strings

String concatenation
The + sign can be used to concatenate(join) two strings. During the concatenation, non-string
operands are converted into string type.

Example

String s=“Sunil”+“kumar”;

Substring extraction

Substring from a large string can be extracted using substring() method.

Example

String s=new String(“Sunilkumar”);

String n1=s.substring(0,5); //not including 5th character

String n2=s.substring(5);

“Sunil” will be stored in n1. “kumar” will be stored in n2.

Converting to lowercase

String characters can be converted into lowercase letters by using toLowerCase() method.

Example

Newstr=Oldstr.toLowerCase();

Converting to uppercase

String characters can be converted into uppercase letters by using toLowerCase() method.

Example

Newstr=Oldstr.toUpperCase();
Replacing characters

Characters in a string are replaced by using the method replace().

Example

Newstr=Olddstr.replace(‘x’,’-‘); //replace all occurrence's of ‘x’ by ‘-’.

Removing spaces in the edges

Spaces in the beginning and endings can be removed by using the method trim().

Example

Newstr=Oldstr.trim();

Comparing strings

Strings are compared by using 4 methods. equals(), equalsIgnoreCase(), compareTo() and


compareToIgnoreCase().

Example

str1.equals(str2); // if str1 and str2 are equal it returns true, otherwise false.

str1.equalsIgnoreCase (str2); //same as above, but ignores the case.

str1,compareTo(str2); // str1=str2 -0 , str1>str2 - positive, str1<str2 - negative.

str1 ,compareToIgnoreCase(str2); // same as compare to function, but ignores the case.

Finding string length

To get the length of a string length() method is used.


Example

int len =str.length();

Getting a character

A character can be extracted from a string using the charAt() method.

Example

str.charAt( 10); //extracts the 10th character of str

Methods available in string handling

1. ChartAt()

To extract a single character from a string, can refer directly to an individual character.

via CharAt() method

Syntax - char CharAt(int where) - index of character that we want to obtain.

CharAt() returns the character at the specified location. For example,

char ch;

ch = “abc”.charAt(1);

It assigns the value ‘b’ to ‘ch’.

2. getChars()

More than one character can be extracted by using this method getchars()

General form

void getChars(int sourceStart, int sourceEnd, Char target[ ], int targetStart)


3. Equals()

To compare two strings for equality, use equals().

General form

boolean equals(object str)

where str is the string object being compared with the invoking string object.

String S1 = “Hello”

String S2 = “Good-bye”;

System.out.println(S 1 .equals(S2));

It displays false as the result.

4. Replace()

Replace method replaces all occurrence of one character in the invoking string with another
character.

General form

String replace(char original, char replacement).

original - Specifies the character to be replaced by the character.

replacement - Specifies the character to be replaced.


UNIT III EXCEPTION HANDLING AND I/O
Exceptions - exception hierarchy - throwing and catching exceptions – built-in exceptions,
creating own exceptions, Stack Trace Elements. Input / Output Basics – Streams –Byte streams
and Character streams – Reading and Writing Console – Reading and Writing Files.
3.1 Exceptions - exception hierarchy - throwing and catching exceptions
Exceptions are the situations which must be avoided during program executions. Exceptions are
caused by errors, invalid inputs or invalid processing. Exceptions results in either program
termination or generating unexpected outputs.

Exception Handling

Exception handling is a process of handling exceptional situations that may occur in a program
due to the above stated reasons in such a way that:

1. The program will terminate gracefully i.e. it will give a proper message and then will terminate
the program.

2. After giving the proper message stating the reason of the exception the program continues to
execute after correcting the error.

In the C++ language, exception handling is performed using the following keywords:

• try
• throw
• catch

try: A try block identifies a block of code for which particular exceptions will be activated. It is
followed by one or more catch blocks.

throw: A program throws an exception when a problem shows up. This is done using a throw
keyword.

catch: A program catches an exception with an exception handler at the place in a program
where we want to handle the problem. The catch keyword indicates the catching of an
exception.

Throwing Exceptions

Exceptions can be thrown anywhere within a code block using throw statements. The operand of
the throw statements determines the type of the exception and it can be any expression and the
type of the result of the expression determines the type of exception thrown.
Catching Exceptions

The catch block following the try block catches any exception. We can specify the type of
exception we want to catch and it can be determined by the exception declaration that appears
in the parentheses following the keyword catch.

Program

#include <iostream>

using namespace std;

int main()

int x = -1;

// Some code

cout << "Before try \n";

try

cout << "Inside try \n";

if (x < 0)

throw x;

cout << "After throw (Never executed) \n";

catch (int x ) {
cout << "Exception Caught \n";

cout << "After catch (Will be executed) \n";

return 0;

Output:

Before try

Inside try

Exception Caught

After catch (Will be executed).

The use of the exception handling mechanism is to provide a means to detect and report the
“exceptional circumstance” so that the appropriate action can be taken.

Key words used in exception handling

The keywords used in exception handling are as follows:

• throw(Find the problem)

• try(Inform that an error has occurred)

• catch(Receive the error information)

• Handle (Take corrective actions)

Without exception handling with exception handling


When an exception occurs, control goes to the • Programs are allowed to trap exceptions.
operating system, the following action takes
• There is a possibility to fix the problem and
place.
• An error message is displayed. continuing exception.

• The program is terminated.

TRY BLOCK

Keyword try is used to preface a block of statements (surrounded by braces) which might
generate exceptions.When an exception is detected, it is thrown using a throw statement in the
try block.

CATCH BLOCK

Catch block is defined by the keyword catch, catches the exception thrown by the throw
statement in the try block and handles it appropriately.

Exception Handling
Syntax:

Syntax:

try //try block

…….

throw exception; //
Block of statements
which detects and
throws an exception

catch(type arg) // Catches exception


{

…….

…….. // Block of statements that handles the exception

Example:

#include <iostream>

int main()

cout << “start execution”;

try

{ // start

a try block cout << Inside try

block\n”;

throw 100; // throw an error

cout << “This will not execute”;

catch (int i)

{ // catch an error

cout << “caught an exception “;

cout << i ; cout << “End”;


return 0;

Exception Types:

Synchronous Exception:

• Out of range

• Over flow

Asynchronous Exception:

• Error that are caused beyond the control of the program.

• Keyboard interrupts.

In C++ only synchronous exception can be handled.

Factors determining Exception

• Access to an array outside of it’s bounds.

• Division by zero.

• Running out of disk space.

• Running out of memory.

Need for Exception Handling:

• Unconditional termination & programmer preferred termination.

• Dividing the error handling.


• Object destroy problem.

• Separating error reporting and error handling.

When the program enters the try block it is said to be in the guarded section.

In the below program, when the value of j is zero, an exception is created and thrown. Note that
the statement after throw statement in the try block is not executed.

Once the exception is thrown the catch block catches the value and handles it. After that the
program continues its normal execution.

Example:

#include<iostream.h>

int main()

int i,j;

cout<<” starts here\n”; i=10;

j=0;

try

//start a try block

cout<<”Inside try block \n”;

if(j==0)

{
throw j;//throw an error

cout<<”This will not be printed \n”;}

cout<<”RESULT IS”<<i/j;

catch(int a)

{ //catch an error

cout<<”The Number Caught is:”;

cout<<a<<”\n’;

cout<<”Ends here”;

return 0;

Functions Generating Exceptions

C++ allows functions to generate exceptions. These functions can’t be called as an ordinary
function. Enclose the function call with a try catch block.

Syntax:

try

{ function(arg);

}
catch(type arg)

------}

Example

#include<iostream>

void compute(int a,int b)

int c;

if (b==0)

throw b;

else

c=a/b;

cout<<”RESULT OF THE DIVISON”<<c;

void main()

int x,y;
cout<<”Enter Two Numbers”;

cin>>x>>y;

try

compute(x/y); //fun generating exception

catch(int k)

cout<<”Divide By Zero exception”;

Throwing Mechanisms:

• An exception is thrown by using the keyword “throw” from inside the try block.

• The throw expression accepts one parameter, which is passed as an argument to the exception
handler.

Eg. throw b;

The throw statement will have the following.

Example:

throw (exception)
throw exception

throw

Catching Mechanisms

• If the data type specified by a catch, matches that of the exception, then catch statement is
executed.

• When an exception is caught, argument will receive it’s value.

Multiple Catch Statements

• The try can have multiple catches.

• If there are multiple catches for a try, only one of the matching catch is selected and its
corresponding catch block is then executed.

Syntax:

try

any statements

if (some condition) throw value1;

else if (some other condition)

throw value2;

else if (some last condition)

throw valueN;

}
catch (type1 name)IPLUS

any statements

catch (type2 name)

any statements

catch (typeN name)

any statements

Example:

#include<iostream>

void multiple_catch(int value)

try

if (value1==0) //throw an int value


throw 1;

else if (value1==1) //throw a char

throw “a”;

else //throw float

throw 1.1;

catch(char c)

cout<<”Character value is thrown” <<c;

catch(int i)

cout<<”Integer value is thrown”<<i;

catch(float f)

cout<<”Float value is thrown”<<f;

}}

void main()
{

cout<<”Main Program”<<endl;

multiple_catch(0);

multiple_catch(1);

multiple_catch(5);

Syntax:

try

….

throw a;

catch (char c)

throw; //rethrow same exception in catch block in main()

Example:

#include <iostream.h>

class sam
{

int exno1;

public:

sam (int errno)

exno1=errno;

void shoex()

cout<<”error no:”<<exno1;

}};

void ergen()

try

sam s1(20);

int c;

cin>>c;

switch (c)
{

case 1:

throw 10;

case 2:

throw „a‟;

case 3:

throw s1;

case 4:

throw “welcome”;

catch (int ie)

cout<<”ie”<<ie;

throw; //rethrowing

catch (char ce)

cout <<”ce”<<ce;

throw; //rethrowing
}

void main ()

try

ergen();

throw 10;

catch (int)

cout <<”caught integer”;

catch(char)

cout<<”caught char”;

catch (sam s2)

{
s2.show x();

Terminate Function

Terminate () is the function which calls abort() to exit the program in the event of run time error
related to exceptions.

The user provide his or her own terminate function instead of built-in terminate.

Use:

Used to close all open files & deallocate resources before quitting the program.

Syntax: set_terminate (myterminate);

Unexpected Function

If the function throws an exception which is not permitted, then a function unexpected () is
called, which in turn calls abort.

We can use set_unexpected in similar to set_terminate

Syntax:

set_unexcepted(my unexcepted);

Example:

#include <iostream.h>

void myunexpected ()

cout << "unexpected called\n";


throw 0; // throws int (in exception-specification)

void myfunction

() throw (int)

throw 'x'; // throws char (not in exception-specification)

int main (void)

set_unexpected (myunexpected);

try

myfunction();

catch (int)

cout << "caught int\n";

catch (...)
{

cout << "caught some other exception type\n";

return 0;

Uncaught Exception()

This function returns true if an exception has been thrown but not yet caught. Once caught, the
function returns false.

Syntax:

bool

uncaught_exceptions.

if

(uncaught_exception)

))

//Do not call the function which might throw an exception

Otherwise

{
Follow the natural sequence of the destructor Algorithm

3.2 Built-in exceptions


Java defines several exception classes inside the standard package java.lang.

The most general of these exceptions are subclasses of the standard type RuntimeException.
Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.

Java defines several other types of exceptions that relate to its various class libraries. Following is
the list of Java Unchecked RuntimeException.

Examples of Built-in Exception:

Arithmetic exception: It is thrown when an exceptional condition has occurred in an arithmetic


operation.

// Java program to demonstrate

// ArithmeticException

class ArithmeticException_Demo

public static void main(String args[])

Try

int a = 30, b = 0;

int c = a / b; // cannot divide by zero

System.out.println("Result = " + c);


}

catch (ArithmeticException e)

System.out.println("Can't divide a number by 0");

Output:

Can't divide a number by 0

ArrayIndexOutOfBounds Exception:

It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.

// Java program to demonstrate

// ArrayIndexOutOfBoundException

class ArrayIndexOutOfBound_Demo

public static void main(String args[])

try

int a[] = new int[5];

a[6] = 9; // accessing 7th element in an array of size 5//


}

catch (ArrayIndexOutOfBoundsException e)

System.out.println("Array Index is Out Of Bounds");

Output:

Array Index is Out Of Bounds

ClassNotFoundException:

This Exception is raised when we try to access a class whose definition is not found.

// Java program to illustrate the

// concept of ClassNotFoundException

class Bishal

class Geeks

class MyClass

public static void main(String[] args)


{

Object o = class.forName(args[0]).newInstance();

System.out.println("Class created for" + o.getClass().getName());

Output:

ClassNotFoundException

FileNotFoundException : This Exception is raised when a file is not accessible or does not open.

// Java program to demonstrate

// FileNotFoundException

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

class File_notFound_Demo

public static void main(String args[])

try

{ // Following file does not exist

File file = new File("E:// file.txt");

FileReader fr = new FileReader(file);

}
catch (FileNotFoundException e)

System.out.println("File does not exist");

Output:

File does not exist

IOException: It is thrown when an input-output operation failed or interrupted.

// Java program to illustrate IOException

import java.io.*;

class Geeks

public static void main(String args[])

FileInputStream f = null;

f = new FileInputStream("abc.txt");

int i;

while ((i = f.read()) != -1)

System.out.print((char)i);

}
f.close();

Output:

error: unreported exception IOException; must be caught or declared to be thrown

InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing,


and it is interrupted.

// Java Program to illustrate

// InterruptedException

class Geeks

public static void main(String args[])

Thread t = new Thread();

t.sleep(10000);

Output:

error: unreported exception InterruptedException; must be caught or declared to be thrown

NoSuchMethodException: It is thrown when accessing a method which is not found.

// Java Program to illustrate

// NoSuchMethodException
class Geeks {

public Geeks()

Class i;

try {

i = Class.forName("java.lang.String");

try {

Class[] p = new Class[5];

catch (SecurityException e)

e.printStackTrace();

catch (NoSuchMethodException e)

e.printStackTrace();

catch (ClassNotFoundException e)

e.printStackTrace();

}
}

public static void main(String[] args)

new Geeks();

Output:

error: exception NoSuchMethodException is never thrown in body of corresponding try


statement

NullPointerException: This exception is raised when referring to the members of a null object.
Null represents nothing

// Java program to demonstrate NullPointerException

class NullPointer_Demo {

public static void main(String args[])

try

String a = null; // null value

System.out.println(a.charAt(0));

catch (NullPointerException e) {

System.out.println("NullPointerException..");
}

Output:

NullPointerException..

NumberFormatException: This exception is raised when a method could not convert a string into
a numeric format.

// Java program to demonstrate

// NumberFormatException

class NumberFormat_Demo

public static void main(String args[])

try

// "akki" is not a number

int num = Integer.parseInt("akki");

System.out.println(num);

catch (NumberFormatException e)

System.out.println("Number format exception");


}

Output:

Number format exception

StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an


index is either negative than the size of the string.

// Java program to demonstrate

// StringIndexOutOfBoundsException

class StringIndexOutOfBound_Demo

public static void main(String args[])

try

String a = "This is like chipping "; // length is 22

char c = a.charAt(24); // accessing 25th element

System.out.println(c);

catch (StringIndexOutOfBoundsException e) {

System.out.println("StringIndexOutOfBoundsException");

}
}

Output:

StringIndexOutOfBoundsException

3.2.1 Creating own exceptions

Java provides us facility to create our own exceptions which are basically derived classes of
Exception. For example MyException in below code extends the Exception class.

We pass the string to the constructor of the super class- Exception which is obtained using
“getMessage()” function on the object created.

// A Class that represents use-defined expception

class MyException extends Exception

public MyException(String s)

// Call constructor of parent Exception

super(s);

// A Class that uses above MyException

public class Main


{

// Driver Program

public static void main(String args[])

try

// Throw an object of user defined exception

throw new MyException("GeeksGeeks");

catch (MyException ex)

System.out.println("Caught");

// Print the message from MyException object

System.out.println(ex.getMessage());

Output:

Caught
GeeksGeeks

In the above code, constructor of MyException requires a string as its argument. The string is
passed to parent class Exception’s constructor using super(). The constructor of Exception class
can also be called without a parameter and call to super is not mandatory.

// A Class that represents use-defined expception

class MyException extends Exception

// A Class that uses above MyException

public class setText

// Driver Program

public static void main(String args[])

try

// Throw an object of user defined exception

throw new MyException();

catch (MyException ex)


{

System.out.println("Caught");

System.out.println(ex.getMessage());

Output:

Caught

Null

3.2.2 Stack Trace Elements


An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents
a single stack frame. All stack frames except for the one at the top of the stack represent a
method invocation. The frame at the top of the stack represents the execution point at which
the stack trace was generated.

This class describes single stack frame, which is an individual element of a stack trace when an
exception occur.

• All stack frames except for the one at the top of the stack represent a method invocation.

• The frame at the top of the stack represent the execution point of which the stack trace was
generated.

• Each stack frame represents an execution point, which includes such things as the name of the
method, the name of file and the source code line number.

• An array of StackTraceElement is returned by getStackTrace() method of the Throwable class.

Constructor: Creates a stack trace element representing the specified execution point.
StackTraceElement(String declaringClass,

String methodName, String fileName, int lineNumber)

Class methods:

boolean equals(Object obj) - This method returns true, if the specified object is another
StackTraceElement instance representing the same execution point as this instance.

String getClassName() - This method returns the fully qualified name of the class containing the
execution point represented by this stack trace element.

String getFileName() - This method returns the name of the source file containing the execution
point represented by this stack trace element.

int getLineNumber() - This method returns the line number of the source line containing the
execution point represented by this stack trace element.

String getMethodName() - This method returns the name of the method containing the
execution point represented by this stack trace element.

int hashCode() - This method returns a hash code value for this stack trace element.

boolean isNativeMethod() - This method returns true if the method containing the execution
point represented by this stack trace element is a native method.

String toString() - This method returns a string representation of this stack trace element.

3.3 Input / Output Basics


Java I/O (Input and Output) is used to process the input and produce the output based on the
input.

Java uses the concept of stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations. We can perform the file handling in java by java
IO API.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It is called a stream
because it is like a stream of water that continues to flow.

In java, three streams are created for us automatically. They are:

1) Standard output stream: System.out


2) Standard input stream: System.in
3) Standard error stream: System.err

Standard Input: This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and is represented as System.in.

Standard Output: This is used to output the data produced by the user's program and usually a
computer screen is used for standard output stream and is represented as System.out.

Standard Error: This is used to output the error data produced by the user's program and usually
a computer screen is used for standard error stream and is represented as System.err.

Working of standard Output stream and Input stream

OutputStream class: OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts the output bytes and sends
them to some sink.

Commonly used methods of OutputStream class are:


1) public void write(int)throws IOException: It is used to write a byte to the current output
stream.

2) public void write(byte[])throws IOException: It is used to write an array of byte to the current
output stream.

3) public void flush()throws IOException: It flushes the current output stream.

4) public void close()throws IOException: It is used to close the current output stream.

Output stream hierarchy in I/O

InputStream class: InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.

Commonly used methods of InputStream class are:

1) public abstract int read()throws IOException: It reads the next byte of data from the input
stream. It returns -1 at the end of file.

2) public int available()throws IOException: It returns an estimate of the number of bytes that
can be read from the current input stream.

3) public void close()throws IOException: It is used to close the current input stream.
Input

stream hierarchy in I/O


Java.io package

The classes form a reasonably structured hierarchy. Most of the package consists of byte
streams--subclasses of InputStream or OutputStream and (in Java 1.1) character streams--
subclasses of Reader or Writer. Each of these stream types has a specific purpose, despite its
size, java.io is a straightforward package to understand and to use.

Before we consider the stream classes in the package, let us examine the important non-stream
classes. File represents a file or directory name in a system-independent way and provides
methods for listing directories, querying file attributes and renaming and deleting files.
FilenameFilter is an interface that defines a method that accepts or rejects specified filenames.

It is used by java.awt.FileDialog and File to specify what types of files should be included in
directory listings. RandomAccessFile allows us to read from or write to arbitrary locations of a
file. Often, we will prefer sequential access to a file and should use one of the stream classes.

InputStream and OutputStream are abstract classes that define methods for reading and writing
bytes. Their subclasses allow bytes to be read from and written to a variety of sources and sinks.
FileInputStream and FileOutputStream read from and write to files. ByteArrayInputStream and
ByteArrauOutputStream read from and write to an array of bytes in memory. PipedInputStream
reads bytes from a PipedOutputStream and PipedOutputStream writes bytes to a
PipedInputStream. These classes work together to implement a pipe for communication
between threads.
FilterInputStream and FilterOutputStream are special; they filter the input and output bytes.
When we produce a FilterInputStream, we tend to specify an InputStream for it to filter. When
we call the read() of a FilterInputStream, it calls the read() method of its InputStream, processes
the bytes it reads and returns the filtered bytes. Similarly, when we produce a
FilterOutputStream, we specify an OutputStream to be filtered. Calling the write() method of a
FilterOutputStream causes it to process our bytes in some way and then pass those filtered bytes
to the write() method of its OutputStream.
BufferedInputStream

public class BufferedInputStream extends FilterInputStream

// Public Constructors

public BufferedInputStream (java.io.InputStream in);

public BufferedInputStream (java.io.InputStream in, int size);

// Public Methods Overriding FilterInputStream

public int available () throws IOException; //synchronized

public void close () throws IOException;

public void mark (int readlimit); //synchronized

public boolean markSupported (); //constant

public int read () throws IOException; //synchronized

public int read (byte[ ] b, int off, int len) throws IOException; //synchronized

public void reset () throws IOException; //synchronized

public long skip (long n) throws IOException; //synchronized

// Protected Instance Fields

protected byte[ ] buf ;

protected int count ;

protected int marklimit ;

protected int markpos ;

protected int pos ;

}
Hierarchy:Object→java.io.InputStream→FilterInputStream→BufferedInputStream

BufferedOutputStream

public class BufferedOutputStream extends FilterOutputStream {

// Public Constructors

public BufferedOutputStream (java.io.OutputStream out);

public BufferedOutputStream (java.io.OutputStream out, int size);

// Public Methods Overriding FilterOutputStream

public void flush () throws IOException; //synchronized

public void write (int b) throws IOException; //synchronized

public void write (byte[ ] b, int off, int len) throws IOException; //synchronized

// Protected Instance Fields

protected byte[ ] buf ;

protected int count ;

Hierarchy:Object→java.io.OutputStream→FilterOutputStream→BufferedOutputStream

3.4 Streams –Byte streams and Character streams


Stream

A stream can be defined as a sequence of data. There are two kinds of Streams. They are,

InPut Stream − The InputStream is used to read data from a source.

OutPut Stream − The OutputStream is used for writing data to a destination.


Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream.

Following is an example which makes use of these two classes to copy an input file into an
output file.

Example

import java.io.*;

public class CopyFile

public static void main(String args[]) throws IOException

FileInputStream in = null;

FileOutputStream out = null;

try

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;

while ((c = in.read()) != -1)


{

out.write(c);

finally

if (in != null)

in.close();

if (out != null)

out.close();

Out put:

Now let's have a file input.txt with the following content.

This is test for copy file.

As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt.
So let's put the above code in CopyFile.java file and do the following,

$javac CopyFile.java

$java CopyFile

Character Streams

Java byte streams are used to perform input and output of 8-bit bytes, whereas java character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an input
file into an output file.

Example:

import java.io.*;

public class CopyFile

public static void main(String args[]) throws IOException

FileReader in = null;

FileWriter out = null;

try

in = new FileReader("input.txt");

out = new FileWriter("output.txt");


int c;

while ((c = in.read()) != -1)

out.write(c);

finally

if (in != null)

in.close();

if (out != null)

out.close();

Out put:

Now let's have a file input.txt with the following content:

This is test for copy file.


As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following:

$javac CopyFile.java

$java CopyFile

3.5 Reading and Writing Console


Reading console:

In java, there are three different ways for reading input from the user in the command line
environment(console).

1.Using Buffered Reader Class

This is the java classical method to take input, Introduced in JDK1.0. This method is used by
wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the command line.

Advantages:

The input is buffered for efficient reading.

Disadvantage:

The wrapping code is hard to remember.

Program:

// Java program to demonstrate BufferedReader

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Test

{
public static void main(String[] args) throws IOException

//Enter data using BufferReader

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

// Reading data using readLine

String name = reader.readLine();

// Printing the read line

System.out.println(name);

Input:

Geek

Output:

Geek

2. Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class
is to parse primitive types and strings using regular expressions, however it is also can be used to
read input from the user in the command line.

Advantages:

• Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.

• Regular expressions can be used to find tokens.

Drawback:

• The reading methods are not synchronized

To see more differences, please see this article.


// Java program to demonstrate working of Scanner in Java

import java.util.Scanner;

class GetInputFromUser

public static void main(String args[])

// Using Scanner for Getting Input from User

Scanner in = new Scanner(System.in);

String s = in.nextLine();

System.out.println("You entered string "+s);

int a = in.nextInt();

System.out.println("You entered integer "+a);

float b = in.nextFloat();

System.out.println("You entered float "+b);

Input:

GeeksforGeeks

12

3.4

Output:

You entered integer 12


Enter a float

You entered float 3.4


3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In
addition, it can be used for reading password-like input without echoing the characters entered
by the user; the format string syntax can also be used (like System.out.printf()).

Advantages:

• Reading password without echoing the entered characters.

• Reading methods are synchronized.

• Format string syntax can be used.

Disadvantages:

Does not work in non-interactive environment (such as in an IDE).

Example:

// Java program to demonstrate working of System.console()

// Note that this program does not work on IDEs as

// System.console() may require console

public class Sample

public static void main(String[] args)

// Using Console to input data from user

String name = System.console().readLine();

System.out.println(name);

}
}

Writing console:

Console output is most easily accomplished with print() and println() methods, as described
earlier. These methods are defined by the class PrintStream which is the type of object
referenced by System.in. Even though System.out is a byte stream, using it for a simple program
output is still acceptable.

Because the PrintStream is an output stream derived from the OutputStream, it also implements
the low-level method write(). Thus, write() can be used to write to the console.

The simplest form of write() defined by the PrintStream is shown below :

void write(int byteval)

This method writes the byte specified by byteval. Although byteval is declared as an integer, only
the low-order eight bits are written.

Following is a short example that uses write() to output the character 'X' followed by a newline
to the screen:

/* Java Program Example - Java Write Console Output

* This program writes the character X followed by newline

* This program demonstrates System.out.write() */

class WriteConsoleOutput

public static void main(String args[])

int y;

y = 'X';

System.out.write(y);
System.out.write('\n');

This Java program will produce the following output:

We will not often use write()


to perform console output
(although doing so might be
useful in some situations)
because print() and println()
are substantially easier to use.

3.6 Reading and Writing Files


Java FileWriter and FileReader classes are used to write and read data from text files. It is
recommended not to use the FileInputStream and FileOutputStream classes. If we have to read
and write any textual information as these are Byte stream classes.

FileWriter

FileWriter is useful to create a file writing characters into it.

• This class inherits from the OutputStream class.

• The constructors of this class assume that the default character encoding and the default byte-
buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on
a FileOutputStream.

• FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider
using a FileOutputStream.

Constructors:

FileWriter(File file) – Constructs a FileWriter object given a File object.

FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.

FileWriter (String fileName) – constructs a FileWriter object given a file name.

FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name
with a Boolean indicating whether or not to append the data written.

Methods:

public void write (int c) throws IOException – Writes a single character.

public void write (char [] stir) throws IOException – Writes an array of characters.

public void write(String str)throws IOException – Writes a string.

public void write(String str,int off,int len)throws IOException – Writes a portion of a string. Here
off is offset from which to start writing characters and len is number of character to write.

Reading and writing take place character by character, which increases the number of I/O
operations and effects performance of the system.BufferedWriter can be used along with
FileWriter to improve speed of execution.

Following program depicts how to create a text file using FileWriter

// Creating a text File using FileWriter

import java.io.FileWriter;

import java.io.IOException;

class CreateFile

public static void main(String[] args) throws IOException

// Accept a string

String str = "File Handling in Java using "+" FileWriter and FileReader";

// attach a file to FileWriter

FileWriter fw=new FileWriter("text");


// read character wise from string and write into FileWriter

for (int i = 0; i < str.length(); i++)

fw.write(str.charAt(i));

//close the file

fw.close();

FileReader

FileReader is useful to read data in the form of characters from a ‘text’ file.

• This class inherit from the InputStreamReader Class.

• The constructors of this class assume that the default character encoding and the default byte-
buffer size are appropriate. To specify these values ourself, construct an InputStreamReader on a
FileInputStream.

• FileReader is meant for reading streams of characters. For reading streams of raw bytes,
consider using a FileInputStream.

Constructors:

FileReader(File file) – It creates a FileReader , given the File to read from.

FileReader(FileDescripter fd) – It creates a new FileReader , given the FileDescripter to read from.

FileReader(String fileName) – It creates a new FileReader , given the name of the file to read
from.

Methods:

public int read () throws IOException – Reads a single character. This method will block until a
character is available, an I/O error occurs, or the end of the stream is reached.

public int read(char[] cbuff) throws IOException – Reads characters into an array. This method
will block until some input is available, an I/O error occurs, or the end of the stream is reached.
public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a
portion of an array. This method will block until some input is available, an I/O error occurs, or
the end of the stream is reached.

Following program depicts how to read from the ‘text’ file using FileReader:

// Reading data from a file using FileReader

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

class ReadFile

public static void main(String[] args) throws IOException

// variable declaration

int ch;

// check if File exists or not

FileReader fr=null;

try

fr = new FileReader("text");

catch (FileNotFoundException fe)

{
System.out.println("File not found");

// read from FileReader till the end of file

while ((ch=fr.read())!=-1)

System.out.print((char)ch);

// close the file

fr.close();

}
UNIT IV MULTITHREADING AND GENERIC PROGRAMMING
Differences between multi-threading and multitasking, thread life cycle, creating threads,
synchronizing threads, Inter-thread communication, daemon threads, thread groups. Generic
Programming – Generic classes – generic methods – Bounded Types – Restrictions and
Limitations.
4.1 Differences between multi-threading and multitasking
Multi-threading

Multi-threading is different from multitasking in a sense that multitasking allows multiple tasks
at the same time, whereas, the Multi-threading allows multiple threads of a single task
(program, process) to be processed by CPU at the same time.

Multitasking

Multitasking is a process of executing multiple tasks. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:

1. Process-based Multitasking(Multiprocessing).

2. Thread-based Multitasking(Multi threading).

Basis for Comparison Multitasking Multi threading


Basic Multitasking let CPU to Multi-threading let CPU to
execute multiple tasks at the execute multiple threads of a
same time. process simultaneously.
Switching In multitasking CPU switches In multi-threading CPU
between programs frequently. switches between the threads
frequently.
Memory and Resource In multitasking system has to In multi-threading system has
allocate separate memory and to allocate memory to a
resources to each program process, multiple threads of
that CPU is executing. that process shares the same
memory and resources
allocated to the process

4.1.1 Thread life cycle

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated

Life
cycle
of a
thread

1)
New:
The

thread is in new state, if we create an instance of Thread class but before the invocation of start()
method.

2) Runnable: The thread is in runnable state, after invocation of start() method but the thread
scheduler has not selected it to be the running thread.

3) Running: The thread is in running state, if a thread scheduler has selected it.

4) Non-Runnable (Blocked): This is the state, when the thread is still alive, but is currently not
eligible to run.

5) Terminated: A thread is in terminated state or dead state, when its run() method exits.

Creating a thread

Java defines two ways by which a thread can be created.


1. By implementing the Runnable interface.

2. By extending the Thread class.

Create Thread by implementing Runnable interface

If our class is intended to be executed as a thread then we can achieve this by implementing
Runnable interface. We have to follow the three basic steps:

Step 1: As a first step, we need to implement a run() method provided by Runnable interface.
This method provides entry point for the thread.

Syntax of run() method: public void run( )

Step 2: At second step, we will instantiate a Thread object using the following constructor:

Thread (Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnable interface and
threadName is the name given to the new thread.

Step 3: Once Thread object is created, we can start it by calling start( )method, which executes a
call to run( ) method.

Syntax of start() method: void start( );

Program

class MultithreadingDemo implements Runnable

public void run()

System.out.println("My thread is in running state.");


}

public static void main(String args[])

MultithreadingDemo obj=new MultithreadingDemo();

Thread tobj =new Thread(obj);

tobj.start();

Output: My thread is in running state.

Advantage of Java Multithreading

1) It does not block the users because threads are independent and we can perform multiple
operations at same time.

2) We can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

4.1.2 Creating threads


There are two ways to create a thread:

• By extending thread class.

• By implementing runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends object class and implements runnable interface.

Commonly used constructors of thread class:

Thread()

Thread(String name)

Thread(Runnable r)

Thread(Runnable r, String name)

Some methods of thread class:

public void run(): Used to perform action for a thread.

public void start(): Starts the execution of the thread.JVM calls the run() method on the thread.

public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.

public void join(): Waits for a thread to die.

public int getPriority(): Returns the priority of the thread.

public int setPriority(int priority): Changes the priority of the thread.

public String getName(): Returns the name of the thread.

public void setName(String name): Changes the name of the thread.

public Thread currentThread(): Returns the reference of currently executing thread.

public int getId(): Returns the id of the thread.

public Thread.State getState(): Returns the state of the thread.

public boolean isAlive(): Tests if the thread is alive.

public void yield(): Causes the currently executing thread object to temporarily pause and allow
other threads to execute.
public void suspend(): It is used to suspend the thread(depricated).

public void resume(): It is used to resume the suspended thread(depricated).

public boolean isDaemon(): Tests if the thread is a daemon thread.

public boolean isInterrupted(): Tests if the thread has been interrupted.

public static boolean interrupted(): Tests if the current thread has been interrupted.

Runnable interface:

The runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface contain only one method named run().

public void run(): It is used to perform action for a thread.

Starting a thread:

Start() method of thread class is used to start a newly created thread.

It performs following tasks:

• A new thread starts(with new callstack).

• The thread moves from new state to the runnable state.

• When the thread receive a chance to execute, its target run() method will run.

1) Java thread example by extending thread class

class Multi extends Thread

public void run()

System.out.println("thread is running...");

}
public static void main(String args[])

Multi t1=new Multi();

t1.start();

Output: thread is running...

2) Java thread example by implementing runnable interface

class Multi3 implements Runnable

public void run()

System.out.println("thread is running...");

public static void main(String args[])

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);

t1.start();

Output: thread is running...


If we are not extending the thread class, our class object would not be treated as a thread
object, we need to explicitly create thread class object. We are passing the object of our class
that implements runnable, so that our class run() method may execute.

4.1.3 Synchronizing threads, Inter-thread communication


Interthread Communication

The process of execution of exchanging of the data / information between multiple threads is
known as Interthread communication or if an output of first thread giving as an input to second
thread the output of second thread giving as an input to third thread then the communication
between first second and third thread known as Interthread communication.

In order to develop Interthread communication application we use some of the methods of


java.lang.Object class and these methods are known as Interthread communication methods.

Interthread communication methods

public final void wait(long msec)

public final void wait()

public final void notify()

public final void notifyAll()

public final void wait(long msec)

public final void wait (long msec) is used for making the thread to wait by specifying the waiting
time in terms of milliseconds. Once the waiting time is completed, automatically the thread will
be interred into ready state from waiting state. This methods is not recommended to used to
make next thread to wait on the basis of time because java programmer may not be able to
decide or determine the CPU burst time of current thread and CPU burst time is decided by OS
but not by the programmer.

public final void wait()


public final void wait() is used for making the thread to wait without specifying any waiting time
this method is recommended to use to make the next thread to wait until current thread
complete its execution.

public final void notify()

public final void notify() is used for transferring one thread at a time from waiting state to ready
state.

public final void notifyAll()

public final void notifyAll() is used for transferring all the threads at a time from waiting state to
ready state.

Note: public final void wait (long msec) and public final void wait() throws a predefined
Exception called java.lang.InterruptedException.

Thread Synchronization

Whenever multiple threads are trying to use the same resource then there may be chance of
getting wrong output, to overcome this problem thread synchronization can be used.

Definition: Allowing only one thread at a time to utilized the same resources out of multiple
threads is known as thread synchronization or thread safe.

In java language thread synchronization are two different types:

• Synchronized block
• Synchronized method.

Synchronized block

Whenever, we want to execute one or more statement by a single thread at a time th en, those
statement should be placed in a synchronized block.

Class Class_Name implement Runnable or extends thread

{
public void run()

synchronized(this)

..............

Synchronized method

Whenever, we want to allow only one thread at a time among multiple thread for execution to a
method, then that should be declared as synchronized method.

class Class_Name implement Runnable or extends Thread

public void run()

synchronized void fun()

{..............}

public void run()

fun();

....

}
4.1.4 Daemon threads
Daemon thread in java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

We can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java

• It provides services to user threads for background supporting tasks. It has no role in life than
to serve user threads.

• Its life depends on user threads.

• It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?

The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why
JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class

public void setDaemon(boolean status) - It is used to mark the current thread as daemon
thread or user thread.

public boolean isDaemon() - It is used to check that current is daemon.

Simple example of Daemon thread in java

File: MyThread.java

public class TestDaemonThread1 extends Thread

{
public void run()

if(Thread.currentThread().isDaemon())

{ //checking for daemon thread

System.out.println("daemon thread work");

else

System.out.println("user thread work");

public static void main(String[] args)

TestDaemonThread1 t1=new TestDaemonThread1();//creating thread

TestDaemonThread1 t2=new TestDaemonThread1();

TestDaemonThread1 t3=new TestDaemonThread1();

t1.setDaemon(true); //now t1 is daemon thread

t1.start(); //starting threads

t2.start();

t3.start();

}
Output

daemon thread work

user thread work

user thread work

4.1.5 Thread groups


Java provides a convenient way to group multiple threads in a single object. In that way, we can
suspend, resume or interrupt group of threads by a single method call.

Java thread group is implemented by java.lang.ThreadGroup class.

A ThreadGroup represents a set of threads. A thread group can also include the other thread
group. The thread group creates a tree in which every thread group except the initial thread
group has a parent.

A thread is allowed to access information about its own thread group, but it cannot access the
information about its thread group's parent thread group or any other thread groups.

Constructors of ThreadGroup class

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

ThreadGroup(ThreadGroup parent, String name) - It creates a thread group with given parent
group and name.

Methods of ThreadGroup class

checkAccess() - This method determines if the currently running thread has permission to
modify the thread group.

activeCount() - This method returns an estimate of the number of active threads in the thread
group and its subgroups.

activeGroupCount() - This method returns an estimate of the number of active groups in the
thread group and its subgroups.

destroy() - This method destroys the thread group and all of its subgroups.
enumerate(Thread[] list) - This method copies into the specified array every active thread in the
thread group and its subgroups.

getMaxPriority() - This method returns the maximum priority of the thread group.

getName() - This method returns the name of the thread group.

getParent() - This method returns the parent of the thread group.

interrupt() - This method interrupts all threads in the thread group.

isDaemon() - This method tests if the thread group is a daemon thread group.

setDaemon(boolean daemon) - This method changes the daemon status of the thread group.

isDestroyed() - This method tests if this thread group has been destroyed.

list() - This method prints information about the thread group to the standard output.

parentOf(ThreadGroup g) - This method tests if the thread group is either the thread group
argument or one of its ancestor thread groups.

suspend() - This method is used to suspend all threads in the thread group.

resume() - This method is used to resume all threads in the thread group which was suspended
using suspend() method.

setMaxPriority(int pri) - This method sets the maximum priority of the group.

stop() - This method is used to stop all threads in the thread group.

toString() - This method returns a string representation of the Thread group.

Example:

ThreadGroupDemo.java

public class ThreadGroupDemo implements Runnable

public void run()


{

System.out.println(Thread.currentThread().getName());

public static void main(String[] args)

ThreadGroupDemo runnable = new ThreadGroupDemo();

ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

Thread t1 = new Thread(tg1, runnable,"one");

t1.start();

Thread t2 = new Thread(tg1, runnable,"two");

t2.start();

Thread t3 = new Thread(tg1, runnable,"three");

t3.start();

System.out.println("Thread Group Name: "+tg1.getName());

tg1.list();

Output:

one

two

three

Thread Group Name: Parent ThreadGroup


java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]

Thread[one,5,Parent ThreadGroup]

Thread[two,5,Parent ThreadGroup]

Thread[three,5,Parent ThreadGroup]

4.2 Generic Programming


Templates are a feature of the C++programming language that allows the functions and classes
to operate with generic types. Generic programming as an approach where generic types are
used as parameters in algorithms so that they work for a variety of suitable data types and data
structures.

There are two kinds of templates:

1. Function templates.

2. Class templates.

4.2.1 Generic classes


A generic class declaration looks a non-generic class declaration, except that the class name is
followed by a type parameter.

As with generic methods, the type parameter section of a generic class can have one or more
type parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.

Example:

Live Demo

public class Box<T>

private T t;

public void add(T t)


{

this.t = t;

public T get()

return t;

public static void main(String[] args)

Box<Integer> integerBox = new Box<Integer>();

Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));

stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());

System.out.printf("String Value :%s\n", stringBox.get());

Output:

Integer Value : 10

String Value : Hello World


4.2.2 Generic methods
A single generic method declaration that can be called with arguments of different types. Based
on the types of the arguments passed to the generic method, the compiler handles each method
call appropriately.

Following are the rules to define Generic Methods:

• All generic method declarations have a type parameter section delimited by angle brackets (<
and >) that precedes the method's return type ( < E > in the next example).

• Each type parameter section contains one or more type parameters separated by commas. A
type parameter, also known as a type variable, is an identifier that specifies a generic type name.

• The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.

• A generic method's body is declared like that of any other method. Note that type parameters
can represent only reference types, not primitive types (like int, double and char).

Example

Following example illustrates how we can print an array of different type using a single Generic
method −

Live Demo

public class GenericMethodTest

// generic method printArray

public static < E > void printArray( E[] inputArray )

// Display array elements

for(E element : inputArray)


{

System.out.printf("%s ", element);

System.out.println();

public static void main(String args[])

// Create arrays of Integer, Double and Character

Integer[] intArray = { 1, 2, 3, 4, 5 };

Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };

Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");

printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");

printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");

printArray(charArray); // pass a Character array

Output

Array integerArray contains:

12345
Array doubleArray contains:

1.1 2.2 3.3 4.4

Array characterArray contains:

HELLO

4.3 Bounded Types


There may be times when we want to restrict the types that can be used as type arguments in a
parameterized type. For example, a method that operates on numbers might only want to
accept instances of number or its subclasses.

This is what bounded type parameters are for,

• Sometimes we don’t want whole class to be parameterized, in that case we can create java
generics method. Since constructor is a special kind of method, we can use generics type in
constructors too.

• Suppose we want to restrict the type of objects that can be used in the parameterized type.
For example in a method that compares two objects and we want to make sure that the
accepted objects are Comparables.

• The invocation of these methods is similar to unbounded method except that if we will try to
use any class that is not Comparable, it will throw compile time error.

Syntax:

<T extends superClassName>

Example:
public class MaximumTest

// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z)

{
T max = x; // assume x is initially the largest

if(y.compareTo(max) > 0)

max = y; // y is the largest so far

if(z.compareTo(max) > 0)

max = z; // z is the largest now

return max; // returns the largest object

public static void main(String args[])

System.out.printf("Max of %d, %d and %d is %d\n\n",

3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8,
7.7 ));

System.out.printf("Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum("pear",


"apple", "orange"));

Output
Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

4.3.1 Restrictions and Limitations


• In java, generic types are compile-time entities in C++, instantiations of a class template are
compiled separately as source code and tailored code is produced for each one.

• Primitive type parameters (Pair <int>) not allowed in C++, both classes and primitive types
allowed.

• Objects in JVM have non-generic classes:

Pair<String> strPair = new Pair<String> . .;

Pair<Number> numPair = new Pair<Number> . .;

b = strPair.getClass () == numPair.getClass ();

assert b == true; // both of the raw class Pair

but byte-code has reflective info about generics

• Instantiations of generic parameter T are not allowed.

new T () // ERROR: whatever T to produce?

new T [10]

• Arrays of parameterized types are not allowed.

new Pair <String> [10]; // ERROR

since type erasure removes type information needed for checks of array assignments

• Static fields and static methods with type parameters are not allowed

class Singleton <T> {

private static T singleOne; // ERROR


since after type erasure, one class and one shared static field for all instantiations and their
objects.
UNIT V EVENT DRIVEN PROGRAMMING
Graphics programming - Frame – Components - working with 2D shapes - Using color, fonts, and
images - Basics of event handling - event handlers - adapter classes - actions -mouse events
-AWT event hierarchy - Introduction to Swing – layout management -Swing Components – Text
Fields , Text Areas – Buttons- Check Boxes – Radio Buttons – Lists- choices- Scroll bars – Windows
–Menus – Dialog Boxes.
5.1 Graphics programming
Initially, the concept of templates was not included in some languages, such as Java and C#1.0.
Java's adoption of generics mimics the behaviour of templates, but is technically different.

C# added generics (parameterized types) in .NET 2.0. The generics in Ada predate C++ templates.

Some of the advanced template features utilized by libraries such as Boost and STL Soft and
implementations of the STL itself, for template meta-programming are not available with
generics.

Type parameter

The generic type declaration specifies the class of types for which an instance of the generic will
work:

• type T is private; - Any type with assignment (Non-limited).

• type T is limited private; - Any type (No required operations).

• type T is range <>; - Any integer type (Arithmetic operations).

• type T is (<>); - Any discrete type (Enumeration or integer).

• type T is digits <>; - Any floating-point type.

• type T is delta <>; - Any fixed-point type.

• Within the generic, the operations that apply to any type of the class can be used.

• The instantiation must use a specific type of the class.

A generic function

generic

type T is range <>; - parameter of some integer type

type Arr is array (Integer range <>) of T; - parameter is array of those function

Sum_Array (A : Arr) return T; - Body identical to non-generic version function


Sum_array (A : Arr) return T is Result : T := 0; - some integer type, so literal 0 is legal

begin

for J in A’range loop - some array type, so attribute is available

Result := Result + A (J); - some integer type, so “+” available.

end loop;

return Result;

end;

• Only available operations are assignment and equality.

generic

type T is private;

procedure Swap (X, Y : in out T);

procedure Swap (X, Y : in out T) is

Temp : constant T := X;

begin

X := Y;

Y := Temp;

end Swap;

Subprogram parameters

A generic sorting routine should apply to any array whose components are comparable, i.e. for
which an ordering predicate exists. This class includes more than the numeric types:

generic

type T is private; - parameter


with function “<“ (X, Y : T) return Boolean; - parameter

type Arr is array (Integer range <>) of T; - parameter

procedure Sort (A : in out Arr);

Supplying subprogram parameters: The actual name must have a matching signature, not
necessarily the same name:

procedure Sort_Up is new Sort (Integer, “<“, …);

procedure Sort_Down is new Sort (Integer, “>”, … );

type Employee is record .. end record;

function Senior (E1, E2 : Employee) return Boolean;

function Rank is new Sort (Employee, Senior, …);

Value parameters: Useful to parametrize containers by size:

generic

type Elem is private; -- type parameter

Size : Positive; -- value parameter

package Queues is

type Queue is private;

procedure Enqueue (X : Elem; On : in out Queue);

procedure Dequeue (X : out Elem; From : in out Queue);

function Full (Q : Queue) return Boolean;

function Empty (Q : Queue) return Boolean;

private

type Contents is array (Natural range <>) of Elem;


type Queue is record

Front, Back: Natural;

C : Contents (0 .. Size);

end record;

end Queues

5.1.1 Frame – Components


Graphical components must be placed inside a container. A container corresponds to a
rectangular area of the monitor screen and the components it contains correspond to smaller
areas within it.

In java, a frame is a window that has nice borders, various buttons along the top border, and
other features. What we usually call a "window" java calls a "frame". A frame is a container
object, so GUI components can be placed in it.

All software objects, a frame object is actually a section of main memory that holds information
and methods. The operating system and the graphics board, java paints a picture on the
computer monitor that represents the frame. People often speak as if the frame were the actual
picture on the monitor. In fact, what we see on the monitor is just a graphical representation of
the frame.

GUI application programs are usually organized around one or more frames.

Method Description

public void add(Component c) - Inserts a component on this component.

public void setSize(int width,int height) - Sets the size (width and height) of the component.

public void setLayout(LayoutManager m) - Defines the layout manager for the component.

public void setVisible(boolean status) - Changes the visibility of the component, by default false.
5.2 Working with 2D shapes
The AWT's Graphics class represents a graphics context and has a relatively poor set of graphics
primitives. It was only designed to provide those features found on most platforms. For example,
MS Windows programmers were able to able to set pen and fill styles, and set transformations to
map from user-space to the display. In constrast, Java programmers were stuck with nothing
more sophisticated than single-pixel lines and solid fills.

The Java 2D API set out to rectify this. Developed by Sun and Adobe, it is based around a new
graphics context class, Graphics2D, which provides a number of sophisticated features. The API is
not contained in a single package.

Some of its classes are in the original java . awt package, and the rest are in sub-packages:

• java . awt contains the new Graphics2D class; the BasicStroke class for creating pen styles; the
TexturePaint and GradientPaint classes for creating fill styles; and updated Color and Font
classes.

• java . awt . color provides classes for more sophisticated colour control.

• java . awt . font includes support for glyphs (rendered text strings); text with multiple fonts;
and a greater range of font styles (such as superscript).

• java . awt . geom contains the classes concerned with geometric transformations.

• java . awt . image includes support for a range of image-processing tasks.

Note that with the beta-2 release of Java 1.2, Java 2D could not be used with the Swing
components. This was because Swing components received a SwingGraphics object in their paint
( ) methods which is a subclass of the original Graphics class.

5.2.1 Using color, fonts, and images


Colour

A colour space describes a range of possible colours. The color class uses a Red-Green-Blue
(RGB) colour space as standard, whereby any colour can be described by its red, green and blue
components. Although this is a convenient way of describing colour, there are other colour
spaces designed to help you find colours with similar attributes, such as hue or saturation. A
colour space such as Hue-Saturation-Brightness (HSB) might be more appropriate in this case. In
addition, a number of devices use different colour spaces. Most colour printers, for example, use
the Cyan-Magenta-Yellow-Black (CMYK) colour space.

All of the colour spaces mentioned above are device-dependent. Different devices have different
colour capabilities, in particular the number of colours they can reproduce. The java . awt.col or
package provides a number of standard colour spaces and methods to convert colours between
them. This is done through a colour profile that maps a colour space to or from the device-
independent Commission Internationale de I'Eclairage X-Y-Z (CIEXYZ) colour space. If you want to
convert colours between two device-dependent colour spaces, you must do so using the CIEXYZ
colour space as an intermediate. The java.awt.image. ColorConvertOp class provides methods to
convert the colours of whole images.

Java 2D also lets we define the alpha component of colours, which represents the transparency
of the colour. If this sounds like a lot of hassle for just selecting colour. Although these features
provide we with much more control over colours for different devices, we can still carry on using
the Color class as before.

Fonts:

Text fonts in java are represented by instances of the java.awt.Font class. A Font object is
constructed from a name, style identifier, and a point size. We can create a Font object at any
time, but it's meaningful only when applied to a particular component on a given display device.
Here are a couple of fonts:

Font saallcont = new Font(“Moonspaced”, Font.PLAIN, 10);

Font bigFont = new Font(“Serif”, Font, BOLD, 18);

Font names come in three varieties: family names, face names (also called font names), and
logical names. Family and font names are closely related. For example, Garamond Italic is a font
name for a font whose family name is Garamond.

A logical name is a generic name for the font family. The following logical font names should be
available on all platforms:

• Serif (generic name for TinesRoman)


• SansSerif (generic name for Helvetica)

• Monospaced (generic name for Courier)

• Dialog

• Dialoglnput

The logical font name is mapped to an actual font on the local platform. Java's fonts. properties
files map the font names to the available fonts, covering as much of the Unicode character set as
possible. If we request a font that doesn't exist, we get the default font.

One of the big wins in the 2D API is that it can use most of the fonts you have installed on your
computer. The following program prints out a full list of the fonts that are available to the 2D API:

//file: ShowFonts.java

import java.awt.*;

public class ShowFonts

Public static void main(String] args)

Font[] fonts;

fonts *

GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts( );

for(int i 0; i < fonts.length; i++)

System.out.print(fonts[i].getFontName( ) + “ : ");

System.out.print(fonts[i].getFamily( ) + " : ");

System.out.print(fonts[i].getName( ));
System.out.println(); }

Note, however, that the fonts installed on our system may not match the fonts installed on
someone else's system. For true portability, we can use one of the logical names or go with the
defaults. We can also allow our users to configure the application by choosing fonts themselves.

The static method Font.getFont ()looks up a font name in the system properties list . getFont()
takes a String font property name, retrieves the font name from the Properties table, and returns
the Font object that corresponds to that font.

The Font class defines three static style identifiers: PLAIN, BOLD, and ITALIC. You can use these
values on all fonts. The point size determines the size of the font on a dis-play. If a given point
size isn't available, Font substitutes a default size.

We can retrieve information about an existing Font with a number of routines. The getName(),
getSize(), and getStyle() methods retrieve the logical name, point size, and style, respectively.
You can use the getFamily() method to find out the family name while getFontName() returns
the face name of the font.

Finally, to actually use a Font object, we can simply specify it as an argument to the setFont()
method of a Component or Graphics2D object. Subsequent text-drawing commanded such as
drawingString() for that component or in that graphics context use the specified font.

Images

Images Java 2D provides the ability to apply filters to images, to transform them, and to adjust
their colour look-up tables. These features are based around the new subclass of Image, called
BufferedImage. This also provides methods to apply transformations, create sub-images and
create a graphics context to draw directly onto the image.

5.3 Basics of event handling - Event handlers


Event Handling

The Abstract Window Toolkit (AWT) uses event driven programming to do processing of user
actions, one that underlies all modern window systems programming. Within the AWT, all user
actions belong to an abstract set of things called events. An event describes, in sufficient detail, a
particular user action. Rather than the program actively collecting user-generated events, the
Java run time notifies the program when an interesting event occurs. Programs that handle user
interaction in this fashion are said to be event driven.

Event Handling provides four types of classes; they are:

1. Event Adapters
2. Event classes
3. Event Sources
4. Event Listeners

1. Event Adapters

In a program, when a listener has many abstract methods to override, it becomes complex for
the programmer to override all of them.

For example, for closing a frame, we must override seven abstract methods of WindowListener,
but we need only one method of them.

For reducing complexity, Java provides a class known as "adapters" or adapter class. Adapters
are abstract classes, that are already being overriden.

2. Event classes

Every event source generates an event and is named by a Java class. An event is generated when
something changes within a graphical user interface.

For example the event generated by a:

• Button is known as an ActionEvent

• Checkbox is known as an ItemEvent

All the events are listed in the java.awt.event package.

3. Event Sources

Event Sources are responsible for generating events and are called components.

The source for an event can be a button, TextField or a Frame etcetera.


4. Event Listeners

Events are handled by a special group of interfaces known as "listeners".

The following is required to perform event handling:

1. Implement the Listener interface and override its methods

2. Register the component with the listener

For adding various components we use publics methods, for example:

Button

void addActionListener( ActionListener a)

List

void addActionListener(ActionListener a)

void addItemListener(ItemListener a)

Choice

void addItemListener(ItemListener x)

MenuItem

void addActionListener(ActionListener x)

TextField

void addActiontListener(ActionListener x)

void addTextListener(TextListener x)

TextArea

void addTextListener(TextListener x)

Checkbox

void addItemListener(ItemListener x)
Example:

import java.awt.event.*;

import java.awt.*;

class EventActEx1 extends Frame implements ActionListener

TextField txtfld;

EventActEx1()

txtfld= new TextField();

txtfld.setBounds(65,60,190,20);

Button bt=new Button("Click me");

bt.setBounds(100,120,80,30);

bt.addActionListener(this);

add(bt);add(txtfld);

setSize(350,350);

setLayout(null);

setVisible(true);

public void actionPerformed(ActionEvent e)

txtfld.setText("welcome 2 c-sharpcorner.com");

}
public static void main(String args[])

new EventActEx1();

Out put:

When we
click on
"click
me"
button,
an event
is
generated that shows the "welcome 2 c-sharpcorner.com" message in the textfield area, hence
we see an event change in this program.

5.4
Adapter
classes -
Actions
-Mouse
events
Adapter
class

• It is a pattern which provides default implementation of interface or abstract class.

• Adapter class provides the default implementation of all the methods in an event listener
interface.
• Usually adapter classes ease the programmers by providing the implementations of the
listener interfaces instead of having to implement them. This is where the event adapter class
comes into picture.

• These classes are useful when we want to process only few of the events that are handled by a
particular event listener interface.

• Using adapters, it helps to reduce the clutter in our code.

Advantages of the Adapter class:

• It increases the transparency of classes.

• It makes a class highly reusable.

• It provides a pluggable kit for developing application.

• It provides a way to include related patterns in a class.

MouseListener Methods

public void mouseClicked(MouseEvent e) - Contains the handler for the event when the mouse is
clicked (i.e., pressed and released).

public void mouseEntered(MouseEvent e) - Contains the code for handling the case wherein the
mouse enters a component.

public void mouseExited(MouseEvent e) - Contains the code for handling the case wherein the
mouse exits a component.

public void mousePressed(MouseEvent e) - Invoked when the mouse button is pressed on a


component.

public void mouseReleased(MouseEvent e) - Invoked when the mouse button is released on a


component.

MouseListener Methods public void mouseDragged(MouseEvent e) - Contains the code for


handling the case wherein the mouse button is pressed on a component and dragged. Called
several times as the mouse is dragged.
public void mouseMoved(MouseEvent e) - Contains the code for handling the case wherein the
mouse cursor is moved onto a component, without the mouse button being pressed. Called
multiple times as the mouse is moved.

5.4.1 AWT event hierarchy


The Java AWT (Abstract Windowing Toolkit) contains the fundamental classes used for
constructing GUIs. The abstract component class is the base class for the AWT. Many AWT
classes are derived from it. These are the old AWT components that are no longer in use.

Some of the AWT classes derived from component are Button, Canvas, and Container.

The diagram shows how the classes of the AWT and swing fit together.
The JComponent class is derived from Container and is one of the base classes of Swing. The
JFrame class is derived from the AWT Frame class. It is usually the main container for a GUI
application.

The JApplet class is derived from the AWT Applet class and is used for modern applets.

5.5 Introduction to Swing–Layout management


Swing has plenty of layout managers available both built-in and third-party. However, most of
the managers are not suitable in modern UI creation.

There are three layout managers that can do the job properly:

1. MigLayout

2. GroupLayout

3. FormLayout

MigLayout, GroupLayout, and FormLayout are powerful, flexible layout managers that can cope
with most layout requirements. GroupLayout manager to get design the user interface.

The following layout managers are obsolete:

1. FlowLayout
2. GridLayout
3. CardLayout
4. BoxLayout
5. GridBagLayout

FlowLayout

The FlowLayout arranges the components in a directional flow, either from left to right or from
right to left. Normally all components are set to one row, according to the order of different
components. If all components can not be fit into one row, it will start a new row and fit the rest
in.

To construct a FlowLayout, three options could be chosen:

FlowLayout(): construct a new FlowLayout object with center alignment and horizontal and
vertical gap to be default size of 5 pixels.
FlowLayout(int align): construct similar object with different settings on alignment

FlowLayout(int align, int hgap, int vgap): construct similar object with different settings on
alignment and gaps between components.

For the constructor with the alignment settings, the possible values could be: LEFT, RIGHT,
CENTER, LEADING and TRAILING.

BorderLayout

A BorderLayout lays out a container, arranging its components to fit into five regions: NORTH,
SOUTH, EAST, WEST and CENTER. For each region, it may contain no more than one component.
When adding different components, you need to specify the orientation of it to be the one of
the five regions.

For BorderLayout, it can be constructed like below:

BorderLayout(): construct a border layout with no gaps between components.

BorderLayout(int hgap, int vgap): construct a border layout with specified gaps between
components.

CardLayout

For CardLayout, it treats the components as a stack and every time, what we can see is only one
component. That’s why it’s called CardLayout.

BoxLayout

BoxLayout manager is a simple layout manager that organizes components in a column or a row.
It can create quite sophisticated layouts with nesting. However, this raises the complexity of the
layout creation and uses additional resources, notably many other JPanel components.
BoxLayout is only able to create fixed spaces. Therefore, its layouts are not portable.

BoxLayout has the following constructor:

BoxLayout(Container target, int axis)


The constructor creates a layout manager that will lay out components along the given axis.
Unlike other layout managers, BoxLayout takes a container instance as the first parameter in the
constructor. The second parameter determines the orientation of the manager. To create a
horizontal box, we can use the LINE_AXIS constant. To create a vertical box, we can use the
PAGE_AXIS constant.

The box layout manager is often used with the Box class. This class creates several invisible
components, which affect the final layout.

1. glue

2. strut

3. rigid area

GridLayout

The GridLayout manager is used to lay out the components in a rectangle grid, which has been
divided into equal-sized rectangles and one component is placed in each rectangle.

It can constructed with following methods:

GridLayout(): construct a grid layout with one column per component in a single row.

GridLayout(int row, int col): construct a grid layout with specified numbers of rows and columns.

GridLayout(int row, int col, int hgap, int vgap): construct a grid layout with specified rows,
columns and gaps between components.

GridBagLayout

GridBagLayout is a more flexible layout manager, which allows the components to be vertical,
horizontal, without specifying the components to be the same size. Each GridLayout object holds
a dynamic rectangular grid of cells. Each component is associated with an instance of
GridBagConstraints. The GridBagConstraints decides where the component to be displayed and
how the component should be positioned.
5.6 Swing Components - Text Fields , Text Areas – Buttons- Check Boxes – Radio Buttons – Lists-
choices- Scroll bars – Windows –Menus – Dialog Boxes.
JTextField

JTextField is used for taking input of single line of text. It is most widely used text component. It
has three constructors,

JTextField(int cols)

JTextField(String str, int cols)

JTextField(String str)

cols represent the number of columns in text field.

JTextArea

1. A text area is a text control that lets the user enter multiple lines of text.

2. Text areas are implemented in Swing by the JTextArea class.

3. The constructor methods of this class are:

• JTextArea( int rows, int cols) — creates a text area with rows and columns.

• ifextArea(String str, int rows, int cols) — creates a text area with the specified text and rows
and cols.

JButton

JButton class provides functionality of a button. JButton class has three constuctors,

JButton(Icon ic)

JButton(String str)

JButton(String str, Icon ic)

It allows a button to be created using icon, a string or both. JButton supports ActionEvent. When
a button is pressed an ActionEvent is generated.

Check box:
The JCheckBox class provides support for check box buttons. You can also put check boxes in
menus, using the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem
inherit from AbstractButton, Swing check boxes have all the usual button characteristics, as
discussed earlier in this section. For example, you can specify images to be used in check boxes.

Check boxes are similar to radio buttons but their selection model is different, by convention.
Any number of check boxes in a group — none, some, or all — can be selected. A group of radio
buttons, on the other hand, can have only one button selected.

Here is a picture of an application that uses four check boxes to customize a cartoon:

Radio buttons

Radio buttons are groups of


buttons in which, by
convention, only one button at
a time can be selected. The
Swing release supports radio
buttons with the JRadioButton and ButtonGroup classes. To put a radio button in a menu, use
the JRadioButtonMenuItem class. Other ways of displaying one-of-many choices are combo
boxes and lists. Radio buttons look similar to check boxes, but, by convention, check boxes place
no limits on how many items can be selected at a time.

Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual
button characteristics, as discussed earlier in this section. For example, you can specify the
image displayed in a radio button.

Here is a picture of an application that uses five radio buttons to let you choose which kind of
pet is displayed:

Lists

As its name suggests, a


list control presents the
user with a list of items
- text strings - from which one can select. In windowing environments, space is often at a
premium, so it is a good idea to place items in lists, because using scrollbars, we can hide long
lists in short list components. The user can select the item in the list he wants, double-click it,
and initiate some action.

Lists can also support multiple selections at the same time, using the Shift and Ctrl keys.
However, if we support multiple selections, we have to think about how to use the mouse in a
list control. Clicking an item selects it, so the user can't just make multiple selections and then
double-click one to initiate some action because when one item is double-clicked, all the others
are deselected. To solve this problem, Sun suggests we to use some other event, such as a
button click, to initiate an action when dealing with multiple selections.

Choices

Choice controls also present the user with a list of items to select from, but there's a difference
choice controls are even more compact than lists. Choice controls look much like text fields
although you can't edit the text in them with a small button on the right that has a downward-
pointing arrow. When the user clicks the arrow, a list opens displaying all the available choices,
and the user can select from one of them.

After the selection is made, the choice control closes the list and displays the current selection. If
the user opens the list again, the current selection is highlighted. Note that choice controls are
only designed to display one choice at a time, which means you can't select more than one item
in the list at a time. Using Shift+click and Ctrl+click is the same as just clicking an item. Like the
other components in this chapter, choice controls support scrolling. If the list of items is long,
scrollbars will appear on the side of the list automatically.

JWindow:

A JWindow is a top-level container. It can be displayed anywhere on the desktop. JWindow does
not have a title bar, and window-management buttons. The user cannot move or resize the
window. It has no border. The default layout for JWindow is BorderLayout.

Menus:
The windowing toolkit supports the creation of menu-driven GUIs. These GUIs have a menu bar
situated at the top of a window with a list of menu names appearing on this bar. Selecting one of
these names causes a menu to drop down. This menu consists of one or more menu items that
are text-based commands for handling casks. Some of these menu items can be checked to
represent state. For example, a ruler menu item might be checked to indicate that a ruler should
be displayed in a word processor program. A special keystroke combination can be assigned to a
menu item to speed up access. This keystroke combination is known as a menu shortcut.

The following classes (all located in the tava.awt package) work together to implement menus:

• MenuBar

• Menu

• Menultem

• CheckboxMenultem

• MenuShortcut

The MenuBar class creates objects that represent menu bars. Call the MenuBar() constructor to
create a menu bar.

Menus are added to a menu bar by calling MenuBar add method and removed by calling either
of its two overloaded remove methods. To obtain a specific menu, call getMenu. If you need to
know how many menus have been added, call getMenucount.

Menu bars typically display a special Help menu on their extreme right. Call unmeant/term to
designate the Help menu. To find out which menu is the Help menu, call getHelpiMenu.

MenuBar provides a shortcuts method that conveniently enumerates all menu shortcuts
assigned to menu items. Given a menu shortcut, you can obtain the associated menu item by
calling MenuBar's getShortouthenulten method. If we want to remove a shortcut, call
deleteShorteut.

A menu bar doesn't accomplish way much without menus. Menus are represented by objects
created from the menu class. Call the menu 0 constructor to create a menu without a label.
Scrollbars

Scrollbars are components that enable a part of a large display to be selected for viewing. They
an often used on text areas that contain more lines than a graphical user interface has space to
display. A user can move to a particular location by dragging a box (the knob) between two
wows. The user can also move the view region a short distance (such as a line) by clicking one of
the arrows. or a longer distance by clicking between an arrow and the knob.

Some Swing components have built-in scrollbar functionality, including scrolling panes and lists.
We can also create a scrollbar by itself.

Scrollbars are normally created by specifying the minimum and maximum values that can be set
using the component.

We can use the following constructor methods:

• JScrollBar(int)—A scrollbar with the specified orientation.

• JScrollBar(int ,int ,Int, Int, int)—A scrollbar with the specified orientation. starting value, scroll
box size, minimum value, and maximum value.

The orientation is indicated by either of two JScrollBar class constants: HORIZONTAL or


VERTICAL.

The initial value of the scrollbar should be equal to or between the minimum and maximum
values of the bar. The default value is the minimum.

The third argument is the overall amount of material that can appear at one time in the display
to which the scrollbar applies. If the scrollbar applies to a text area, for example. the third
argument to the constructor is the number of lines the area can show. The default value is 10.

The fourth and fifth arguments are the minimum and maximum values of the scrollbar. The
defaults are 0 and 100.

The following statement creates a vertical scrollbar with a minimum value of 10 , a maxi-mum
value of 50, and an initial value of 33.

JScrollBar bar = new JScrollBar(JScrollBar. HORIZONTAL, 33, 0, 10, 50);


Dialog Boxes

A dialog box to hold a set of related controls. Dialog boxes are primarily used to obtain user input
and are often child windows of a top-level window. Dialog boxes don't have menu bars, but in
other respects, they function like frame windows. Dialog boxes may be modal or modeless.
When a modal dialog box is active, all input is directed to it until it is closed. This means that we
cannot access other parts of our program until you have closed the dialog box. When a modeless
dialog box is active, input focus can be directed to another window in our program.

Thus, other parts of your program remain active and accessible. Dialog boxes are of type Dialog.
Two commonly used constructors are shown here:

Dialog(Frame parentWindow, boolean mode)

Dialog(Frame parentWindow, String Me, boolean mode)

Here, parentWatdow is the owner of the dialog box. If mode is true, the dialog box is modal.
Otherwise, it is modeless. The tide of the dialog box can be passed in tide Generally, you will
subclass Dialog, adding the functionality required by your application.

Following is a modified version of the preceding menu program that displays a modeless dialog
box when the New option is chosen. Notice that when the dialog box is closed, dispose( ) is
called. This method is defined by Window, and it frees all system resources associated with the
dialog box window.

You might also like