CS8392 Object Oriented Programming - MLM
CS8392 Object Oriented Programming - MLM
This book has been prepared as per Anna University syllabus, 2017 regulation.
CS8392 OBJECT ORIENTED PROGRAMMING
OBJECTIVES:
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.
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:
//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
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.
In object-oriented programming, message passing involves specifying the name of objects, the
name of the function and the information to be sent.
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.
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
Extensibility in an object oriented programming is easy. New functionality is easy to add without
affecting existing functionality.
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.
• 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.
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
Object Oriented
Java supports Inheritance, encapsulation and polymorphism, the three major object oriented
constructs that distinguish a language as Object-Oriented.
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
• 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
% 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. 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.
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.
System.out.println("Hello Java");
}
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.
<constructor declarations>
}
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().
int length;
int breadth;
int 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.
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.
• It cannot be virtual.
There are many forms in which a constructor can take its shape namely:
* Default Constructor
* Copy constructor
* Parameterized constructor
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:
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.
This operator could be used to refer to any member in the class explicitly.
char name[30];
int age1;
public:
void getdata(void);
void display(void);
}
s1.getdata();
s1.display();
}
1.6.1 Static members
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
Example Program:
#include<iostream.h>
#include<conio.h>
class count
{
public:
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.
Syntax:
//This is single line comment //
Example:
System.out.println(i);
Output:
10
Syntax:
Example:
int i=10;
System.out.println(i);
}
}
Output:
10
Syntax:
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
javac Calculator.java
javadoc Calculator.java
There are eight primitive data types supported by java. Primitive data types are predefined by
the language and named by a keyword.
Byte:
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.
Short:
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.
Int is generally used as a default data type for integral values unless there is a concern about
memory.
Default value = 0.
Long:
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.
Float data type is never used for precise values such as currency.
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.
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.
Char:
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.
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'.
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.
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
This is defined inside pupAge() method and its scope is limited to this method only.
int age = 0;
age = age + 7;
Output:
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
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Unary Operator
Operator Operation
Operator Operation
== Equal to
!= Not equal to
Conditional Operator
&& Conditional-AND
|| Conditional-OR
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.
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.
In Java programming language, there are three types of control flow statements. They are:
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)
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)
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
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();
Java jump statements are break, continue, and return. These statements transfer control to
another part of the program.
1. Break
2. Continue
3. Return
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.
class break1
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.
class continue1
{
for (int i=1; i<1=0; i++)
if (i%2 == 0)
continue;
System.out.println("\n" + i);
Output :
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.
class Return1
boolean t = true;
if(t)
Output :
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
Example:
int mark[];
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.
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.
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.
Syntax: array_name[index]=initial_value;
Example: mark[3]=4;
Array length
Syntax: array_name.length
Example: size=mark.length;
import java.io.*;
class Sample
int Num[];
Sample()
for(int i=0;i<Num.length;i++)
Num[i]=i+1;
}
void Print()
for(int i=0;i<Num.length;i++)
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
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};
void Print()
for(int i=0;i<Num.length;i++)
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
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.
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;
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.
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.
static void arraycopy (Object from, int It copies elements from the first array to the
fromIndex, Object to, int toIndex, int count) second array.
Multi dimensional arrays are represented using multiple-indexes. It is the collection of one
dimensional arrays.
Example
int [][]a;
(or)
int a[][];
(or)
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.
java.util.Arrays;
java.io.BufferedReader ;
java.util.Date;
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
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
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:
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.
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
md MyPackage
cd MyPackage
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
package MyPackage;
System.out.println(“Value:”+obj);
}
}
• Compile the java file and .class file is created and stored in the same directory(package).
Javac MyPackage\MyClass.java
For example:
import MyPackage.*;
class MyProg
MyObj.print(10);
MyObj.print(“Sunil kumar”);
}
}
Output:
Value is: 10
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:
/**
• <p>
• @see Blob .1
try
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.
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
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()
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()
cin>>rno;
cin>>m1>>m2;
};
class sports
protected:
int sm; // sm = Sports mark
public:
void getsm()
cin>>sm;
};
int tot,avg;
public:
void display()
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\tAverage : "<<avg;
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
Output:
90
80
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>
class person
char name[100],gender[10];
int age;
public:
void getdata()
cout<<"Name: ";
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
void display()
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
};
public:
void getdata()
person::getdata();
fflush(stdin);
gets(institute);
cout<<"Level: ";
cin>>level;
void display()
person::display();
cout<<"Level: "<<level<<endl;
}
};
char company[100];
float salary;
public:
void getdata()
person::getdata();
flush(stdin);
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
void display()
person::display();
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
Gender: Male
Level: Bachelor
Displaying data
Age: 21
Gender: Male
Level: Bachelor
Employee
Enter data
Age: 24
Gender: Female
Salary: $29000
Displaying data
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()
};
class B : public A
};
class C : public B
};
int main()
C c;
c.display();
return 0;
Output
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”;
};
Protected:
Int sub1,sub2;
Public:
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”;
};
{
Float total;
Public:
Void display();
};
void result::display()
Total=sub1+sub2+score;
display_rno();
display_mark();
put_score();
int main()
Result s r1;
r1. getno(123);
r1. get_mark(60,80)
r1.get_score(6);
r1.display();
• 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
• The class hierarchy refers the inheritance relationship between the classes. The root of the
class hierarchy is the class Object.
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
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.
• 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.
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>
class Box
protected:
double wi;
};
public:
};
double SmallBox::getSmallWidth(void)
return wi ;
wi = wid;
}
int main( )
SmallBox box;
box.setSmallWidth(5.0);
return 0;
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:
• 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.
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
**********
}
#include<iostream.h>
#include<conio.h>
class I
public: int x;
I()
x=20;
}; class II
public:
int k;
I y;
II()
{ k=30;
void show()
}; 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.
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;
Abstract class:
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:
private:
};
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>
// Base class
classShape
{ public:
virtualintgetArea() = 0;
voidsetWidth(intw)
width=w;
voidsetHeight(inth)
height= h;
protected:
intwidth;
intheight;
};
// Derived classes
{ public:
intgetArea()
return(width * height);
};
{ public:
intgetArea()
return(width * height)/2;
};
intmain(void)
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
Tri.setWidth(5);
Tri.setHeight(7);
return0;
When the above code is compiled and executed, it produces the following result:
45
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.
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
return WHEELS;
Van.java
Main.java
}
}
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.
return WHEELS;
Now, if we try to create another class by extending class ‘Car’, it will show one compile time error
message.
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.
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
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
void print();
{
int y=20;
System.out.println(“x = “+x);
System.out.println(“y = “+y);
class Sample
SubObj.print();
SubObj.print();
Output:
x = 10
y = 20
x = 10
y = 20
Class Interface
Supports only multilevel and hierarchical Supports all types of inheritance are multilevel,
inheritances but not multiple inheritance. hierarchical and multiple.
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.
Example
// Filename: Sports.java
// Filename: Football.java
// Filename: Hockey.java
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.
Method Signature:
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:
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,
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.
class Outer
class Inner
class Main
in.show();
}
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
Output:
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
void my_Method()
class MethodInner_Demo
inner.print();
}
outer.my_Method();
If you compile and execute the above program, you will get the following result −
Output:
Static nested classes are not technically an inner class. They are like a static member of outer
class.
Example:
class Outer
System.out.println("inside outerMethod");
{
public static void main(String[] args)
outerMethod();
Output:
inside outerMethod
Anonymous inner classes are declared without any name at all. They are created in two ways.
class Demo
void show()
class Flavor1Demo
void show()
super.show();
};
d.show();
Output
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.
class Flavor2Demo
};
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.
• 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.
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.
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.
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
1. By string literal
2. By new keyword
1) String Literal
2) By new keyword
String s=new String("Welcome"); //Creates two objects and one reference variable.
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(Locale l, String format, Object... args) - Returns formatted string with given
locale.
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.
String replace(char old, char new) - Replaces all occurrences of specified char value.
String trim() - Returns trimmed string omitting leading and trailing spaces.
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
Example
String n2=s.substring(5);
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
Example
Spaces in the beginning and endings can be removed by using the method trim().
Example
Newstr=Oldstr.trim();
Comparing strings
Example
str1.equals(str2); // if str1 and str2 are equal it returns true, otherwise false.
Getting a character
Example
1. ChartAt()
To extract a single character from a string, can refer directly to an individual character.
char ch;
ch = “abc”.charAt(1);
2. getChars()
More than one character can be extracted by using this method getchars()
General form
General form
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));
4. Replace()
Replace method replaces all occurrence of one character in the invoking string with another
character.
General form
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>
int main()
int x = -1;
// Some code
try
if (x < 0)
throw x;
catch (int x ) {
cout << "Exception Caught \n";
return 0;
Output:
Before try
Inside try
Exception Caught
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.
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:
…….
throw exception; //
Block of statements
which detects and
throws an exception
…….
Example:
#include <iostream>
int main()
try
{ // start
block\n”;
catch (int i)
{ // catch an error
Exception Types:
Synchronous Exception:
• Out of range
• Over flow
Asynchronous Exception:
• Keyboard interrupts.
• Division by zero.
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;
j=0;
try
if(j==0)
{
throw j;//throw an error
cout<<”RESULT IS”<<i/j;
catch(int a)
{ //catch an error
cout<<a<<”\n’;
cout<<”Ends here”;
return 0;
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>
int c;
if (b==0)
throw b;
else
c=a/b;
void main()
int x,y;
cout<<”Enter Two Numbers”;
cin>>x>>y;
try
catch(int k)
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;
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.
• 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
throw value2;
throw valueN;
}
catch (type1 name)IPLUS
any statements
any statements
any statements
Example:
#include<iostream>
try
throw “a”;
throw 1.1;
catch(char c)
catch(int i)
catch(float f)
}}
void main()
{
cout<<”Main Program”<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
Syntax:
try
….
throw a;
catch (char c)
Example:
#include <iostream.h>
class sam
{
int exno1;
public:
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”;
cout<<”ie”<<ie;
throw; //rethrowing
cout <<”ce”<<ce;
throw; //rethrowing
}
void main ()
try
ergen();
throw 10;
catch (int)
catch(char)
cout<<”caught char”;
{
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.
Unexpected Function
If the function throws an exception which is not permitted, then a function unexpected () is
called, which in turn calls abort.
Syntax:
set_unexcepted(my unexcepted);
Example:
#include <iostream.h>
void myunexpected ()
void myfunction
() throw (int)
set_unexpected (myunexpected);
try
myfunction();
catch (int)
catch (...)
{
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)
))
Otherwise
{
Follow the natural sequence of the destructor Algorithm
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.
// ArithmeticException
class ArithmeticException_Demo
Try
int a = 30, b = 0;
catch (ArithmeticException e)
Output:
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.
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
try
catch (ArrayIndexOutOfBoundsException e)
Output:
ClassNotFoundException:
This Exception is raised when we try to access a class whose definition is not found.
// concept of ClassNotFoundException
class Bishal
class Geeks
class MyClass
Object o = class.forName(args[0]).newInstance();
Output:
ClassNotFoundException
FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
try
}
catch (FileNotFoundException e)
Output:
import java.io.*;
class Geeks
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
System.out.print((char)i);
}
f.close();
Output:
// InterruptedException
class Geeks
t.sleep(10000);
Output:
// NoSuchMethodException
class Geeks {
public Geeks()
Class i;
try {
i = Class.forName("java.lang.String");
try {
catch (SecurityException e)
e.printStackTrace();
catch (NoSuchMethodException e)
e.printStackTrace();
catch (ClassNotFoundException e)
e.printStackTrace();
}
}
new Geeks();
Output:
NullPointerException: This exception is raised when referring to the members of a null object.
Null represents nothing
class NullPointer_Demo {
try
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.
// NumberFormatException
class NumberFormat_Demo
try
System.out.println(num);
catch (NumberFormatException e)
Output:
// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
try
System.out.println(c);
catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
Output:
StringIndexOutOfBoundsException
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.
public MyException(String s)
super(s);
// Driver Program
try
System.out.println("Caught");
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.
// Driver Program
try
System.out.println("Caught");
System.out.println(ex.getMessage());
Output:
Caught
Null
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.
Constructor: Creates a stack trace element representing the specified execution point.
StackTraceElement(String declaringClass,
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.
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.
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.
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.
2) public void write(byte[])throws IOException: It is used to write an array of byte to the current
output stream.
4) public void close()throws IOException: It is used to close the current output stream.
InputStream class: InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
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
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 Constructors
public int read (byte[ ] b, int off, int len) throws IOException; //synchronized
}
Hierarchy:Object→java.io.InputStream→FilterInputStream→BufferedInputStream
BufferedOutputStream
// Public Constructors
public void write (byte[ ] b, int off, int len) throws IOException; //synchronized
Hierarchy:Object→java.io.OutputStream→FilterOutputStream→BufferedOutputStream
A stream can be defined as a sequence of data. There are two kinds of Streams. They are,
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.*;
FileInputStream in = null;
try
in = new FileInputStream("input.txt");
int c;
out.write(c);
finally
if (in != null)
in.close();
if (out != null)
out.close();
Out put:
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.*;
FileReader in = null;
try
in = new FileReader("input.txt");
out.write(c);
finally
if (in != null)
in.close();
if (out != null)
out.close();
Out put:
$javac CopyFile.java
$java CopyFile
In java, there are three different ways for reading input from the user in the command line
environment(console).
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:
Disadvantage:
Program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
{
public static void main(String[] args) throws IOException
System.out.println(name);
Input:
Geek
Output:
Geek
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.
Drawback:
import java.util.Scanner;
class GetInputFromUser
String s = in.nextLine();
int a = in.nextInt();
float b = in.nextFloat();
Input:
GeeksforGeeks
12
3.4
Output:
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:
Disadvantages:
Example:
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.
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:
class WriteConsoleOutput
int y;
y = 'X';
System.out.write(y);
System.out.write('\n');
FileWriter
• 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, 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, 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 (char [] stir) throws IOException – Writes an array of characters.
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.
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
// Accept a string
String str = "File Handling in Java using "+" FileWriter and FileReader";
fw.write(str.charAt(i));
fw.close();
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
• 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(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:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
// variable declaration
int ch;
FileReader fr=null;
try
fr = new FileReader("text");
{
System.out.println("File not found");
while ((ch=fr.read())!=-1)
System.out.print((char)ch);
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).
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
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.
Step 2: At second step, we will instantiate a Thread object using the following constructor:
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.
Program
tobj.start();
1) It does not block the users because threads are independent and we can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
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.
Thread()
Thread(String name)
Thread(Runnable r)
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 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 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().
Starting a thread:
• When the thread receive a chance to execute, its target run() method will run.
System.out.println("thread is running...");
}
public static void main(String args[])
t1.start();
System.out.println("thread is running...");
t1.start();
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.
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 notify() is used for transferring one thread at a time from waiting state to ready
state.
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.
• 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.
{
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.
{..............}
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.
• It provides services to user threads for background supporting tasks. It has no role in life than
to serve user threads.
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.
public void setDaemon(boolean status) - It is used to mark the current thread as daemon
thread or user thread.
File: MyThread.java
{
public void run()
if(Thread.currentThread().isDaemon())
else
t2.start();
t3.start();
}
Output
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.
ThreadGroup(ThreadGroup parent, String name) - It creates a thread group with given parent
group and name.
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.
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.
Example:
ThreadGroupDemo.java
System.out.println(Thread.currentThread().getName());
t1.start();
t2.start();
t3.start();
tg1.list();
Output:
one
two
three
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
1. Function templates.
2. Class templates.
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
private T t;
this.t = t;
public T get()
return t;
integerBox.add(new Integer(10));
Output:
Integer Value : 10
• 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
System.out.println();
Integer[] intArray = { 1, 2, 3, 4, 5 };
Output
12345
Array doubleArray contains:
HELLO
• 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:
Example:
public class MaximumTest
{
T max = x; // assume x is initially the largest
if(y.compareTo(max) > 0)
if(z.compareTo(max) > 0)
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 ));
Output
Max of 3, 4 and 5 is 5
• Primitive type parameters (Pair <int>) not allowed in C++, both classes and primitive types
allowed.
new T [10]
since type erasure removes type information needed for checks of array assignments
• Static fields and static methods with type parameters are not allowed
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:
• Within the generic, the operations that apply to any type of the class can be used.
A generic function
generic
type Arr is array (Integer range <>) of T; - parameter is array of those function
begin
end loop;
return Result;
end;
generic
type T is private;
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
Supplying subprogram parameters: The actual name must have a matching signature, not
necessarily the same name:
generic
package Queues is
private
C : Contents (0 .. Size);
end record;
end Queues
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 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.
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.
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 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:
• 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.*;
Font[] fonts;
fonts *
GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts( );
System.out.print(fonts[i].getFontName( ) + “ : ");
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.
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.
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.
3. Event Sources
Event Sources are responsible for generating events and are called components.
Button
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.*;
TextField txtfld;
EventActEx1()
txtfld.setBounds(65,60,190,20);
bt.setBounds(100,120,80,30);
bt.addActionListener(this);
add(bt);add(txtfld);
setSize(350,350);
setLayout(null);
setVisible(true);
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
• 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.
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.
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.
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.
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.
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.
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.
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.
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)
JTextArea
1. A text area is a text control that lets the user enter multiple lines of text.
• 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)
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
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
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.
• JScrollBar(int ,int ,Int, Int, int)—A scrollbar with the specified orientation. starting value, scroll
box size, minimum value, and maximum value.
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.
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:
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.