Sie sind auf Seite 1von 107

The Java Programming Language

Java is defined as General Purpose, Object Oriented and Multithreaded Programming


Language

Features of JAVA
The Java programming language is a high-level language that can be characterized by all of the
following buzzwords:
Simple
Dynamic
Robust
Object oriented
Architecture neutral
Secure
Distributed
Portable
Multithreaded
High performance
Simple
Java syntax is similar to C/C++ syntax.
Java omits many rarely used, poorly understood, confusing feature of C++.
In java there is
- No Pointer and Pointer Arithmetic
- No Structure and no union
- No operator overloading
- No virtual base class
- No goto statement

No need to remove unreferenced objects because java has automatic garbage collection.
Object oriented
Java is made up of objects(i.e., there is no coding written outside class definition including main()
method.
Object oriented design is a technique for programming that focuses on the data(=object) and on
the interface to that data. The object oriented facilities of java are essentially those of C++ (such
as encapsulation, polymorphism, inheritance )
The major difference between C++ and java lies in multiple inheritance, which java replaced with
simpler concept of interface
Distributed/Network Savvy

Java was designed with networking in mind and comes with many classes to develop
sophisticated Internet communications.
Java has extensive library of routines for coping with TCP/IP protocol like HTTP and FTP. Java
applications can open and access objects across the Net via URLs with the same ease as when
accessing a local file system
Multithreaded
Java was designed to meet the real world requirement of creating interactive, networked program.
To accomplish this, java support multithreaded programming, which allows you to write a
program that do many things simultaneously
Multithreading is one of the reasons why java is such an appealing language for server side
development
Dynamic
With the help of OOPs java provides inheritance and with the help of inheritance we reuse code
that is predefined.
Java is more dynamic language that C++, C. libraries can freely add new method and instance
variable without any effect on their client
Architecture neutral
The java compiler generate an architecture-neutral object file format, so that the compiled code is
executable on many processor, given the presence of JVM

Java compiler generates byte code instruction, which JVM can understand, and JVM easily
translate byte code into native machine code.
Portable
Unlike C, C++ in Java, there are no implementation dependent aspects of specification. For
example, an in java is always a 32 bit integer, but in C++ / C, int can mean a 16-bit integer, or any
other size, in different compiler
Because java having fixed size for number type eliminates a major porting headache. String are
stored in standard Unicode format
Interpreted Compiler Combo
Java enable the creation of cross platform programs by compiling into an intermediate
representation called java byte code. This code can executed on any machine in which JVM has
been ported
High performance

Interpretation of bytecodes slowed performance in early versions, but advanced virtual


machines with adaptive and just-in-time compilation and other techniques
Robust
Compiler detects many problems, that are identified during runtime in other languages
Java is said to be strong , since it has
Exception handling built-in
strong type checking (that is, all data must be declared an explicit type)
local variables must be initialized
Secure
Because java is intended to be used in networked / distributed environment, we need to concern
more about security of data. Java enable construction of virus free, tamper- free system
Java was designed to make certain kinds of attacks impossible, among them:
- overrunning the runtime stack a common attack of worm and viruses
- corrupting memory outside its own process space
- reading or writing file without permission

JAVA PROGRAM STRUCTURE


A Java program may contain many classes of which only one class defines a main
method.

Classes contain data members and methods that operate on the data members of
the class

Methods contain data type declarations and executable statements.

The structure of the java is

documentation section
package statement
import statements
interface statements
Class definitions
main method class
{
main method definition
}

suggested
optional
optional
optional
optional
Compulsory

1) Documentation section or Comment section


- this section contains a set of comment lines giving the name of the program, the author
and other details, which is used to refer at the later stage.
- Comment lines are of 3 types. They are
1. Single line comment
this type of comment is identified by //
only one line can be commented.
e.g.,
// this is first program written in java program
2. Multi line comment
This is identified by /* .*/
Any no. of statements can be written.
e.g.,
/* this is a simple java program
file name is eg.java*/
3. Documentation comment
This is identified by /** .*/
Documentation comments allow the programmer to give information about the
program in the program itself.
This type of comment is used to produce an HTML file that contains the
documentation of the program.
This HTML file is obtain by running the program using javadoc utility program.
This javadoc program extracts information from the java program and then it creates
HTML file.
In a documentation comment, we can use some of the tags.
e.g.,
/** This class demonstrates documentation comments
* @author IImca
* @param num
* @return n
*/
in the above e.g., @author , @param, @return are some of the tags used in
documentation comments.
@author javadoc extracts the author name from this tag.
@param the parameters used in the program is known from this tag.
@return the variable to be returned is known from this tag.
2) Package Statement
Packages are group of classes or interfaces.
E.g.,
keyword user-defined package name
package

student;

The package statement is optional.

3) Import statement
Import statement in java is equal to # include statement in C++.
E.g.,
import java.lang.Math;
This statement instructs the interpreter to load Math class which is floder lang inturn
which in java folder
4) Interface statement
An interface is like a class, which includes a group of method declarations.
This is also an optional section.
5) Class definitions
Classes are the primary and essential elements of a Java program.
A Java program may contain multiple class definitions.
6) Main Method class
A main method is written inside the class.
The main method creates objects of various classes and establishes communication
between them.
e.g.,
/* the program which has main method class part
class example
{
public static void main(String args[])
// main is a static method which can be accessed directly.
{
int a=10,b=20,c;
c=a+b;
System.out.println(The addition of two nos. =+c);
}
}

FEATURES OF OBJECT ORIENTED PROGRAMMING


There are four main features
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Data hiding/data security
ENCAPSULATION
Wrapping of variables and methods into a single unit is known as encapsulation. It is the
mechanism that binds together data and code that manipulates data, and keep both safe from
outside interference and misuse
within the classes, the member of class (such as methods and fileds)may be qualified as private,
public, protected or package proctected
private member of the class is known only by with in the same object, outside it is not accessible

When any member of the class declared public, it is visible to everywhere, regardless object in
which it is defined

POLYMORPHISM
The ability of an object to take more than one form is known as polymorphism
It provide ability to define more than one functions with same name, inside class as long as
number of arguments and types of arguments are different
Compiler will identify the calling method, in term of number of arguments, types of argument and
order of arguments.
Polymorphism not only applicable for method but also applicable to constructors
Method overriding is another concept supported by polymorphism
INHERITANCE
It is the process by which one object can acquires the properties, methods of another object.
It provides the ability to reuse the definition existing class from new class. This avoid rewriting
the same code again, those already exist
It reduce programmer burden, if any modification done on parent class will automatically reflect
on all Child classes.
It support concept of hierarchical classification of classes
Parent, child, grandparent classification possible.

OBJECT

Object is actually an instance of class. Object could represent a person, place, bank account or any
other item that is handled by the program.
Every object consist attributes and functions

CLASS

A Class is a template for an object.


It helps to encapsulate entire set of data and code that operate on data into a single user defined
data type
General form of a class is

class classname {
// instance field declarationa
type instance-variable-1;
type instance-variable-2;

type instance-variable-N;
// method definition
type methodname-1(parameter-list) {
//body of method }
type methodname-2(parameter-list) {
//body of method }

type methodname-N(parameter-list) {
//body of method }
//constructor definition
classname(parameter-list) {
//body of constructor
}
.
}

The class body (the area between the braces) contains following item :
- constructors for initializing new objects
- field declarations
that provide the state of the class and its objects

called as instance field


Syntax
datatype variablename[=value];
- methods
the procedure /code that operates on the data .
Syntax
accessspecifier returntype methodname(parameter list){}.
Example

class Box {
// instance field
double width, height, depth;
// constructor of 3 parameters
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// method to compute and return volume
double volume() {
return width * height * depth;
}
}
OBJECTS
Defn:

Called as instance of a class


or
An object in Java is a block of memory that contains space to store all the instance
variables.
Declaring objects or creating objects
Creating an object is referred as instantiating an object.
Once class is defined, you can create new data-type of that class.
Obtaining object of the class is a two-step process:

1. Declare reference variable of class type.(i.e., the data type of a variable is a class
name).
Syntax
classname reference-variable; // only declaration
Note: This declaration does not define object, instead it is indicating that b is reference
variable of object Box, presently it is point to null object
2. Acquire an actual, physical copy of the object and assign its address to the reference
variable This process is done by new operator
new operator dymamically allocate memory for an object and return reference(i.e.,
address in memory allocate to it) to it(i.e. to the object)
This could be done using following syntax:
reference-variable = new classname([argument-list]);

Syntax for creating object


classname objectname;
// declare

objectname = new classname(); // memory allocated to the object


or
classname objectname = new classname(); // two process in single step
e.g., for the above class Box , the object is created as
Box b; //declare
b =new Box ();//memory allocated to the object
or
Box b = new Box (); // two process in single step

attempt to access the variable b after declaration statement , gets compile-time


error.

Pictorial representation for the above object creation(the two-step process)


Action

Statement

Effect or result

Declare

Box

b null (address is not


allocated for object b

Object
reference

b=new Box();

b;

baddress is allocated
b
width=10,height=12.5,depth=9.0
Box(float,float,float){}
double volume(){}

METHODS

Procedure or code that operates on instance fields


Methods of the class has all rights to access, set, modify instance field of class
Methods could have any access specifier such as public, private, protected, and package-protected
It may have return type, and can have zero on more arguments. It general signature is

return-type methodname-1(parameter-list)
{
//body of method
}
return-type and parameter-list can be of any valid java primitive data-type or type of user-defined
class. If the method does not return a value, its return-type must be void
Only non-void methods require to have return-statement within its body.
Syntax of return statement
return(value);
Different types of methods are
1. Mutator Method : Methods that change the instance fields
2. Accessor Method: Methods that only access instance fields without modifying it

E.g., for mutator and accessor method

class student
{
String name;
void setname(String s) // Mutator method
{ name=s; }
String getname() // accessor method
{ return name; }
public static void main(String args[])

{
student stud=new student();
stud.setname(Sarveswaran);
System.out.println(Name of the Student is + stud.getname());
}
}

METHOD OVERLOADING
Defn
Creating methods that has
same name
different parameter lists(i.e., arguments)
different definitions(i.e., each method has different meaning)
is called method overloading.
Or
Defining two or more methods within the same class that share the same name, with
different parameter declarations(either number of parameters or types of parameters are
different) is called as overloaded methods/method overloading.
Method Overloading is one way where Java implements the concept Polymorphism(i.e.,
static binding/compile time binding).
Automatic type conversion will happen in invocation of overloaded methods, if exact
method signature not found.

How overloaded method invocation is determined?


i) First, Java runtime system matches name of the method with the name of the methods
exists in the object.
ii) If more than one method found with same name, method determination is done using
number of arguments
iii) If more than one method found with same number of argument, method determination
is done using type of the arguments
E.g.,
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
double test(double a) {
System.out.println("double a: " + a);
}
void test(double a, double b) {
System.out.println("a and b: " + a + " " + b);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20); // here intergers are automatically converted to double

ob.test(123.25);
}
}

METHOD PARAMETER
Two way of argument passing to methods
Arguments are passed to methods in two ways
call-by-value
method copies the value of an actual argument into formal parameter
Therefore, changes made on formal-parameters within the method, does not affect the
actual-parameters.
All java primitive types/ simple types are passed to method as passed-by-value
call-by-reference
reference to an argument is passed to the method, instead of value of an argument.
All java classs objects are passed to method as reference

Note: Java always uses call by value


The follwing program demonstrates both feature
class MyObject
{
int a;
output
MyObject(int i)
before call x=15
{
increment:i=30
a=i;
after call x=15
}
}

before call mo.a=15

class Test {
increment:o.a=30
// call by value
after call mo.a=30
static void increment(int i)
{
i*=2;
System.out.println("increment:i="+i);
}
// reference passed as call by value
static void increment(MyObject o)
{
o.a*=2;
System.out.println("increment:o.a="+o.a);
}
}
class ArgumentDemo {
public static void main(String args[]) {
int x = 15;
Explains call by
System.out.println("before call x="+x);
value using primitive
Test.increment(x);
type
System.out.println("after call x="+x);
MyObject mo = new MyObject(15);
System.out.println("\nbefore call mo.a="+mo.a);
Test.increment(mo);
System.out.println("after call mo.a="+mo.a);
}
}

Shows call by value by


passing reference

ACCESS SPECIFIERS
Encapsulation provides access control (i.e., what part of the program can access the
members of the class)
Visibility control means restricting the access of the instance variables and methods of
the class.
Different types of access specifiers are
1) public
- The instance variables and method declare as public can be accessed in
i)
same class
ii) subclass(i.e., derived class) of same package
iii) other classes in same package
iv) subclass in other packages
v) Non-subclasses in other packages
- to make instance variables and method as public , we have to specify it in the
program.
- e.g., public int a=10;
public void area(){ }
2) friendly/package protected/package private/defualt
- When access specifier is not specified in the program, the accessibility is treated as
friendly(i.e., default access specifier)
- The accessibility of friendly variables and methods are
i) within same class
ii)
subclass of same package
iii)
other classes in same package
- e.g.,
int a;
void area(){}
3) protected
- The accessibility of protected fields are
i) within same class
ii)
subclass of same package
iii) other classes in same package
iv) subclass in other packages
- e.g., protected int a=10;
protected void area(){ }
4) private
- the methods and variables declared as private can be accessed only in the same
class.
- A method declared as private work as method declared as final.
- e.g., private int a=10;
private void area(){ }

STATIC MEMEBERS
creating a member (variable & method) that can be called without instance of the class, but
accessed using class name itself.
To create such a member, precede its declaration with the keyword static

When a member of the class is declared as static, it can be accessed before any objects of its class
are created. You can declare both methods and variables as static
The most common example of static member is main() method, main( ) declared as static because it
must be called before any object exist

1. Static Field
Static variables are global variables for the objects created under same class
when object of the class are declared, no copy of static variable is made, instead all
instance share the same static variables
Syntax of static variable
static datatype variablename [=value];
E.g.,
static int eid=101;
To access Static variables from other class, the general form is
classname.variablename;
is a static variable in Math class
e.g.:
circle-area = Math.PI * r * r;

2. Static method
Do not operate on objects
Methods declared as static has the following restrictions
1) They can call only other static methods
2) They must access only static data
3) They cannot use this or super keyword in any way
Math is the class, which has all its methods and variables as static.
To call static method outside of it class, use the following general form
Classname.methodname([argument-list]);
static method in Math class
e.g.:
root = Math.sqrt(10);

3. Static constants
One common use of static is to create a constant value thats attached to a class.
add the keyword final in there, to make name a constant (in other words, to
prevent it ever being changed).
make name uppercase by convention, to indicate that its a constant
Syntax
static final datatype varname = value;
E.g.
static final double MAX = 5;

4. Static block/Static initialization block


Used to dynamically initialize static variable during runtime using some computation
Static block gets executed only once, when the class is first loaded
Static block in java is executed before main method.
That is, Java execution starts from static blocks and not from main() method.
Static block can be placed anywhere within the class, but outside of any method,
constructor in the class.
Can have any number of static blocks in the class
The general syntax of static block is:
static

{
//your static variable initialization code here
}
Example Program that describe the features of Static Members
class MyStatic {
static int a = 3;
static int b;
int c;
void setC(int tmp)
{
c=tmp; }

static variable
instance variable

static void showAB( ) {


System.out.println("a = " + a);
System.out.println("b = " + b);
display( );

Static method which uses


only static variable a, b
not c and access only
static methods

// setC(10); error because setC( ) is non static method


// System.out.println("c = " + c); error because c is non static variable
}
static void display() {
System.out.println("message from static display\n");
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}

Static block that executes when


the class is first loaded

}
class StaticDemo
{
public static void main(String args[])
{
MyStatic.showAB( );
MyStatic.a=10;
//Mystatic.c=20; //error
MyStatic ms=new MyStatic( );
ms.c=20;
System.out.println("ms.c="+ms.c+",ms.a"+ms.a);
ms.showAB();
}

Output:
Static block initialized.
a=3
b = 12
message from static display
ms.c=20,ms.a10
a = 10
b = 12
message from static display

CONSTRUCTORS
Defn :
A constructor initializes instance variables while creating an object.
or
Constructor is automatically called immediately after the object is created, before the new
operator completes.

Constructor is always called with the new operator


Constructor cannot be called using object name or class name
Constructors are a special method, which has the same name as class name and accept zero or
more arguments as parameters
They are used to initialize the data member of object, when it is created.
It must have access specifier as always public or package protected(i.e., default)
Constructor has no return value because , the return-type of the classs constructor is always
class type itself
If your class does not contain constructor definition, java system will automatically define default
constructor for your class

Types of constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
class_name(){}
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor.

CONSTRUCTOR OVERLOADING
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.
The compiler differentiates these constructors by matching the parameters in the list and
their type.
A compiler time error occurs if the compiler cannot match the parameter or if more than
one match is possible. This is called as overloading resolution.
Example demonstrates constructor and constructor overloading
/* Here, Box defines three constructors to initialize the dimensions of a box in various ways.*/
class Box
{
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = height = depth = -1;// use -1 to indicate an uninitialized box
}
// constructor used when cube is created
Output:
Box(double len) {
Volume
of mybox1 is 3000.0
width = height = depth = len;
Volume
of mybox2 is -1.0
}
Volume of mycube is 343.0
double volume() {
return width * height * depth;
}
}

class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}

FIELD INITIALIZATION
Instance Fields of a class can be initialized in different ways . they are
1. Initializing using constructor
a) Default field initialization(when default constructor in not specified)
If a instance field is not set explicitly in a constructor , and no default constructor is
written, default constructor is create automatically and all the instance fields are
initialized to default values.
Default values => int to 0, boolean to false, object reference to null
b) Using default constructor(creating default constructor explicitly)
Default constructor is created and all the instance fields are set to the default values
or the values provided by the user
2. Initializing during declaration/Explicit field initialization
a) Setting initial value during declaration
During declaration itself the initial value for the instance filed is assigned
E,g.,
class student
{
int sno=101;
String sname=siva;
}
b) Field initialization with a method call
Assigning initial value to the instance field by calling a method
e.g.,
class Employee
{
int assigneno()
{
int eno=10;
return eno;
}
// empno =10 is initialized by calling assigneno() method
int empno=assingeno();
}
3. Using Instance initialization block

Class declaration can contain arbitrary blocks of code which is executed whenever an
object of that class is created. This arbitrary block is called as initialization block
This block can contain operations(i.e., executable statements/initialization of instance
field) that are common to all objects
is invoked after the parent class constructor is invoked.
E.g.,
class bike
{
int speed;
bike()
{
System.out.println(Speed is + speed);
}
// instance initialization block
instance
initialization
block
{
invoked whenever the object this
System.out.println(inside initialization block);
class is created
speed =100;
}
public static void main(String args[])
{
bike b=new bike(); // when b is created instance initialization block is executed
}
}
Output
Inside initialization block
Speed is 100

Finalize() method
is in System class
is a method that is called just before an objects final destruction by the garbage collector
Syntax
protected void finalize() throws Throwable
is invoked each time before the object is garbage collected to free the resource used by
the objects
any object not created with new operator use finalize() for cleanup process
Note: neither finalization nor garbage collection is guaranteed.

PACKAGES
Definition
A package can be defined as a grouping of related type(classes , interfaces) providing
access protection and name space management
Packages are container for classes; they are used for the following reason:
To avoid name collision of classes developed by different programmer, different software
company

To import classes: Classes stored in a package are explicitly imported into new class definition
from its location, without making copy of that in your folder
Packages are also used to control accessibility of the classes, members of the classes

Packages are classified into two types


1. Predefined packages
2. User-defined packages
1.
Predefined packages
Predefined packages are those which are developed by SUN micro systems and supplied
as a part of JDK (Java Development Kit) to simplify the task of java programmer.
some of the predefined packages are
java.lang , java.util, ,java.awt, java.io
2.

User defined packages /defining packages

To create a package simply include a package command at the top of the every source file
A package statement must be the first statement in the java source file.
Any classes declared within that file will belong to specified package.
A source file must have only one package statement
If you omit package statement in your java source code, the classes for your souce code are put
into the default package, which has no name
The general form of the package statement is:

package is keyword

package <pkg>;
here pkg is the name of the package.
For example:
package mypackage;
The package name and folder name in which your java file stored must have the same
name
Hierarchy of packages can also be created
This is done by creating a hierarchy of folder, and separating each package name using
period(.).
The general form of multileveled package is shown here
package pkg1[.pkg2[.pkg3]];
For example:
package pack1.subpack1;

Note: package in java is converted into directory (i.e., folder) during execution
e.g., java.util.* is converted as java\util\.*
Simple example of package
package name is mypack . it is written as first
package mypack;
statement .
class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

Note: the above program must be saved in folder mypack and the name of the source
file must be Simple.java
To Run the package program
i) Compile using javac
D:\sathiya\javac Simple.java
ii) Run using java

Specify packagename.mainmethodclassname

D:\sathiya\java mypack.Simple

Welcome to package

Setting a class path


By default java runtime(i.e., interpreter) looks for .class files only in the current directory,
Because java runtime uses the current working directory as its starting point
To import classes in the package from anywhere, add a path of parent directory of your package,
where it residing into environment variable classpath.
For example if your package pkg1.pkg2 is residing in d:\sathiya then you have to set classpath has
set classpath=%classpath%;d:\sathiya;.;

Importing package/class importation


A class can use all classes from its own package and all public classes from other packages.
Accessing public classes from other packages can be done in
a) Using fully qualified name
Add full package name in front of every class name
b) Using import statement
Can import certain classes from a package or whole package
Syntax
import pkg1[.pkg2].(classname | * );
you specify classname or *. Here * indicates that the java compiler should import the entire
package into memory
In java source file, import statements must occur immediately following package statement
and before any class definitions
e.g.1:
import java.util.Scanner; // (or) import java.util.*;
class Employee
{
public static void main(String args[])
{
String name;
Scanner input=new Scanner(System.in );
System.out.println(input.nextInt());
}
}
e.g.2 (without import statement using fully qualified name)
class Employee
{
public static void main(String args[])
{
String name;
java.util.Scanner in=new java.util. Scanner(System.in );

System.out.println(input.nextInt());
}
}

Static import
the static import facilitate the java programmer to access any static member of a class
directly. There is no need to qualify it by the class name.
syntax
import static packagename;
e.g.,
import static java.lang.System;
Program that implements import static
import static java.lang.System;
class StaticImportExample
{
public static void main(String args[])
{
out.print("Hello");//Now no need of System.out
out.println(" Java");
}
}
Output:
Hello Java

Introducing Access controls


important attribute of encapsulation is access control.
Through encapsulations access control, you can control what part of the program can access the
member of the class, which help to prevent misuse of member of the class
Java supports rich set of access-specifier that defines various level of visibility of class members.
They are : public, private, protected, and default (package protected)
Visibility/accessibility control means restricting the access of instance variables and methods of
the class from outside world
Java contains 4 categories of visibility for class members as shown in the table:

Access location
Within the same class
subclasses in the same packages
non-subclass in the same package
subclass in other package
non-subclass in other package

private
Yes
No
No
No
No

default/package
private/package
protected
Yes
Yes
Yes
No
No

protected public
Yes
Yes
Yes
Yes
No

Yes
Yes
Yes
Yes
Yes

Note:
A Class has only two possible access levels: default and public
When a class is declared a public, it can be accessed in the package or from other packages.
If class is declared without access-specifier(i.e., default), it can be accessed from other classes
within the package, but not from other packages

Example program for package


The following programs has to be stored in the pack1\subpack1 folder
Parent.java

package pack1.subpack1;
public class Parent {
private int a=10;
int b=20;
protected int c=20;
public int d=40;
public int getA() // method helps to access private variable a from other classes
{ return a; }
}
SamePackage.java
package pack1.subpack1;
public class SamePackage {
public static void main(String args[]) {
Parent p = new Parent();
// error, private variable not accessible outside its class
// System.out.println(Private variable + p.a);
// used public method to access a of same class
System.out.println(Private variable: + p.getA());
System.out.println(Default variable: + p.b);
System.out.println(Protected variable : + p.c);
System.out.println(Public variable: + p.d);
}
}
Note : Here both the classes Parent and SamePackage are stored in the same package
pack1.subpack1, so that SamePackage.class, can access member of Parent : b, c and d , but not a

Output
Private variable: 10
Default variable: 20
Protected variable: 30
Public variable: 40

THE STRING CLASS


Strings are a sequence of characters.
Java does not have primitive string type.
Java library contains pre-defined class called String class
In the Java programming, strings are objects.
The String class is immutable, so that once it is created a String object cannot be changed.
String class is in java.lang package
String class is declared as final(i.e, this class cannot be inherited from other class)

String Constructors/Creating Strings


String object can be constructed a number of way.
1. The most direct way to create a string is to write:

String greeting = "Hello world!";


here, "Hello world!" is a string literala series of characters that is enclosed in
double quotes.
Whenever compiler encounters a string literal in your code, the compiler creates a
String object with its valuein this case, Hello world!.
You can also create string using a constructor. The constructor of the String is listed below:
2. String( ); - When you invoke default constructor, it creates string with no character in it.
e.g.:
String s=new String( ); // s=null
3. String(String str); - It will create new String object from the existing object str
e.g.:
String s1=Welcome;
String s2=new String(s1); // s2=Welcome
4. String(char c[]); - It will create new String object from character array c. In the following
example string object is created from character array:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println(helloString); // print hello
Finding length of the string
a) int length() - This method is used to find number of characters stored in a string object
String s= "welcome ";
int len=s.length();
System.out.println( length of s is+len); // len = 7

Character Extraction
String class provides a number of ways to extract characters from string object.
a) char charAt(int index);
used to retrieve single character from the specified index.
This will raise ArrayIndexOutofBounds exception, if the value of index is more than the
length of the string
E.g.,
String s=welcome;
char ch=s.charAt(4);
System.out.println(ch=+ch); \\ch=o
b) char[ ] toCharArray(); - converts all the characters in a String object into a character array.
String s=abcd;
char c[]=s.toCharArray( );
for(char tmp:c)
System.out.print(tmp+,);

//c= a

\0

// will print a,b,c,d;

String Comparison
The String class includes several methods that compare strings or substrings within strings
a) boolean equals(Object str)
used to compare two strings for equality. Here, str is the String object being compared with
the invoking String object.

It returns true if the strings contain the same characters in the same order, and false
otherwise.
The comparison is case-sensitive
e.g.,
String s1=Hello;
String s2=new String(Hello);
String s3=new String(hello);
System.out.println(s1.equals(s2)=+ s1.equals(s2)); //return true
System.out.println(s1.equals(s3)=+ s1.equals(s3)); //return false
System.out.println(s1.equalsIgnoreCase(s3)=+ s1.equalsIgnoreCase(s3));
//return true
b) boolean equalsIgnoreCase(String str); used to compare two strings without case sensitive.
c) equals( ) versus ==
It is important to understand that the equals( ) method and the == operator perform two different
operations.
equals( )
==
The equals( ) method compares the characters
The == operator compares two object references to
inside a String object
see whether they refer to the same instance
It is a method
It is an operator
The following program shows how two different String objects can contain the same characters, but
references to these objects will not compare as equal:

String s1 = "Hello";
String s2 = new String(s1);
String s3=s1;
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
System.out.println(s1 + " == " + s3 + " -> " + (s1 == s3));
The above code fragment will print:
Hello equals Hello -> true
Hello == Hello -> false // s1 and s3 refers to different address in memory
Hello == Hello -> true // s1 and s3 refers to same address in memory
d) int compareTo(String str) - The Shing method compareTo( ) will compare the content

of invoking string with str and return the following values:


< 0, If the invoking string object is less than parameter str
= 0, If the invoking string object is , equal to parameter str
> 0, If the invoking string object is greater than parameter str
String s1 = "Bala";
String s2 = "Arun";
if(s1.compareTo(s2)==0)
System.out.println( both s1 and s2 are equal);
else if(s1.compareTo(s2)<0)
System.out.println( s1 smaller than s2);
else
System.out.println( s1 greater than s2);
Output: s1 greater than s2
e) int compareTolgnoreCase(String str)
This method returns the same results as compareTo(), except that case differences are ignored. For
example

SEARCHING STRINGS
a. int indexOf(int ch) : searchs the first occurrence of the value of ch in the String starting from 0th
location or -1 will be return if no value of ch found in the given string
b. int indexOf(int ch, int offset): start search the value of ch in the given string starting from the
index mentioned in the offset, not from index 0
String s=object;
char ch=e;
int loc=s.indexOf(ch,2);
if(loc==-1)
System.out.println(ch+ " not found in the given string );
else
System.out.println(ch+ " found at "+loc); // result : o found at 7
c. int indexOf(String ss): used to search one sub string in another. If found return index of the first
occurrence, otherwise return -1
d. int indexOf(String s, int offset): start search the given word starting from index mentioned in the
offset, but not from index 0
String sentence=object oriented programming language;
String word =language;
int loc=sentence.indexOf(word);
if(loc==-1)
System.out.println(word+ not found);
else
System.out.println(word + " found at "+loc); // result : language found at 16

MODIFYING A STRING
a. String concat(String s1)
It is used to concatenate two strings and return concatenated string as result
String s= "welcome ";
S=s.concat(" to java ");
System.out.println(s=+s); // s=welcome to java
Strings are more commonly concatenated with the + operator, as in
Hello, + world + !
which results in
Hello, world!
The + operator is widely used in print statements
b. String substring(int startIndex);
This method is used to extract portion of substring from the invoking string, starting from the
startIndex up to the end of the string
String s=java programming;
int loc =s.indexOf(prog);
String ss=s.substring(loc);
System.out.println(ss=+ss); // output : ss=programming
c. public String substring(int startindex , int endIndex);
method is used to extract portion of substring from the invoking string object, starting startIndex up
to endIndex-1
String s=java programming;
String ss=s.substring(5,12);
System.out.println(ss=+ss); // output : ss=program
d. String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by replacement. The
resulting string is returned. For example
String s = "Hello".replace('l', 'w'); // puts the string "Hewwo" into s

e. String trim( )
This method will remove any leading and trailing whitespace present in the invoking string, return the
resultant string as result
String s1 = "
how are you
";
String s2 = s1.trim();
System.out.println("|"+s1+"|");
System.out.println("|"+s2+"|");
The output of the above code shown here:
|
how are you
|
|how are you|

JAVA DOCUMENTATION COMMENTS


The Java language supports three types of comments:
Comment
Description
/* ------- */
Multi line comment
// text
One line comment
This is a documentation comment and in general its called doc comment.
/**
The JDK javadoc tool uses doc comments when preparing automatically
documentation */
generated documentation.
What is Javadoc?
Javadoc comments are any multi-line comments ("/** ... */") that are placed before
class, field, or method declarations.
They must begin with a slash and two stars, and they can include special tags to describe
characteristics like method parameters or return values.
The HTML files generated by Javadoc will describe each field and method of a class,
using the Javadoc comments in the source code itself.
The javadoc Tags:
The javadoc tool recognizes the following tags:
Tag
@author
@param

@return
@throws
@version
@see

Description
Specify the author of the program

Syntax
@author name-text

Example
@author IIICSE

@param numA This is


Specifies parameter-name followed by the @param parameter- the first paramter to
description of the Parameter.
name description
addNum method
Specifies what type of value the method
returns
The @throws and @exception tags are
synonyms.
Specifies under what version this java
program written
"See Also" heading with a link or text

@return int This


@return description returns sum of numA
and numB
@throws class-name @throws IOException
description
@version version- @version 1.7.0
text
@see reference
@see IOException

entry that points to reference.


Specifies on what date onwards this
program works

@since

@since release

Example:
import java.io.*;
/**
* @author IIICSE
* @version 1.7.0
* @since 21.07.2014
*/
public class AddNum {
/**
* This method is used to add two integers.
* @param numA This is the first paramter to addNum method
* @param numB This is the second parameter to addNum method
* @return int This returns sum of numA and numB.
*/
public int addNum(int numA, int numB) {
return numA + numB;
}
/**
* This is the main method which makes use of addNum method.
* @param args Unused.
* @return Nothing.
* @throws IOException On input error.
* @see IOException
*/
public static void main(String args[]) throws IOException
{
AddNum obj = new AddNum();
int sum = obj.addNum(10, 20);
System.out.println("Sum of 10 and 20 is :" + sum);
}
}
Output of javadoc
public class Addnum extends java.lang.Object
Since:
21.07.2014
Version:
1.7.0
Author:
IIICSE

Method Detail
addNum
public int addNum(int numA,

int numB)

This method is used to add two integers.

@since 21.07.2014

Parameters:
numA - This is the first paramter to addNum method
numB - This is the second parameter to addNum method
Returns:
int This returns sum of numA and numB.

this operator
this operator is used for two purpose
a) to refer the current object created
b) to refer to the hiding instance variable
a) to refer the current object created
1. this is used inside any method to refer to the current object invoked.
2. this keyword always refers to the object that is currently invoked(i.e., currently created).
3. e.g., consider the program
class thiskey
{
int l,b;
thiskey(int l1, int b1)
{
this.l=l1;
this.b=b1;
}
}
class mclass
{
public static void main(String s[])
{
thiskey th=new thiskey(2,3);
thiskey th1=new thiskey(2.3);
}
}
4. In the above example when the instance th is created, this keyword refers to the instance
th.(i.e., th and this keyword refers to same memory location and the methods ,instance
variables of th belong to this keyword also). Similarly , when th1 object is created this
keyword now points to th1 object not th object.
b) to refer to the hiding instance variable
- hiding instance variables means the local variables has the same name as instance
variable in the class.(i.e.,local variable hides instance variable).
- To differentiate between local variable and instance variable, this keyword is used.
- e.g.,
class thiskey
{
int l,b; // l and b are instance variable
local variable
thiskey(int l, int b)
{
/* Differentiating local variable and instance variable in the
constructor.
1. instance variable is represeneted by this keyword. e.g., this.l,
this.b
2. local variable are represented as it is */

this.l=l;
this.b=b;
}
}
class mclass
{
public static void main(String s[])
{
thiskey th=new thiskey(2,3);
}
}

UNIT-II
INHERITANCE
Defn : Creating a new class form already existing class
It is the acquiring the properties, methods of an existing class to the new class
It allows the creation of hierarchical classification of classes.
Already existing class is called as super class or base class or parent class.The new class
is called as subclass or derived class or child class
Advantage is
Reuse the methods and instance fields of existing class at the same time can add new
methods and instance fields
extends keyword is used to inherit a class from another class.
syntax is
access specifier class subclassname extends superclassname
{
// body of the class
}
class and extends are keywords. The keyword extends says, the properties of
superclass is extended to the subclass.
Access specifier can be public or default.
subclass can access all members of superclass ,except private members
No class can be a superclass of itself.
Different types of inheritance java supports are
1. Single Inheritance child can have only one base class
2. Multilevel Inheritance it define grandparent, parent and child like more than one
level of depth of inheritance
3. Hierarchical Inheritance The same base class used as parent by many derived
classes
Java does not support multiple inheritance ,since single child class can have more than
one parent. But java support multiple inheritance through concept called interface
Single Inheritance
The subclass is derived from only one base class, it is called as single inheritance.
The following example describes single inheritance:
class A//superclass
{
class A Base class
//body of the superclass

class B

Sub class

}
subclass
class B extends A
{
//body of the subclass
}
2. Multilevel Inheritance
Multilevel inheritance, describes grand parent, parent, child relationship among inheriting
classes. A child class inherits feature from it parent class, which in turn has another parent as
shown below:
class A A act as base class for B
e.g.:
class A {
// Grand Parent

}
class B extends A {

}
class C extends B {

class B B derived from A, But base class for C


// Parent

class C

Subclass C is derived from B and C

3. Hierarchical Inheritance
If more than one child is derived from same superclass it is called hierarchical inheritance.
e.g.: class A
{

}
class A
class B extends A {

}
class B
class C
class D
class C extends A {

}
Class Hierarchy/Inheritance hierarchy(2 marks)
The collection of all classes extending from a common superclass is called as inheritance
hierarchy
class A

class B

class C

class D

class E

class F

class G

Using super keyword


super keyword can be used in two way. They are
(i) is used to call immediate super class constructor from sub-classes. Syntax is

super(parameter-list);
- Here parameter-list specifies argument list that should match with the constructor

defined in the superclass.


- super keyword must always be the first statement inside a subclass constructor.
e.g.

class Base
{
int x,y;
Base(int x,int t2)
{
this.x=x;
y=t2;
}
Base(int t1)
{
this(t1,t1);
}
}
class Derived extends Base
{
int z;
Derived(int a,int b, int c)
{
super(a,b); //it invokes Base classs constructor
z=c;
}
}
(ii)Second form of super is used to access hidden members of super-class from sub-class. General
form is
super.member
- Here member can be either method or instance-variable present in the base class.
- Hidden members means, with the same name if methods / variables defined in both super-class
and sub-class, super-class variables / methods are not visible from the sub class
e.g.:

class Base
{
int x;
void display()
{ System.out.println(base:display ); }
}
class Derived extends Base
{
int x; // this x hides the x in Base
void display()// this hides display in Base
{
System.out.println(derived:display );
x=10;
// x in Derived
super.x=20;
// x in Base
super.display( ); // invoke display( ) in Base
}
}

Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signatures
as in its super class, then the method in the subclass is said to override, the method in the
superclass.
(i.e., method defined in the subclass must have same method name, same return-type,
same number of arguments, and same type of arguments as in its superclass)
When the overridden method is called from within the subclasss object, it will always
refer to the method in subclass, not in the superclass. The method in the superclass is
hidden.
Advantage is
Overridden methods allow java to support runtime polymorphism.
Method overriding is possible only when inheritance concept is implemented.
Example here:
class A
// display j-- this overrides show() in A
Output:
{
void show()
i:
1
int i;
{
j: 2
A(int a)
super.show( ); //calls show( ) in A
{ i = a; }
System.out.println("j: " + j);
void show()
}
{ System.out.println("i: " + i); }
}
}
class Override
class B extends A
{
{
public static void main(String args[])
int j;
{
B(int a, int b)
B subOb = new B(1, 2);
{
subOb.show(); // this calls show() in B
super(a);
}
j= b;
}
}

POLYMORPHISM
Polymorphism allows general class to specify methods that will be common to all of its
derived classes, while allowing subclasses to define specific implementation of some or all
of those methods defined in the general class
Polymorphism also allows the subclasses the flexibility to define its own methods
Dynamic Method dispatch /dynamic binding/late binding/runtime binding
Automatically selecting the appropriate overridden method at runtime.
This is achieved by calling overridden method through a super class reference variable.
Static binding/compile time binding
Method call is resolved at compile time
e.g., method overloading
e.g. for runtime polymorphism( Base class reference variable can reference subclass object)
class A {
void display()
{
System.out.println("Overridden method in class A ");

}
}
class B extends A {
int x;
void display() {
System.out.println("\nOverridden method in class B ");
}
}
class Override
{
Output:
public static void main(String args[]) {
Overridden method in class A
A aref;
aref=new A();
Overridden method in class B
aref.display( ); // calls classs A display
aref =new B( ); // Bs object is assigned to reference variable of class A
aref.display( ); // calls classs B display, not As display
// aref.x=10;
//error, reference varaible of A does not aware of B's variable x
((B)aref).x=10; //correct, because after explicitly type casting to B it is possible
}
}

A super class reference variable can reference subclass object.


When super classs reference variable pointing to derived classs object, you can access
only members those defined in the super class, additional members added in the derived
class cannot be accessible, because base class does not aware of those members.
To invoke additional members of subclass, explicitly typecast super class reference
variable into derived class reference.

Use of final keyword


final keyword can be used in 3 ways
1.
2.
3.
1.

To create constant variable in the class( like const variable in C/C++)


To prevent method Overriding in the derived classes
To prevent inherting particular class from other classes

variables are declared final to make it as constant variables in the class

If class member variable declared as a final, its value cannot be changed anywhere in your program
during execution
It must be initialized at the time of declaration itself.
Name of the final variable must always be written in upper case letters to differentiate between final
variables from other variables
final variable cannot be declared inside a method. They should be used only as class variables
e.g.:
class XYZ
{
final double PI=3.1415; // legal declaration because declared as class variable
void method1(int r)
{
final int J=1234;//illegal declaration because declared as method variable
PI=PI*2.0; //error because final variable cannot be modified
int area=PI *r*r; // legal because final variable is not modified
}
}
2. methods are declared final to prevent overriding it from derived classes

When method defined within the super class is declared as final, it cannot be overridden from any
of its subclasses.
e.g.:
class Base {
final void display( ) {
System.out.println(base display);
}
}
class B extends A {
void display( ) {
// error cannot override final method here
System.out.println(illegal)
}
}
3. classes are declared final to prevent other classes inheriting it
If the class is declared as final it cannot be inherited from any other classes.
String is the classical example for final class. Features of String class cannot be inherited from any
other classes.
If the class is declared as final, the methods defined within the class is also treated as final
implicitly
e.g.:
final class NoInherit
{
double calculate(double x) { // also treated as final
return 2 * x / (x * 0.5);
}
}
// error, because final class cannot be inherited
class MyClass extends NoInherit
{
//..
}

ABSTRACT CLASS
Defn:
Creating a superclass which defines only a structure of a method (i.e., this method does
not contain source code in it) that is shared by its subclass. The source code for these methods
are implemented (i.e., written) in the subclasses.
Abstract Method

If the methods are declared without body, within the class, it has to be qualified with
abstract clause.
The syntax of abstract method is:
abstract return-type methodname(argument-list);
Abstract method always starts with abstract keyword and ends with semicolon( ; ), without
its body
Any class that contains one or more abstract methods must be declared as abstract.
To declare a class as abstract, write abstract keyword in front of the class keyword at the
beginning of the class declaration.
Syntax of abstract class is:
keywords

e.g.:

[public] abstract class class-name


{
//body of the abstract class with one or more abstract method decalration
}
- getName() is of abstract method.
abstract class Person
- It does not have code in it.
{
- It is compulsory overridden by the
subclass of Person
- The class Person is made abstract
since it contains abstract method

private String name;


public abstract String getName( );
}
Abstract class can also contain instance variables, and other non-abstract method within
it.
you cannot instatiate abstract class, which means object of the abstract class cannot be
created, but but reference can be created of abstract class
e.g., for the above example , for class Person creation of instance is not possible
i.e., Person a=new Person (); // invalid instance
Person aref; // valid, aref is called as reference variable
All these abstract methods must be implemented in the derived classes or the derived class has to
be declared as abstract.

Abstract constructors and abstract static methods cannot be declared.(i.e., we cannot


write constructor of the abstract class and the abstract method cannot be made static).
e.g., abstract class A
{
// invalid constructor bcose, the construct is declared as abstract
abstract A()
{
System.out.println(Invalid constructor );
}
// illegal method a1(), bcose the abstract method cannot be made static
abstract static void a1(); // invalid
}
Abstract methods are called as subclasser responsibility (means, the subclass has to write
code for the abstract methods).
e.g.,
abstract class shape
{
int l,b;
shape(int l,int b)
{
this.l=l;
this.b=b;
}
abstract void area();// abstract method
void ordinarymethod()
{ System.out.println("non-abstract Method in the abstract class"); }
}
class rect extends shape
{
rect(int l1,int b1)
{
super(l1,b1);
}
void area()
{
System.out.println("Area of a rectangle : "+ l*b);

Output
}
Area of a rectangle : 50
class Mabstract
Non-abstract Method in the abstract class
{
public static void main(String args[])
{
//shape s=new shape()// illegal creation of instance
shape serf; // legal creation of reference for superclass which is abstract
serf = new rect(10,5);
serf.area(); // belongs to class rect
serf.ordinarymethod();
}
}

INTERFACE

An interface is a pure-abstract class, which contains only set of abstract methods, and set
of final static variables within it.
By using interface, you can specify what its derived class must do, but not how it does it
An interface is similar to classes, but lack instance-variables and non-abstract methods.
when implementing an interface, derived class must define all abstract methods declared in
the interface, if not the class is treated as abstract class
Interface are designed to support dynamic method resolution at runtime
Defining an interface
Syntax
[public] interface interfacename [extends another-interface-name]
{
return-type method-name1(argumentlist); implicitly abstract methods
return-type method-name2(argumentlist);

type variable1 = value;


final static variables
type variable2 = value;

}
Access-specifier of interface is either public or default (package protected). When access
specifier is public, it can be accessible from other packages .If no access-specifier used
then, it can be accessible only within same package.
All the methods are implicitly abstract methods and all variables are static final
variables.
All methods and variables are implicitly public if the interface is declared public.
e.g.:
interface Shape
{
final static variables
int PI=3.1415;
double area( );
abstract methods
double volume( );
}
here PI is static final variable, and area( ) and volume( ) are abstract methods

Implementing Interfaces

Once an interface has been defined, one or more classes can implement that interface
using a keyword implements
Syntax
class classname [extends super-classname] implements interface1[, interface,]
{
//body of the class
}
A class can implements any number of interfaces and also can extends another-class
simultaneously.
Java supports multiple inheritance only through concept of interface
E.g., Note: read this program for university practicals

interface shape
{
float PI=3.14f;
float area();
}
class square implements shape
{
float l;
square(float l)
{ this.l=l; }
public float area()
{ return l*l; }
}
class rect extends square implements shape
{
float b;
rect(float l1, float b2)
{
super(l1);
b=b2;
}
public float area()
{return l*b;}
}
class circle implements shape
{
float r;
circle(float r)
{this.r=r;}
public float area()
{return PI*r*r;}
}
public class Interfacedemo {
public static void main(String args[]) {
shape sp;// reference variable of interface shape

sp=new square(10);// assign square object to reference variable


System.out.println("sp.area="+sp.area());
sp=new rect(10,5);
System.out.println("sp.area="+sp.area());
sp=new circle(10);
System.out.println("sp.area="+sp.area());
}
}
Difference between abstract class and Interface
S.No.
Abstract class
1.
Contains abstract and non-abstracts methods
2.
Contains instance fields
3.
Members can be public, private ,protected or
default
4.
A Java abstract class should be extended using
keyword extends.
5.
An abstract class can extend another Java class
and implement multiple Java interfaces
6.
Cannot instantiate.
7
Can only be used to derive.

Object class

Interface
Contains only abstract methods
Contains static final fields
Members are public
interface should be implemented using
keyword implements;
An interface can extend another
interface only
Cannot instantiate.
Can only be used to derive.

is in java.lang package
is a super class of all other classes
every class in java extends Object class, if no superclass is explicitly given
e.g.,
class emp
{
int a=10;
after compilation
public static void main(String arg[])
{
Object obj=new emp();
} //legal, Object class is superclass of all classes
}
class emp extends Object
{
int a=10;
public static void main(String arg[])
{
Object obj=new emp();
}
}

Note: In java only primitive types are not object. All array types, whether they are
arrays of objects or arrays of primitive types are class types that extend the Object
class
e.g.,
obj e[]=new emp[3];
obj= new int[10];

Methods in Object class


1. equals method
uses the identity comparison operator(==) to test if two objects are identical(means,
checks two objects shares the same address in memory)
source code of Object class equals method
public boolean equals(Object obj)
{
return(this==obj);
}
To test whether two objects are equal in the sense of equivalency(i.e., contains same
information) equals method must be overridden .
Rules to override equals method in our class
1. Do this check : if yes then return true
2. Do Null check : if yes then return false
3. Check objects belongs to same class or not by using
Obj.getClass() != this.getClass();
return false if objects are not of same class
4. Type cast the object
5. Compare individual attribute starting with numeric attribute
e..g,
public class equalsdemo
{
int a;
equalsdemo(int a)
{ this.a=a;}
/*Overriding equals() method of Object class to compare two objects contains same
information*/
public boolean equals(Object o)
{
// both object share same memory address
if (o == this)
return true;
// check explicitly passed object is null
if((o == null)
return false;
//check both object belongs to same class
if (o.getClass() != this.getClass()))

Output
checks two objects contain same information :true
checks two objects contain same information :false

return false
// typecast o to equalsdemo so that we can compare data members
equalsdemo c = (equalsdemo) o;
// Compare the data members and return accordingly
return this.a==c.a;
}
public static void main(String[] args)
{
equalsdemo o1=new equalsdemo(10);
equalsdemo o2=new equalsdemo(10);
equalsdemo o3=new equalsdemo(40);
System.out.println(checks two objects contain same information : +
o1.equals(o2));
System.out.println(checks two objects contain same information : +
o1.equals(o3));
}
}
2.
toString method
used when we need a string representation of an object
if x is an object and call to System.out.println(x) internally calls x.toString().
Output of this is packagename.classname@hexaversion of hashcode
e.g.,
class Apple
{
int a=10;
public static void main(String ar[])
{
Apple a1=new Apple();
System.out.println(a1);//
}
}
Output[note: packagename is not displayed bcose no package name is specified]
Apple@1ad086a
class name hexaversion of hashcode
We can override toString() method in our class. The format of output to be return by
overridden toString() is
name of the class[+variables list +]
class emp
{
Output
int rno=101;
emp[roll number : 101]
public String toString()
{ return this.getClass().getSimpleName() +[ roll number : + rno+] }
public static void main(String ar[])

{
emp a1=new emp();
System.out.println(a1.toString);
}
}
Superclass toString() method can be called by using
super.toString();
3.
hashcode method
returns an integer value that is derived from an object memory address
syntax
public int hashcode();

OBJECT CLONING
In Java, when you assign an object to another variable, only the memory address of
the object is copied and hence any changes in the original object will be reflected
in the new variable.
e.g.,
MainObject obj1 = new MainObject();
obj2 = obj2;
In the above example any changes you make to obj1 will reflect in obj2 and
vice versa.
if you dont want the change made in obj2 to be seen in obj1 or any change
made in obj1 to be seen in obj2, then we go for a concept called as cloning.
Defn:
cloning means creating(i.e., duplicate) a copy of the object
Object Cloning is implemented using the interface called Cloneable
The other name for Cloneable interface is tagging interface or maker interface
The Cloneable interface defines no members. It is used to indicate that a class
allows a bitwise copy of an object (that is, a clone) to be made.
implementing this interface helps to call clone() method

clone() method

syntax of clone() method in Object Class


protected Object clone() throws CloneNotSupportedException

creates new object that is same as the invoking object


class that does not implement Cloneable interface, when calls clone() method
a CloneNotSupportedException is thrown.
When a clone is made, the constructor for the object being cloned is not
called
clone() is declared as protected inside Object

if this method is explicitly overridden by our class it is declared as public


cloning cause unintended side effects
Cloning can be divided into two types.
1. Shallow Copy cloning
By default any clone() method gives shallow copy of the object i.e. if we
invoke super. clone()
Shallow copy is a bit-wise copy of an object.
New object has an exact copy of the values in the original object.
if the field which is to be copied is a primitive type, then the value is copied
else if the field which is to be copied is a memory address (or an object
itself) then the address is copied.
Pictorial representation for shallow copy based on the example program
d object
x1 object

x2 object

2. Deep Copy cloning


A deep copy copies all fields, and makes copies of dynamically allocated
memory pointed to by the fields.(i.e., an object is copied along with the
objects to which it refers.)
Pictorial representation for deep copy based on the example program
d object

x1 object

d object

x2 object

Example program that explains two types of cloning


import java.util.Date;
class TestClone implements Cloneable
{
int a;
Date d;
Deep cloning
TestClone()
{
x1:a=10,x1:date=6
a=10;
x2:a=10,x2:date=6
d=new Date();
}
x1:a=40,x1:date=20
void setdate()
x2:a=10,x2:date=6

Output
Shallow copy
x1:a=10,x1:date=6
x2:a=10,x2:date=6
x1:a=40,x1:date=20
x2:a=10,x2:date=20

d.setDate(20); }

public Object cloneTest()


{
try
{
TestClone t=(TestClone)super.clone();
t.d = (Date)d.clone();
return t;
} catch(CloneNotSupportedException e)
{
System.out.println("Cloning not allowed.");
return this;
}

Shallow copy

Deep cloning

}
}
public class Clonedemo
{
public static void main(String[] args)
{
TestClone x1 = new TestClone();
TestClone x2;
x2 =(TestClone) x1.cloneTest();
System.out.println("x1:a=" + x1.a +",x1:date=" + x1.d.getDate());
System.out.println("x2:a=" + x2.a +",x2:date=" + x2.d.getDate());
x1.a=40;
x1.setdate();
System.out.println("x1:a=" + x1.a +",x1:date=" +x1.d.getDate());
System.out.println("x2:a=" + x2.a +",x2:date=" + x2.d.getDate());
}
}

INNER CLASSES
A class defined inside another class

E..g,
class X
{
int i,j;
class Y
{
int q,w;
}
}
Reasons for inner class

A inner class methods can access all the members of its enclosing / outer class,
including private members
Inner classes can be hidden from other classes in the same package

An inner class can be classified into


1. Static inner class
2. Non-static inner class
3. Local inner class
4. Anonymous inner class
1. Non-static inner class
An inner class is associated with an instance of its enclosing class and has direct
access to that object's methods and fields. (i.e.,the nested class can access outer
class members directly (i.e., without creating instance for the outer class))
Since an inner class is associated with an instance, it cannot define any static members
itself.
Objects that are instances of an inner class exist within an instance of the outer class.
To instantiate an inner class, you must first instantiate the outer class. Then, create the
inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Consider the following classes:

class Outer {
int outer_x = 100;
void test()
{

/*Accessing non-static nested class from outer class by creating


instance inner */

Inner inner = new Inner();


inner.display();
/*Accessing outclass members from non-static inner
}
class.
// this is an innner class
- the nested class can access outer class members
class Inner {
directly e.g., Inner access outer_x directly */
int y=10;
void display() {
System.out.println("display: outer_x = " + outer_x+", y="+y);
}
}
//ERROR Y CANNOT BE ACCESSIBLE FROM ENCLOSING CLASS OUTER
/* public void showY() {
System.out.println("inner:y="+y);
}*/
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
Creating object for non-static inner class outside
Outer.Inner inner=outer.new Inner();
the class
inner.display();
}
}
Output : display: outer_x = 100, y=10

2. Static inner class


which has static modifier applied
because it is static, it must access members of its enclosing class only through an
object reference(i..e, it cannot refer outerclass members directly)
Syntax to create an object for the static nested class from a program
OuterClass.StaticNestedClass nestedObject
OuterClass.StaticNestedClass( );

new

class outclass // outer class


{
private int a =10;
void display() //
{
a++;
sinclass in=new sinclass();
in.write();
System.out.println("printing static nested class variable : "+in.y);
}
/*Accessing outclass members from static inner
// static nested class
class
static class sinclass
- if the nested class is static, the nested class has
{
to create instance for the outer class to access
private int y=20;
outer class members*/
void write()
{
outclass o1=new outclass();
System.out.println("Accessing outerclass variable when the nested
class is static :" +o1.a);
}
}
}
class statiinnerdemo
{
public static void main(String args[])
{
// outclass o = new outclass();
outclass.sinclass sinc=new outclass.sinclass();
sinc.write();
}
}
3. Local inner class
A class that is created inside a method is known as local inner class.
Local inner classes does not have access specifier because the scope of this class
is restricted to the block in which they are declared.
If you want to invoke the methods of local inner class, you must instantiate this
class inside the method.(i.e., Local inner class cannot be invoked from outside the
method).
They can access the fields of their outerclass, but they cannot use local
variables of the method where they have been defined. To use local variables of
method, that variable must be declared final.

Advantage is they are completely hidden from the outside world


E.g.,
class Global
{
int x = 100;
void createLocal()
{
int y=101;// not possible because it is not final
final int z=102;
Local class defined inside the method createLocal
class Local
Can access outerclass variable i.e., x
{
Can access local class variable i.e., a
int a=104;
Can access local variable of method if it is final ie., z
void display()
Cannot access local variable of a method if it is not final i.e., y
{
System.out.println("Variable of Global class x = " + x);
System.out.println("Variable of Local class y= " + a);
System.out.println("Variable of createLocal method which is final "+ z );
//compile time error
//System.out.println("Variable of createLocal method which is not final " +
y);
}
}
Local inner = new Local(); // object of local inner class within createLocal
method
inner.display();
}
}
class Localinnerclass {
public static void main(String args[]) {
Global g = new Global();
g.createLocal();
}
}
Output
Variable of Global class x = 100
Variable of Local class y= 104
Variable of createLocal method which is final 102
4. Anonymous Inner class
inner class within the body of a method without name. These classes are known as
anonymous inner class.
helps to create the object the interface or abstract class.
want to make only a single object of this class.
Syntax to create object
new superType(construction parameter)
{
inner class methods and data
}
where superType can be interface or abstract class

anonymous inner class cannot have constructor because, the name of the
constructor must be the same as the name of the class, and the class has no
name.
the construction parameters are given to the superclass constructor.
When the inner class implements an interface, it cannot have any construction
parameters, however supply a set of parentheses as
new interfaceType()
{
methods and data
}
E.g., Java Anonymous Inner Class of a abstract Class Type
abstract class shape
{
abstract void area();
}
class anonymousclass
{
void canonyclass()
{
shape s=new shape()// start of anonymous class
{
void area()
{
System.out.println("anonymous class create using object of abstract class");
}
}; // end of an anonymous class
s.area();
}
}
public class aicctype
{
public static void main(String args[])
{
anonymousclass ac=new anonymousclass();
ac.canonyclass();
}
}
Output : anonymous class create using object of abstract class
E.g., Java Anonymous Inner Class of a Interface Type
interface shape
{
abstract void area();
}
public class aicctype
{
public static void main(String args[])
{
shape s=new shape()// start of anonymous class
{

public void area()


{
System.out.println("anonymous class create using object of
interface");
}
}; // end of an anonymous class
s.area();
}
}
Output : anonymous class create using object of interface
e.g.,3 Java Anonymous Inner Class in Method Arguments
//abstract class shape
interface shape
{
abstract void area();
}
class amethodarg
{
void area1(shape s)
{
s.area();
}
}
public class aicctype
{
public static void main(String args[])
{
amethodarg am=new amethodarg();
am.area1(new shape()
// start of anonymous class
{
public void area()
{
System.out.println("anonymous class object used as parameter in
method");
}
}); // end of an anonymous class
}
}
Output : anonymous class object used as parameter in method

REFLECTION
Program that analyzes the capabilities of classes during runtime is called as
reflection.
or
Reflection in Java is the ability to examine and/or modify the properties or behavior
of an object at run-time.

java.lang.reflect package is used to implement reflection in Java, since it contains all


the necessary classes for implementing reflection.

The Class class


When program is running, the java runtime system always maintains runtime type
identification on all objects.(keep tracks of class to which each object belongs).
Runtime type information is used by the virtual machine to select the correct
methods to execute.
The Class class is also used to access information about objects.
Methods to get information about objects are
1. getClass() method of Object class
It returns the instance of Class class.
It should be used if you know the type.
Moreover, it can be used with primitives.
e.g,
package reflection;
class Reflection
{
public static void main(String args[]){
Reflection t=new Reflection();
packagename
Class c=t.getClass();
System.out.println(c); // class reflection.Reflection
Class name
System.out.println(c.getName());//reflection.Reflection
System.out.println(int.class.getName());//int
}
}
2. forName() Method of Class class
is used to load the class dynamically.
returns the instance of Class class.
It should be used if you know the fully qualified name of class
This cannot be used for primitive types.
Syntax
public static Class<?> forName(String className) throws ClassNotFoundException

E.g.,
package reflection;
public class forname {
public static void main(String[] args) {
try {
// returns the Class object for the class with the specified name
Class cls = Class.forName("reflection.forname");
// returns the name and package of the class
System.out.println("Class found = " + cls.getName());
System.out.println("Package = " + cls.getPackage()); Output
}
if class name is found
catch(ClassNotFoundException ex) {
Class found = reflection.forname
System.out.println(ex.toString());
Package = package reflection
}
If class name not found(assume input is
}
reflection.java)
}
java.lang.ClassNotFoundException:
reflection.java

3. newInstance() method
Is in Class class and Constructor class
used to create a new instance of the class.
The newInstance() method of Class class can invoke zero-argument constructor
whereas newInstance() method of Constructor class can invoke any number of
arguments. So Constructor class is preferred over Class class.
Syntax of newInstance() method of Class class
public T newInstance()throws InstantiationException,IllegalAccessException
Here T is the generic version. You can think it like Object class.
e.g.,
package reflection;
class Test
{
void message()
{ System.out.println("called using object created dynamically"); }
public static void main(String args[])
{
try
{
Class c=Class.forName("reflection.Test");
Output
Test s=(Test)c.newInstance();
called using object created dynamically
s.message();
}catch(Exception e){System.out.println(e);}
}
}
Using reflection to analyze the capabilities of classes
Java.lang.reflect package used three classes Field,Method,Constructor to analyze the
capacbilities of class.
S.N.
1

3
4.

Method & Description


java.lang.Class
Field[] getFields() , Field[] getDeclaredFields()
getFields() returns an array of Field objects for all the fields declared by the
class or interface represented by this object.
getDeclaredFields() method returns an array containing Field objects for the
public fields of the class/superclass/ interface represented by this Class object.
Note: These two methods return an array of length 0, it there is no fieds.
Method[] getMethods() .Method[] getDeclaredMethods()
This method returns an array of Method objects
getMethods() return public methods of class/inheritedclass.
getDeclaredMethods() returns all methods of this class/interface but not
inherited class
Constructor[] getConstructors(), Constructor getDeclaredConstructors()
Returns an array containing constructor objects.
public int getModifiers()

5.
6.

returns the integer representing the modifiers for this class.


Class[] getParameterTypes()
Returns an array of Class objects that represents the types of parameters in
constructors and methods
Class getReturnType()
Return a Class object that represents the return type

e.g., refer classnote book

PROXIES
are used to create a new classes at runtime that implements the desired interfaces.
are also necessary when the user dont know at compile time which interfaces need
to implement.
Proxy class has two types of methods
The methods specified by the interface
Methods defined in the Object class
New code for the above said method cannot be written at runtime,instead supply an
invocation handler
Invocation handler is an object of any class that implements the InvocatinHandler
interface
This interface has a single method
Object invoke(Object proxy, Method method, Object[] args)
This method is called on the proxy object. For creating proxy object use
newProxyInstance method of Proxy class
public static Object newProxyInstance(ClassLoader loader,Class<?>[]
interfaces, InvocationHandler h)
whenever particular method is called on proxy object, the invocation handler
invokes the invoke method with the object of the method being invoked.It is the
invocation handler who directs how to handle the call for a method at run time

UNIT-III
GRAPHICS PROGRAMMING
Java contains two libraries for graphics programming
1. AWT
2. SWING
1. Abstract Window ToolKit(AWT)
is a concept designed for building simple GUIs in Java applications
introduced in java1.0
java.awt package consists of java awt classes which deals with user interface
elements(example button, textbox, menu etc) .
2. Swing
Java Swing is a lightweight Java graphical user interface (GUI) toolkit
is an extension of java1.1
is a part of the Java Foundation Classes (JFC) and includes several packages for
developing rich desktop applications in Java.
Swing includes built-in controls such as buttons, sliders, toolbars, tables, and text
Swing components are written entirely in Java and thus are platform-independent.
Difference between AWT and SWING
S.No.
1.
2.
3.

AWT

Swing
Swing is also called as JFCs (Java Foundation
stands for Abstract windows toolkit.
classes).
AWT components require java.awt Swing components require javax.swing
package.
package.
Swings are called light weight component
AWT components are called Heavyweight
because swing components sits on the top of
component.
AWT components and do the work.

4.
5.

AWT components are platform dependent.


Look and feel in not there

Swing components are made in purely java


and they are platform independent.
can have different look and feel in Swing.

Frame

is a top-level window with a title and a border.


The AWT library has a class called as Frame.
The swing version is JFrame which extends Frame.
Steps to create a Frame(2 marks)
//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");
//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3. Create components and put them in the frame.
//...create emptyLabel...
frame. add(emptyLabel, BorderLayout.CENTER);
//4. Size the frame.
frame.pack();
//5. Show it.
frame.setVisible(true);

S.No.
1.

Constructors
JFrame()

2.

JFrame(String title)

Description
Creates new instance of frame which is
invisible initially
Creates new instance of frame which is
invisible initially with title

Methods
1.
2.
3.

void setTitle(String title)


void setSize(int w,int h)
void setDefaultCloseOperation(int op)

4.

void setVisbile(boolean value)


Object

Sets the title of the frame


Resizes the frame.
Close the frame when close button is pressed.
Operation
EXIT_ON_CLOSE, HIDE_ON_CLOSE
Sets the frame visible.(because, frame starts
their life invisible)

Positioning a Frame
Methods that resize the frames
1. void setLocation(int w,Component
int h) =>moves the component to the new location
2 .void setBounds(int x, int y, int w, int h)=>moves and resizes this component.
3. void setIconImage(Image image) => An icon image appears on the title bar at the
corner
Container

Inheritance hierarchy for the frame and component classes in AWT and
SWING
JComponent

Window

JPanel

Frame
JFrame

Working with 2D shapes


Java has the ability to draw various graphical shapes.
In java1.0 we use Graphics class
has methods to draw lines, rectangles, ellipses.
drawing operations are very limited.
- E.g., cannot show line thickness, cannot rotate shapes.
Java2D library (Graphics2D class)
is in java 1.2
which implements a set of graphical operations.
to draw shapes obtain objects of Graphics2D class.
Graphics2D class is subclass of Graphics class
Organizes geometric shapes in an object oriented fashion
A graphics object is passed to paintComponent() method which is in
JComponent class
Syntax
public void paintComponent(Graphics g)
e.g., to draw lines, rectangles, ellipse there are classes such as
Line2D, Rectangle2D, Ellipse2D
These classes implements Shape interface
To draw shapes call draw() method of the Graphics2D class
Java2D shapes use floating point coordinates(java1.0 draw method uses integer
coordinates)

Inheritance diagram of shape classes


Shape

Line2D

Ellipse2D

Rectangular
Shape

Rectangle2D
Rectangle

Constructors and Methods


Constructors
Syntax of constructors

Class Name
Rectangle2D.Double

Rectangle2D.Double(double x, double
y, double w, double h)

Rectangle2D.Float

Rectangle2D.Float(float x, float y, float


w, float h)

Ellipse2D.Double

Ellipse2D.Double(double x, double y,
double w, double h)

Line2D.Double
Class name

RectanglerShape

Line2D.Double(double x1, double y1,


double x2, double y2)
Methods
Syntax
double getCenterX() , double getCenterY()
double getMinX() ,double getMinY()
double getMaxX(), double getMaxY()
double getWidth(), double getHeight()
double getX(), double getY()

Description
Defines rectangle with given
top-left corner, width and height
double coordinates
Defines rectangle with given
top-left corner, width and height
float coordinates
Creates a Ellipse2D with a size
of (Width, Height) at location
(X, Y).
Creates a Line2D from (X1, Y1)
to (X2, Y2).
Description
Determines center, minimum,
maximum, X or Y value
Determines the width or height
of the enclosing rectangle
Returns the X or Y coordinate
of the top-left corner of the
enclosing rectangle

Program that implements 2D shapes


import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
class drawcomponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
g2.drawString("Implementing 2D Shapes ",100,10);
Rectangle2D r=new Rectangle2D.Double(100,100,100,75);
Output
g2.draw(r);
Rectangle2D r1=new Rectangle2D.Double(135,125,25,50);
g2.draw(r1);
Line2D l=new Line2D.Double(100,100,150,65);
g2.draw(l);
Line2D l2=new Line2D.Double(200,100,150,65);
g2.draw(l2);
Ellipse2D c=new Ellipse2D.Double(145,85,10,10); // draws circle

g2.draw(c);
}
}
public class SizeFrame
{
public static void main(String[] args)
{
JFrame frame=new JFrame("Implementing Shapes");
frame.add(new drawcomponent());
frame.setSize(500,500);
frame.setVisible(true);
}
}

Using Colors

Painting is the process of filling the interior of the shape with a color, color
gradient, or texture.
Stroking is the process of drawing the shape's outline. You can draw an outline
using different line widths, line styles, and colors.
Painting
Filling the interior of a shape is a two-step process:
1. First, call a setPaint() which is in Graphics2D class . This method accepts any
object that implements the java.awt.Paint interface
2. Then call fill() method in Graphics2D class.
Paints are immutable, which means they can't be modified after they are created.
There are three types of painting supported by the 2D API. The figure contains
three shapes:
The ellipse is filled with a solid color.
The rounded rectangle is filled with a color gradient.
The gradient color is combination of more than one colors to design graphics.
Object with the gradient color looks like a 3-D component.
The object colored with gradient color makes it more attractive.
The arc is filled with a texture
Filling the shapes with image
Three shapes and three paints

Colors can be defined with Color class.


Java.awt.Color class offers 13 predefined constants. E.g., Color.BLACK,
Color. BLUE
Can specif a custom color by creating a Color object by its red,green and
blue components using a scale of 0-255
e.g., for setting custom color
g2.setPaint(new Color(0,0,255));//blue color
g2.drawString("Implementing 2D Shapes ",100,10);

Constructors and Methods

Class
java.awt.Color
java.awt.Graphics
java.awt.Graphics2D

Syntax
Color(int r, int g, int b)
void setColor()
void fill(Shape s)

Description
Creates a color object
Sets the current color
Fills the shape with the current point

java.awt.Component

void setBackground(Color c)

Sets the background color

void setForeground(Color c)

Sets the foreground color

WORKING WITH FONT OBJECT


The AWT supports multiple type fonts. Beginning with Java 2, fonts have a family
name, and a face name.
The family name is the general name of the font, such as Courier, Helvetica.
The face name composed of family name such as Helvetica and optional suffix
such a Bold. E.g.: Courier Italic, Arial Narrow, Helvetica Bold.
The Font class defines these variables:
Variable
Meaning
String name;
It stores the name of the font
int size;
It stores size of the font in points
int style
It stores style of the font. The possible values are: Font.PLAIN,
Font.BOLD, Font.ITALIC, and Font.BOLD+ Font.ITALIC
Constructors of Font class
Font(String fontFace, int style, int size);
Arguments fontFace represents name of the font, style has possible values:
Font.PLAIN, Font.BOLD, Font.ITALIC, and Font.BOLD+ Font.ITALIC, and
size determine text size in points
e.g.: Font f=new Font(Arial Bold,Font.BOLD+Font.ITALIC, 36);

To use a font that you have created, you must select it using setFont(), which
is defined by Component. General form is
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font

e.g.:

g2.setFont(f);
g2.drawString( Font Example ,100,150);
The Font class has rich collection of methods. They are listed below:

Method
String getFamily();
String getName();
String getFontName();
int getStyle();
int getSize();
boolean isPlain();
boolean isBold();

Meaning
Return the name of the font family. For example f.getFamily( )
will return Arial
Both return the name of the font face. For example f.getFamily( )
will return Arial Black
Return integer value that represent style of the font. The possible
values are 0(Font.PLAIN),1(Font.BOLD),2(Font.ITALIC), or
3(Font.BOLD+Font.ITALIC).
Return the size of the current Font object
When style of the invoking Font object is Font.PLAIN, it return
true, otherwise return false
if style of the invoking Font object is Font.BOLD, it return true,

boolean isItalic();

otherwise return false


When style of the invoking Font object is Font.ITALIC, it return
true, otherwise return false

Determining the Available Fonts


To obtain list of font in the current underlying operating system, call the
getAvailableFontFamilyNames() method defined by the GraphicsEnvironment
class.
Syntax is
String[] getAvailableFontFamilyNames()
returns an array of strings that contains the names of the available font families.
e.g.,
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String fnames[]=ge.getAvailableFontFamilyNames();
for(String f:fnames)
System.out.printf("\n%s",f);
There is one more method called
getAllFonts( ) is defined by the
GraphicsEnvironment class to get font name
Syntax
Font[ ] getAllFonts( )
returns an array of Font objects for all of the available fonts.
E.g.,
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font fnames[]=ge.getAllFonts();
for(Font f:fnames)
System.out.printf("\n%s",f.getFontName() );
GraphicsEnvironment reference created using getLocalGraphicsEnvironment()
method, which is defined in GraphicsEnvironment.
Syntax is
static GraphicsEnvironment getLocalGraphicsEnvironment( )
Example(Note : it is a university practical program)
import javax.swing.*;
import java.awt.*;
class text extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g1=(Graphics2D)g;
Font f=new Font("Arial Bold",Font.BOLD+Font.ITALIC, 14);
g1.setFont(f); Color c=new Color(0,0,255);
Output
g1.setPaint(c);
g1.drawString("Text in Arial Bold",100,100);
Font f1=new Font("Verdana Italic",Font.PLAIN, 14);
g1.setFont(f1);

g1.setPaint(Color.pink);
g1.drawString("Text in Verdana Italic",100,200);
Font f2=new Font("Vrinda Bold",Font.ITALIC, 14);
g1.setFont(f);
g1.setPaint(Color.orange);
g1.drawString("Text in Vrinda Bold",100,300);
}
}
public class Disptextwithstyle {
public static void main(String[] args) {
JFrame f=new JFrame("different textshapes with different ");
f.setSize(200,200);
f.add(new text());
f.setVisible(true);
}
}

DISPLAYING IMAGES

Complex Images such as potograhps can be displayed using Graphics Object.


To read Image from the local file , the syntax is
Image img=ImageIO.read(new File(filename));
e.g.,
Image image=ImageIO.read(new File("E:/sathiya/java/blue.jpg"));
to display the image, drawImage() method of Graphics Class is used
Syntax is
boolean drawImage(Image imgob, int left, int top, int width, int height,
ImageObserver imgob)
where
img is your image object,
x and y represent the position to draw the top-left corner of the image.
imgob is an object that implements the ImageObserver interface. Simply
specify this.
The drawImage returns a false value if the image has not yet been completely
loaded and then returns true when the image has finally loaded.
e.g.,
g.drawImage(image,100,100,50 ,50,this) ;
Copying an area: the image displayed can be copied to another part of the screen..
The copyArea() method in a Graphics method can be used for this and the syntax
is:
copyArea(x, y, w, h, x-displacement, y-displacement)
Where the arguments are:
x is the x-coordinate of the area to be copied.
y is the y-coordinate of the area to be copied.
w is the width of the area to be copied.
h is the height of the area to be copied.
x-displacement is the horizontal displacement of the area to be copied.
y-displacement is the vertical displacement of the area to be copied.
Example

import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;

Output

class Imageprg extends JComponent


{
private Image image;
Imageprg() throws Exception
{
image=ImageIO.read(new File("d:/rose.jpg"));
}
public void paintComponent(Graphics g)
{
g.drawImage(image,10,10,100,100,this);
g.copyArea(30, 30, 50, 70, 80, 120);// copies some portion to the new location
}
public static void main(String[] args)throws Exception
{
JFrame frame = new JFrame("Implementing Images");
frame.add(new Imageprg());
frame.setIconImage(ImageIO.read(new File("d:/rose.jpg")));
frame.setSize(500,500);
frame.setVisible(true);
}
}

BASICS OF EVENT HANDLING


Window-based programs require an event-driven model which works under Eventdelegation model.

The Event Delegation Model

Java handles events, based on the delegation event model, which says how events are
generated and processed. Its concept is
1. A source generates an event and sends it to one or more listeners.
2. then, the listener simply waits until it receives an event
3. Once received, the listener processes the event and then returns

Events
An event is an object that describes a state change in a source.
E.g., pressing a button , entering a character via the keyboard, clicking the
mouse
The event handling involves four types of classes.
1. Event Sources
2. Event Classes
3. Event Listeners
4. Event Adapters
1. Event Sources
Event sources are components, subclasses of java.awt.Component, capable to
generate events. The event source can be a button, TextField or a Frame etc.

To process an event generated by the source, it must be registered with some


listener. Each type of event has its own registration method. Here is the general
form
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
example, the method that registers a keyboard event listener is called
addKeyListener( ). The method that registers a mouse motion listener is called
addMouseMotionListener( ).
2. Event classes
Source generates an event and is named by some Java class.
For example, the event generated by button is known as ActionEvent and that of
Checkbox is known as ItemEvent.
All the events are listed in java.awt.event package.
3. Event Listeners
The events generated by components are handled by a special group of interfaces
known as "listeners".
It has two major requirements.
1. First, it must be registered with one or more sources to receive events.
2. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found
in java.awt.event.
For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved.

Pictorial representation relationship between event source and listeners


Event
source

4. Event Adapters

1...*

Event
<<set of one or more>> listener
<<implementation>
>
Listener
interface

When a listener includes many abstract methods to override, the coding becomes
heavy to the programmer.
For example, to close the frame, you override seven abstract methods of
WindowListener, in which, in fact you are using only one method.
To avoid this heavy coding, the designers come with another group of classes
known as "adapters".
Adapters are abstract classes defined in java.awt.event package.
Every listener that has more than one abstract method has got a corresponding
adapter class.
The inheritance diagram of AWT event Classes

Semantic and Low-Level Events(2 marks)


Events are classified into two types
1. Low-Level Events
The events generated by hardware components (like MouseEvent and KeyEvent)
are known as low-level events
Five low-level event classes are commonly used:
o KeyEvent (a key was pressed or released)
o MouseEvent (the mouse button was pressed, released, moved, or dragged)
o MouseWheelEvent (the mouse wheel was rotated)
o FocusEvent (a component got focus or lost focus)
o WindowEvent (the window state changed)
2. Semantic Events
The events generated by software components (like Button, List) are known as
semantic events.
E.g.,
o ActionEvent ( button click, menu selection, selecting a list item, or ENTER
typed in a text field)
o AdjustmentEvent (the user adjusted a scrollbar)
o ItemEvent (the user made a selection from a set of checkbox or list items)
Summary of Event Handling
Event Class

Listener Interface

ActionEvent

ActionListener

Listener Methods
actionPerformed()

Event
Gene
getActionCommand() JTextF
JButto
getModifiers()
JCom
Class methods

adjustmentValueChanged()
AdjustmentEvent AdjustmentListener
ItemEvent

ItemListener

itemStateChanged()

KeyEvent

KeyListener

keyPressed(),keyReleased()
keyTyped()
mouseClicked()
mouseEntered()
mouseExited()
mousePressed()
mouseReleased()
mouseDragged()
mouseMoved()
windowActivated()
windowClosed()
windowClosing()
windowDeactivated()
windowDeiconified()
windowIconified()
windowOpened()

MouseListener
MouseEvent
MouseMotionListener
WindowEvent
WindowListener

getAdjustable()
getAdjustmentType()
getValue()
getItem()
getItmeSelectable()
getStateChanged()
getKeyChar()
getKeyCode()
getKeyText()
getX(),getY()
getPoint()

public void actionPerformed(ActionEvent e) {


int r = (int) (Math.random()* 3);
l.setText(s[r]);
}

JCom

Comp

Comp

Comp

getWindow()

Program that implements Event Handling(practical program)


import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Displaygreetings extends JFrame implements ActionListener {
String s[] = {"Welcome", "Thank You", "Good Evening", "Good Afternoon"};
JLabel l
JButton b;
public Displaygreetings() {
Output
setTitle("Random Greetings");
setSize(200, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(new FlowLayout());
l = new JLabel("Click Button to change the greeting");
add(l);
b= new JButton("Change Greeting");
b.addActionListener(this);
add(b);
}

JScro

Wind

public static void main(String args[]) {


new Displaygreetings();
}
}

ADAPTER CLASSES

Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface.
An adapter class provides an empty implementation of all methods in an event
listener interface.
E.g. Suppose you want to use WindowClosing Event or method from
WindowListener, if you do not use adapter class then unnecessarily you have to
define all other methods from WindowListener such as windowActivated(),
windowClosed(),
windowClosing(),
windowDeactivated(),
windowDeiconified(), windowIconified(), windowOpened() .
The table shows adapter classes in java.awt.event and corresponding interface .
Adapter Class
Listener Interface
ComponentAdapter
ComponentListener
ContainerAdapter
ContainerListener
FocusAdapter
FocusListener
KeyAdapter
KeyListener
MouseAdapter
MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter
WindowListener
Adapter Class is explained using WindowListener interface. Methods in
WindowListener are
Method

Description

public void windowActivated(WindowEvent e)

is called after the window has been opened

public void windowClosed(WindowEvent e)

Invoked when a window has been closed

public void windowClosing(WindowEvent e)

is called after the window has been closed

public void windowDeactivated(WindowEvent e)

Invoked when a window is no longer the user's


active window,

public void windowDeiconified(WindowEvent e)

Invoked when a window is changed from a


minimized to a normal state.

public void windowIconified(WindowEvent e)

Invoked when a window is changed from a


normal to a minimized state.

public void windowOpened(WindowEvent e)

Invoked the first time a window is made visible.

E.g.,1 Program with WindowListener using Anonymous Inner Class


package windolistener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Windolistener

{
public static void main(String args[])
{
JFrame j = new JFrame("Implementing window Listener");
// implementing Anonymous Inner class
j.addWindowListener(new WindowListener()
{
// override all 7 abstract methods
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e)
{
System.out.println("Window closed ");
System.exit(0);
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}
); // closing inner class
j.setSize(300,300);
j.setVisible(true);
}}
E.g., 2 Program with WindowAdapter using Anonymous Inner Class
package windoadpater;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Windoadpater
{
public static void main(String args[])
{
JFrame j = new JFrame("Implementing windowAdapter ");
// implementing Anonymous Inner class
j.addWindowListener(new WindowAdapter()
{
// invoking only windowClosing Event
public void windowClosing(WindowEvent e)
{
System.out.println("Window closed ");
System.exit(0);
}
}
);
j.setSize(300,300);
j.setVisible(true);
}
}
Output(both programs generates same output)

Window closed

MOUSEEVENTS

The class which processes the MouseEvent should implement this interface.
The object of that class must be registered with a component.
The object can be registered using the addMouseListener() method.
Syntax
public interface MouseListener extends EventListener

When the user clicks the mouse button, three listener methods are called
1. mousePressed
2. mouseRelesed
3. mouseClicked
Methods of MouseListener Interface
S.N.
Method & Description
void mouseClicked(MouseEvent e)
1
Invoked when the mouse button has been clicked (pressed and released) on a
component.
void mouseEntered(MouseEvent e)
2
Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)
3
Invoked when the mouse exits a component.
void mousePressed(MouseEvent e)
4
Invoked when a mouse button has been pressed on a component.
void mouseReleased(MouseEvent e)
5
Invoked when a mouse button has been released on a component.
To get x and y-coordinate use getX() and getY() method that belongs to
MouseEvent class.
getClickCount() method is used to identify how many mouseclicks are done.
Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Mouseevents extends JFrame implements MouseListener {
JLabel l;
Mouseevents()
{
setSize(200,200);
setVisible(true);
l=new JLabel("mouseevents");
add(l);
l.addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{

l.setText("i am Clicked") ;

public void mouseExited(MouseEvent e)


{

l.setText("i am Exited") ;

public void mouseEntered(MouseEvent e)


{

l.setText("I am Entered"); }

public void mousePressed(MouseEvent e)


{

l.setText("I am Pressed"); }

public void mouseReleased(MouseEvent e)


{

l.setText("I am Released);

public static void main(String[] args) {


new Mouseevents();
}
}

Actions
The Action interface provides a useful extension to the ActionListener
interface in cases where the same functionality may be accessed by several
controls.
An action is an object that encapsulates
A description of the command(as a text string and an optional icon)
Parameters that are necessary to carry out command
Action Interface extends ActionListener Interface. Therefore can use an Action
Object whenever ActionListener object is expected
The Action interface has the following methods
1. void actionPerformed(ActionEvent e) - performs the action corresponding to
event e
2. void setEnabled(boolean b) - this turns the action on or off
3. boolean isEnabled() - checks if the action is on
4. void putValue(String key, Object val)
store a value under a key (String type).
There are 2 standard keys: Action.NAME (name of action) and
Action.SMALL_ICON (icons for action).
E.g., Action.putValue(Action.SMALL_ICON, new ImageIcon("red.gif"));
5. Object getValue(String key) - retrieve the value stored under key
Predefined Action Table Names
Name
Value
NAME
The name of the action, displayed on buttons and menu items
SMALL_ICON
A place to store a small icon, for display in a button, menu item
SHORT_DESCRIPTION A short description of the icon, for display in a tooltip
MNEMONIC_KEY
A mnemonic abbreviation
ACCELERATOR_KEY
Short cut keys

Action is an interface. Any class implementing this interface must implement the
seven methods. Therefore for Action interface there is an equivalent class is
available. It is called as AbstractAction class
Example for AbstractAction class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class PrintHelloAction extends AbstractAction
{
private static final Icon printIcon = new ImageIcon("D:/blue.JPG");
PrintHelloAction(String name)
{
super(name, printIcon);
putValue(Action.SHORT_DESCRIPTION, "Hello, World");
}
public void actionPerformed(ActionEvent actionEvent)
{
System.out.println("Hello, World");
}
}
public class Actioninter
{
public static void main(String args[])
{
JFrame frame = new JFrame("Action Sample");
final Action printAction = new PrintHelloAction("print");
JButton b1;
Output
frame.setLayout(new FlowLayout());
frame.add(new JButton(printAction));
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
menu.add(new JMenuItem(printAction));
frame.setJMenuBar(menuBar);
JButton enableButton = new JButton("Enable");

Hello, World

ActionListener enableActionListener = new ActionListener() {


public void actionPerformed(ActionEvent actionEvent) {
printAction.setEnabled(true);
}
};
enableButton.addActionListener(enableActionListener);
JButton disableButton = new JButton("Disable");
ActionListener disableActionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
printAction.setEnabled(false);
}
};
disableButton.addActionListener(disableActionListener);

frame.add(enableButton);
frame.add(disableButton);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

SWING COMPONENTS

JLabel
It is the simplest control
Labels are passive controls that do not support any interaction with the user
Label defines the following constructors
JLabel( )
JLabel(String str)

This create blank label


creates a label that contains the string specified by str. This string is
left-justified
JLabel(String str, int
Creates a lable that contains the string specified by str using the
how)
alignment specified by how. how must be one of these three constants:
JLabel.LEFT, JLabel.RIGHT, or JLabel.CENTER
e.g: JLabel lbl=new JLabel(Name,JLabel.RIGHT);
Label has following Methods:
Method
description
int getAlignment();
Return the current alignment of the invoking label object. The
possible values are: JLabel.LEFT, JLabel.RIGHT, or
JLabel.CENTER
void setAlignment(int align); This method is used to change the alignment of the text within the
Label
String getText();
Return the text of the invoking Label object
void setText( String str);
It change the text of the invoking Label object to str

Program
import java.awt.*;
import javax.swing.*;
public class labeldemo extends JFrame {
labeldemo()
Output
{
setTitle("implementing Label") ;
setSize(200,200);
setVisible(true);
setLayout(new FlowLayout());
JLabel one = new JLabel("One",JLabel.LEFT);
JLabel two = new JLabel("Two",JLabel.CENTER);
JLabel three = new JLabel("Three",JLabel.RIGHT);
// add labels to applet window
add(one);
add(two);
add(three);
}
public static void main(String[] args) {

new labeldemo();
}
}

Using Buttons
A push button is the component that contains a label and generates events when pressed
Button defines two constructors:
JButton( )
Creates Button without label
JButton(String str)
Creates a Button with specified str as label
Button defines following methods:
Method
Description
String getLabel();
Return the label of the invoking Button object
void setLabel( String str);
It change the label of the invoking Button object to str
Handling Button events
Each time button is pressed, an action event is generated. You have to register each button
with addActionListener(ActionListener ae), so that it monitor events generated by that
button, and send notification to the method actionPerformed( ).

Example
import javax.swing.*;
public class buttondemo extends JFrame
{
buttondemo()
{
setSize(200,200);
setVisible(true);
JButton b=new JButton();
b.setLabel("Name");
add(b);
}
public static void main(String[] args)
{
new buttondemo();
}
}

Output

Text Input
Helps to read input from user and edit text
There are three categories
1.JTextField : accept only one line of text
2. JTextArea: accepts multiple lines of text
3. JPasswordField : accepts one line of text without showing the content
JTextComponent is the base class of all these three classes
1. JTextField
Constructors are
JTextField(int cols) :Constructs an empty textbox with a specified number of columns
JTextField(String text, int cols) :Constructs a textbox with an initial value and number
of columns

Methods are
int getColumns()
void setcolumns(int cols)
which is in use

: Gets or sets the number of columns for the text box

String getText( ):Used to obtain the string currently contained in the text field
void setText(String str):Used to set the text of the text filed. Here, str is the new string
boolean isEditable( ) ::If textfield is modifiable, it return true, otherwise it return false

2. JTextArea
Called as Multiline editor
Can type any number of lines using Enter key to separate them.
Each line ends with \n
Constructors are
JTextArea()
Constructs an empty textArea
JTextArea(int rows,int cols)
Constructs a textarea with rows and
JTextArea(String s,int r, int c)
Constructs the textarea with initial value
Methods are
int getRows() :it return number of visible rows in the textarea
public void setRows(int nRows) : sets number of visible rows in the textarea
public int getColumns() : it return number of visible columns equals to nRows
public void setColumns(int nCols): number of visible columns equals to nCols
void append(String str) : The append( ) method appends the string specified by str
to the end of the current text.

A textarea does not have scrollbars.


Scrollbars can be inserted using scroll pane. Scrollbars automatically appears if
more text exists , and vanish again if the text fits inside the area
3. PasswordFields
Characters entered by the user is not displayed , instead it is represented by echo
character(e.g., *)
Constructor are
1.JPasswordField(String txt, int columns)
2. JPasswordField();
Methods
1. void setEchoChar(char echo) : sets echo character
2. char[] getPassword() : returns the text contained in the password field
PROGRAM
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class text extends JFrame implements ActionListener
{
JTextField t;
JTextArea t1;
JPasswordField pass;
Output
text()
{
t=new JTextField(10);
pass=new JPasswordField(5);
pass.setEchoChar('*');
setSize(100,100);
setVisible(true);
JPanel p=new JPanel();

p.add(t);
p.add(pass);
pass.addActionListener(this);
add(p,BorderLayout.NORTH);
t1 =new JTextArea(2,20);
JScrollPane sp=new JScrollPane(t1);
add(sp,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{
t1.append("user name
:"+ t.getText() + "
}
public static void main(String[] args)
{
new text();
}

Password :"+ pass.getText());

CHOICE COMPONENTS
1. Checkboxes
A check box is a control that is used to turn an option on or off.
It consists of a small box that can either contain a check mark or not.
There is a label associated with each check box that describes what option the

box represents. You change the state of a check box by clicking on it Check
boxes can be used individually
Constructors are
1. JCheckBox(String Label) : constructs the checkbox initially unselected
2. JCheckBox(String Label,Boolean state) : constructs the checkbox with initial state
Methods are
String getLabel();
Return the label of the invoking Checkbox object
void setLabel( String str);
It change the label of the invoking Checkbox object
to str
boolean isSelected()
reterives the current state of each checkbox true/false
void setSelected(boolean state) turn the checkbox on or off.

Handling Check Boxes


Each time a check box is selected or deselected, an item event is generated
Each listener implements the ItemListener interface. Thist interface defines the
itemStateChanged( ) method.
An ltemEvent object is supplied as the argument to this method. It contains
information about the event (for example, whether it was a selection or
deselection)
Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Checkboxdemo extends JFrame implements ActionListener {
JLabel label;
JCheckBox bold, italic;
Checkboxdemo()
{

setSize(200,200);
bold = new JCheckBox("BOLD");
italic = new JCheckBox("ITALIC");
label = new JLabel("Implementation of CheckBox",JLabel.CENTER);
label.setFont(new Font("Times New Roman",Font.PLAIN,14));
JPanel p=new JPanel();
p.add(bold);
Output
p.add(italic);
add(label,BorderLayout.NORTH);
add(p,BorderLayout.CENTER);
bold.addActionListener(this);
italic.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int mode=0;
if (bold.isSelected()) mode+=Font.BOLD;
if (italic.isSelected()) mode+=Font.ITALIC;
label.setFont(new Font("Times New Roman",mode,14));
}
public static void main(String a[])
{ new Checkboxdemo(); }
}

2. RadioButtons
It is possible to create a set of mutually exclusive check boxes in which one and
only one check box in the group can be checked at any one time.
These check boxes are often called radio buttons, because they act like the station
selector buttons on a radio
Appearance of checkboxes are square and contain check mark when selected.
Radio buttons are round and contain a dot when selected
To implement radiobutton construct one object of type ButtonGroup for every
group of buttons. Then add JRadioButton object to this group.
Constructor used is
JRadioButton(String label, boolean state)

Program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Radiobuttondemo extends JFrame
{
public static void main(String[] args)
{
new Radiobuttondemo();
}
JButton b;
public Radiobuttondemo()
{
JRadioButton blue,red;
b=new JButton(new ImageIcon("d:/blue.jpg"));

Output

new JFrame("Creating a JRadioButton Component");


JPanel panel = new JPanel();
ButtonGroup buttonGroup = new ButtonGroup();
blue = new JRadioButton("blue");
buttonGroup.add(blue);
panel.add(blue);
red = new JRadioButton("red");
buttonGroup.add(red);
panel.add(red);
blue.setSelected(true);
add(panel,BorderLayout.NORTH);
add(b,BorderLayout.SOUTH);
ActionListener list = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
b.setIcon(new ImageIcon("d:/" + e.getActionCommand() + ".jpg"));
}
};
blue.addActionListener(list);
red.addActionListener(list);
setSize(400,400);
setVisible(true);
}
}

JComboBox
The class JComboBox is a component which combines a button or editable field
and a drop-down list.
It provides you options to select an item from the item list.
You can never select more than one items from a combo box.
Combo Box can be whether editable or only non-editable means only readable.
Handling Choice
Each time a choice is selected, an item event is generated.
Each listener implements the ItemListener interface.
That interface defines the itemStateChanged( ) method.
An ItemEvent object is supplied as the argument to this method.
Constructors
1. JComboBox() => creates a combo box
2. JComboBox(String
Methods
Method
Meaning
void addItem(Object item)
Adds an item to the item list
void insertItemAt(Object item,int index) Inserts an item into the given index
void removeItem(Object item)
Removes an item from the item list
void removeItemAt(int index)
Removes the item specified in the index
void removeAllItem()
Removes all items from the item list

Object getSelectedItem()

Returns the currently selected item

Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class comboboxdemo extends JFrame{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
comboboxdemo b = new comboboxdemo();
}
public comboboxdemo(){
String course[] = {"CSE","IT","ECE","EEE"};
JPanel panel = new JPanel();
combo = new JComboBox(course);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
setSize(200,200);
setVisible(true);
}}

Output

JSliders
Sliders offer a choice from a continuum of values, for example any number
between 1 and 100.
Constructors
JSlider(): creates a slider with the initial value of 50 and range of 0 to 100.
JSlider(int orientation): creates a slider with the specified orientation set by
either JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and
initial value 50.
JSlider(int min, int max): creates a horizontal slider using the given min and
max.
JSlider(int min, int max, int value): creates a horizontal slider using the given
min, max and value.
JSlider(int orientation, int min, int max, int value): creates a slider using the
given Methods to decorate sliders
Methods
1) public void setMinorTickSpacing(int n): sets the minor tick spacing to the slider.
2) public void setMajorTickSpacing(int n): sets the major tick spacing to the slider.
3) public void setPaintTicks(boolean b): used to determine whether tick marks are
painted.

4) public void setPaintLabels(boolean b): is used to determine whether labels are


painted.
5) public void setPaintTracks(boolean b): is used to determine whether track is
painted.
6) public void setSnapToTicks(boolean b) : once finished dragging a slider in snap
mode it is immediately moved to the closest tick
Program
import javax.swing.*;
class slider extends JFrame{
public slider() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 25);
slider.setMinorTickSpacing(10);
slider.setMajorTickSpacing(20);
Output
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setSnapToTicks(true);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) {
slider frame=new slider();
frame.pack();
frame.setVisible(true);
}
}

INTRODUCTION TO LAYOUT MANAGERS


A layout manager automatically arranges your controls with in a window by using
some type of algorithm
Or
Layout manager determines the positions and size of the components in the
container
Each Container has a default layout manager . E.g., for Panel default layout is
FlowLayout , for JFrame it is BorderLayout
We can set our won layout for container by using setLayout( ) method.
Syntax
void setLayout(LayoutManager layoutObj)
Here, layautObj is a reference to the desired layout manager.
Java.awt support following Layout managers:

FlowLayout
GridLayout
BorderLayout GridBagLayout

FlowLayout

CardLayout

FlowLayout is the default layout manager for Panel


In FlowLayout Components are laid out from the upper-left comer, left to right and
top to bottom manner.
When no more components fit on a line, the next one appears on the next line.
A small space is left between each component, above and below, as well as left and
right.
The constructors for FlowLayout are
1. FlowLayout( ) : creates the default layout, which centers components and leaves
five pixels of space between each component
2. FlowLayout(int how) : specifies how each line is aligned
3. FlowLayout(int how, int horz, int vert) : specifies the horizontal and vertical
space left between components in horz and vert, respectively
values for how are as follows: FlowLayout.LEFT, FlowLayout.CENTER,
FlowLayout.RlGHT
Program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
Output
class FlowLayoutdemo extends JFrame
{
FlowLayoutdemo ()
{
setSize(200,200);
setVisible(true);
FlowLayout fl=new FlowLayout(FlowLayout.LEFT,10,10);
setLayout(fl);
add(new JCheckBox("Windows 98/XP"));
add(new JCheckBox("Windows NT/2000"));
add(new JCheckBox("Solaris"));
}
public static void main(String[] args)
{
new FlowLayoutdemo ();
}
}

BorderLayout
The BorderLayout is the default layout for JFrame.
It has four narrow, fixed-width components at the edges and one large area in the
center.
The four sides are referred as north, south, east, and west. The middle area is
called the center.
constructors for BorderLayout:
1. BorderLayout( ) : creates a default border layout
2. BorderLayout(int horz, int vert) : specifies the horizontal and vertical space left
between components in horz and vert, respectively
BorderLayout defines the following constants that specify the regions:
BorderLayoutCENTER BorderLayoutNORTH

BorderLayout.WEST

BorderLayout.EAST

BorderLayoutSOUTH

Components can be added using add() method


void add (Component compObj, int region);
Here, compObj is the component to be added, and region specifies

center, north, south, east, and west


Program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class borderlayout extends JFrame
{
borderlayout()
{
setSize(200,200);
setVisible(true);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JLabel("Northside",JLabel.CENTER), BorderLayout.NORTH);
add(new JCheckBox("Center",true), BorderLayout.CENTER);
add(new JRadioButton("East",true), BorderLayout.EAST);
add(new JButton("West"), BorderLayout.WEST);
}

Output

public static void main(String[] args)


{
new borderlayout();
}
}

GridLayout
Arranges all components in rows and columns
All components are given the same size.
constructors supported by GridLayout are
1. GridLayout( ) : creates a single-column grid layout.
2. GridLayout(int numRaws, int numCalumns ) : creates a grid layout with the
specified number of rows and columns.
3. GridLayout(int numRaws, int numCalumns, int harz, int vert)
The third form allows you to specify the horizontal and vertical space left between
components in harz and vert, respectively.
Program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class gridlayout extends JFrame
{
gridlayout()
{
setSize(200,200);
setVisible(true);
setLayout(new GridLayout(2,3,5,5));

Output

for(int i=0;i<6;i++)
add(new JButton(Integer.toString(i)));
}
public static void main(String[] args) {
new gridlayout();
}
}

MODEL-VIEW CONTROLLER DESIGN PATTERN


Every component has three characteristics
1. Its content (e,g., state of a button, text in a text field)
2. Visual appearance (color,size)
3. Behavior(reaction to events)
In MVC, these three characteristics are represented as classes
1. The model, which stores the content
2. The view, which displays the content
3. The controller, which handles user input

The Model class


Stores the content, and has no user interface.
e.g., for text field, the content is string object that holds current text.
It must have methods to change the content and what is the content is .
e.g., for text model, methods are add and remove characters in the current text and return
the current text as string.
Model is completely nonvisual.
The View class
Job of a view to draw the data that is stored in the model class
The Controller class
Handles the user-input events such as mouse clicks and keystrokes.
Then decides whether to translate these events into changes in the model class or the view
class.
e.g., if the user presses a character key in the text box, the controller calls the insert
character command of the model. The model then tells the view to update itself. If the
user presses a cursor key , the controller may tell the view to scroll. Scrolling the view has
no effect on the text, so the model never knows that this event happened.
Note: each components has a wrapper class that stores the model and the view. E.g., when
content is retrieved, the wrapper class asks the model and returns the answer/when the
view is changed, the wrapper class forwards the request to the view.

Pictorial representation of interactions among model, view, controller objects

MVC analysis of Swing Buttons


The behavior(internal state) of the button is captured by the ButtonModel interface.

The default button model is DefaultButtonModel().


Properties of ButtonModel interface are
S.No.
Propertiy Name
value
1.
getActionCommand returns the string associated with the
2.
getMnemonic
Gets the keyboard mnemonics of the button
3.
isArmed
True if the button is pressed and the mouse is still over the button
4.
isEnabled
True if the button is selectable
5.
isPressed
True if the button is pressed and still not released
6.
isRollover
True if the mouse on the button
7.
isSelected
True if the button is toggled on(used for checkboxes and radiobutton)

UNIT-IV

EXCEPTIONS
Definition: An exception is a problem (abnormal conditions) that arises during the
execution of a program and terminates the program abnormally. E.g.,
A user has entered invalid data.
A file that needs to be opened cannot be found

Exception types /Exception Hirearchy


All exception types are subclasses of the built-in class Throwable. There are two subclasses
that partition exception into two distinct branches. They are: (i) Exception (ii) Error
Throwable
Error
(un-recoverable errors)

Exception
UnChecked Exceptions
(Sub classes of RuntimeException)

Checked Exceptions

Exception
This class is used for exceptional conditions that user programs should catch and handle.
All user-defined exception / custom exception must be subclass of Exception.
Inside java.lang package, java defines sereral exception classes
Exceptions are broadly classified as 'checked exceptions' and 'unchecked exceptions.

Unchecked Exceptions
The exceptions that are not checked at compile time are called unchecked exceptions.
These type of exception need not be included in the program
Classes that extends RuntimeException comes under unchecked exceptions.

Examples

for

unchecked

exceptions

ArithmeticException,

NullPointerException,

ArrayIndexOutOfBoundException.

Checked Exceptions
Exceptions that are checked at compile-time are called checked exceptions
all classes that extends Exception class except UncheckedException comes under checked
exception category.
These Exception must be included in the method signature
Example
for
Checked
Exception
are
FileNotFoundException,
ClassNotFoundException, CloneNotSupportedException.
Difference between checked and unchecked Exceptions
S.No
Checked Exception
Unchecked Exception
1.
handled at compile time
Handled at runtime
2.
direct sub-Class of Exception
are subclass of RuntimeException.
3.
represent scenario with higher failure rate are mostly programming mistakes.
Error
These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer These types of error are used by java system, to indicate that error happen in runtime
environment itself. Such a error are: stack overflow, memory out of range, system crash, network
failure, etc

Exception handling fundamentals


Java provides specific keywords for exception handling purposes. They are
1.
2.
3.
4.

try-catch
finally block
throws
throw

Using try catch with finally and multiple catch statements


The general form of exception handling block is shown below:
try {
// block of code to monitor for an error
}
catch(ExceptionType1 ob1) {
// exception handling code here
}
catch(ExceptionType2 ob2) {
// exception handling code here
}

finally {
// code placed here will always executed
}
try block - the program statements that you want to monitor for exception are contained
within the try block
catch block
immediately followed by try block, there must be one or more catch block, one block
for each exception types that excepted to occur in the try block.
When exception occurs in try block, control is transferred to corresponding catch
block that match with an exception thrown

finally block The code in the finally block always get executed, regardless of whether
error occurred in the try block or not.
e.g.1. with single catch
Without try catch
class Exception1
Output
{
public static void main(String[] args) Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
{
at exceptions.singlecatch.main(singlecatch.java:6)
int arr[] = {'0','1','2'};
with try catch,output is
try
Trying to print value from larger upper bound
{
System.out.println(arr[4]);
}catch(ArrayIndexOutOfBoundsException a)
{System.out.println("Trying to print value from larger upper bound");}
}
}
Displaying description of an exception
To print description of an exception, pass exception object as argument to println()
statement.
E.g.
try
output
{
java.lang.ArrayIndexOutOfBoundsException: 4
System.out.println(arr[4]);
}catch(ArrayIndexOutOfBoundsException a)
{System.out.println(a);}
Whenever exception object passed to println, it calls toString ( ) method to print the reason
of the exception.
To display only reason for the exception use getMessage() method
System.out.println("reason: +a.getMessage()); //Output : reason : 4
Eg.2 : for Multiple catch with finally clause
More than one exception could be raised by single piece of code.
To handle all of these exceptions, specify two more catch blocks, each catching different
types of exceptions. However every catch block can handle only one type of exception.
When exception is thrown in try block, control is transferred to catch block that match
with the exception thrown, other catch blocks are bypassed
Example:
Output
class DivideNumbers {
D:\sathiya>java DivideNumbers 10 13.5
public static void main(String args[]) {
only integers are allowed
int a,b,c;
from finally block
try
{
D:\sathiya>java DivideNumbers 10 2
a = Integer.parseInt(args[0]);
c=5
b = Integer.parseInt(args[1]);
from finally block
c = a / b;
System.out.println("c="+c);
D:\sathiya>java DivideNumbers 10 0
}
divisor should not be zero
catch(ArithmeticException e) {
from finally block
System.out.println("divisor should not be zero");
}

catch(NumberFormatException e) {
System.out.println("only integers are allowed");
}
finally {
System.out.println("from finally block");
}
}
}
Note: when handling with exception, with catch block, ensure child exception catch
block appears earlier than that of parent exception catch block. Otherwise you will
receive error message during compilation.

Nested try statement


A try statement within another try block is called as Nested try statement.
If an inner try statement does not have a catch handler for a particular exception, the next
try blocks catch handler are inspected for match.
This continue until one of the catch statement successeds, or until all of the nested try
blocks are exhausted. If no catch is match, java runtime system will handle the exception
Syntax of nested try-catch blocks is given below:
try {
try {
// ...
} catch (ExceptionType e1)
{
//statements to handle the exception
}

}catch (ExceptionType e1)


{
//statements to handle the exception
}
Example:
class NestedTry {
public static void main(String args[]) {
int a,b,c;
try {
a = Integer.parseInt(args[0]);
try{
b = Integer.parseInt(args[1]);
c = a / b;
System.out.println("c="+c);
}catch(ArithmeticException e) {
System.out.println("divisor should not be zero");
}
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("pass values from command prompt");
System.out.println("syntax \n>java NestedTry 10 5");
}
catch(NumberFormatException e) {

System.out.println("only integers are allowed");


}
}
}
In the above program, both the exceptions ArrayIndexOutOfBoundsException,
NumberFormatException are thrown from code of both try block, but inner try block does not
define handle, so that those exception are handled by outer try blocks catch

throw clause
used in a program to generate an exception explicitly.
The general form is
throw thowrableInstance;
here thowrableInstance must be an object of type Throwable or subclass of Throwable.
Simple type such as int, char as well as non sub classes of Throwable such as String and
Object cannot be used as exception
Throwable object can be obtain in two way
(i) using parameter caught into catch block
(ii) create one with new operator
Program
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
}
}
OUTPUT:
Caught inside demoproc
public static void main(String args[]) {
Recaught: java.lang.NullPointerException: demo
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
The flow of exception stops immediately after the throw statement, any subsequent statement
will not all not excute.

throws clause

A throws clause lists the type of exception that a method might expect to throw. This is
necessary for all checked exceptions types, except type of Error or RunTimeException
or subclass of RunTimeException
general form of a method decleration that includes a throws clause is
return-type method-name(parameter-list) throws exception-list
{
//body of method
}

Here an exception-list is a list of exceptions that the method expected to throw separated
by comma.
example
public static void main(String s[])throws IOException, InterruptedException
{
// code here
}

Difference between throw and throws clause


S.no.
throws
1.
multiple exceptions can be thrown
sperated by commas
2.
throws keyword gives a method
flexibility of throwing an Exception
rather than handling it
3
throws cannot be used in the place
of return or break statement
4
throws keyword cannot be used
anywhere except in
method
signature

throw
an only throw one instance of exception
throw keyword transfer control of execution to
caller by throwing an instance of Exception.
throw keyword can also be used in place of return
or break statement
throw keyword can be used inside method or static
initializer block provided sufficient exception
handling

CREATING OWN EXCEPTION SUBCLASSES/USER-DEFINED EXCEPTION


Can create your own exception types to handle exceptional situations specific to our
Program.
To create your own user-defined exception, just define the class that must be a subclass of
an Exception.
The Exception class does not define any method of its own, but inherits method provided
by Throwable.
Thus all exceptions including those that you have created, inherits methods defined by
Throwable class
E.g., // This program creates a custom exception type.
class MyException extends Exception {
private int detail;
OUTPUT
MyException(int a) {
Called compute(0)
detail = a;
Normal exit
}
Called compute(20)
public String toString() {
Caught MyException[20]
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {

compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
RETHROWING AND CHAINING EXCEPTIONS
feature allows you to associate another exception with an exception.
The second exception describes the cause of first exception.
For example, a method throws an ArthimeticException, because of an attempt to divide by zero.
However the actual cause of the problem was that an I/O error occurred, which cause the divisor to
be set in properly.
Although, a method only throw an ArithmeticException, but you might also want to let the calling
code know that underlying causes as an I/O error. This is done by chained exeception.

Two methods and two constructors were added in Throwable for chanined exception
Constructors are
Throwable(String, Throwable)
Throwable(Throwable)
Methods are
Throwable getCause(); => return the exception that causes the current exception
Throwable initCause(Throwable causeExec); initCause() associate causeExec with the
invoking exception and return reference to the exception
Example program
class ChainExcDemo {
static void demoproc() {
NullPointerException e = new NullPointerException("top layer");
e.initCause(new ArithmeticException("cause"));
throw e;
}
OUTPUT:
public static void main(String args[]) { Caught: java.lang.NullPointerException: top layer
try {
Original caise: java.lang.ArithmeticException: cause
demoproc();
} catch(NullPointerException e) {
System.out.println("Caught: " + e);
System.out.println("Original cause: " + e.getCause());
}
}

ANALYSING STACK TRACE ELEMENTS


Stack trace is a listing of all pending(meaning is until/during) method calls at a particular
point in the execution of a program when the exception occurred
Or
A stack trace provides information on the execution history and lists the names of the
classes and methods that were called at the point when the exception occurred
Stack trace listings are displayed whenever a java program terminates with an uncaught
exception
E.g.,
Exception in thread "main" java.lang.NullPointerException

at exception.printstac.method1(printstac.java:9)
at exception.printstac.main(printstac.java:17)
A stack trace is a useful debugging tool that you'll normally take advantage of when an
exception has been thrown
Before javaSE1.4 , we access the text description of a stack trace by calling the
printStackTrace method of the Throwable class.
In latest version, we call the getStackTrace() method to get array of StackTraceElement
objects
The StackTraceEleement class has methods to obtain the file name , line number ,class
name and method name of the executing line of code
Thread.getAllStackTraces() yields the stack trace of all threads
E.g.
public class Prinstac
{
static void method1()
{
throw new NullPointerException() ;
}
public static void main(String[] args)
{
Output
int a;
Prinstac.java:6>>prinstac.Prinstac.method1()
try
Prinstac.java:14>>prinstac.Prinstac.main()
{
method1();
a=42/0;
System.out.println(a);
}catch(Exception e)
{
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0; i < elements.length; i++)
{
System.err.println(elements[i].getFileName() + ":"
+ elements[i].getLineNumber() + ">>"
+ elements[i].getMethodName() + "()" );
}
}
}
}

ASSERTIONS
Java language gives 3 mechanisms to deal with system failures
1. Throwing an exceptions
2. Logging
3. Using assertions
Assertions are a commonly used idiom(i.e., expression) for defensive programming.
Assertion mechanism allows you to put in checks during testing and to have them
automatically removed in the production code.
Syntax for assertion
assert (condition) [ : messageExpression];

The optional messageExpression will be converted to a String and passed as the message to
the AssertionError constructor, so it cannot be a call to a function declared as void.
e.g.,
Output
public class AssertionTest {
Exception in thread "main"
public static void main(String[] args) {
java.lang.AssertionError: thirdPartyFunction
double value = thirdPartyFunction();
value 5.0 out of range
assert (value >= 0 && value < 1) :
" thirdPartyFunction value " + value + " out of range"; at AssertionTest.main(AssertionTest.java:12)
System.out.println("Value is " + value);
}
public static double thirdPartyFunction() {
return 5.0;
}
}

Assertion Enabling and Disabling


By default assertions are disabled. To enable use -enableassertions or ea . To disable use
-da

When should you choose assertions?


1. Assertion failures are intended to be fatal(i.e., critical), unrecoverable errors
2. Assertion checks are turned on only during development and testing
3. Assertion should only be used to locate internal program errors during testing

LOGGING
Logging helps a programmer in the debugging process of a program.
Logging is the process of writing log(i.e., record/register) messages during the execution
of a program to a central place. This logging allows you to report and persist error and
warning messages as well as info messages (e.g. runtime statistics) so that the messages
can later be retrieved and analyzed.
The java.util.logging package provides the logging capabilities via the Logger class.
Create a logger
A Logger class is used to create a logger object which is used to log messages.
A logger object is provided with a name and has a set of methods which are used to log
messages at the different levels.
import java.util.logging.Logger;
// assumes the current class is called logger
private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());
Level
There are seven logging levels provided by the Level class. All these levels are static final
field
SEVERE

The highest value; intended for extremely important messages

WARNING Intended for warning messages.


INFO

Informational runtime messages.

CONFIG

Informational messages about configuration settings/setup.

FINE

Used for greater detail, when debugging/diagnosing problems.

FINER

Even greater detail.

FINEST

The lowest value; greatest detail.

Program
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class log2example {
static Logger LOGGER = Logger.getLogger(log2example.class.getName());
public static void main(String[] args) throws SecurityException, IOException
{
LOGGER.info("Logger Name: "+LOGGER.getName())
LOGGER.warning("Can cause ArrayIndexOutOfBoundsException");
//An array of size 3
int []a = {1,2,3};
int index = 4;
LOGGER.config("index is set to "+index);
try{
System.out.println(a[index]);
}catch(ArrayIndexOutOfBoundsException ex)
{
LOGGER.log(Level.SEVERE, "Exception occur", ex);
}
} }
Output
Sep 13, 2014 9:41:09 AM exception.log2example main
INFO: Logger Name: exception.log2example
Sep 13, 2014 9:41:09 AM exception.log2example main
WARNING: Can cause ArrayIndexOutOfBoundsException
Sep 13, 2014 9:41:09 AM exception.log2example main
SEVERE: Exception occur
java.lang.ArrayIndexOutOfBoundsException: 4
at exception.log2example.main(log2example.java:26)

GENERIC PROGRAMMING/PARAMETER TYPES


Generics help us to create a single class, which can be useful to operate on multiple data
types.
or
To write a code that code that can be reused for objects of many different types

Motivation of Generic programming/Advantage of Java Generics


1) Type-safety : Generics hold only a single type of objects.(i.e., It doesnt allow to store
other objects). Remember that generics only work on objects, not primitive types.
2) Type casting is not required: There is no need to typecast the object.E.g.,
Before Generics, type cast is need
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, no need typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");

String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime. The good programming strategy says it is far better to handle the problem at compile
time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Syntax to use generic
ClassOrInterface<Type>
e..g., ArrayList<String>

GENERIC CLASS
A generic class is a class with one or more type variables
Or
A class that can refer to any type is known as generic class.
Syntax
accessspecifier class genericclassname <type variable1, typevariable2..>
{
Constructors
Methods
Fields
}
Type variable indicates that it can refer to any type and having more than one type
paramenter is called as parameterized class
Type variable cannot be primitive type
Program
public class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}

Output
Integer Value :10
String Value :Hello World

public static void main(String[] args) {


Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}

Understanding Type Parameters


The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
6. S,U,V etc. - 2nd, 3rd, 4th types

GENERIC METHODS
A method with type parameters.
Can be defined inside ordinary classes and inside generic classes
Type variables must be placed after modifiers and before return type
Generic methods are invoked like normal methods or invoked by substituting the type
Syntax
[access specifier]<type variable1, type variable2..> return type methodname(parameters)
{
Action block;
}
Syntax to call generic methods

classname/objectname.methodname (parameters)
Or
classname/objectname .[<type>]methodname(parameters)
Example
public class genericmethod
{
< E > void printArray(E[] elements) {
for ( E element : elements)
Output
{
System.out.printf(element +"\t");
}
Printing Integer Array
System.out.println();
10
20
30
40
}
Printing Character Array
public static void main( String args[] ) {
J
A
V
A
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A' };
genericmethod g=new genericmethod();
System.out.println( "Printing Integer Array" );
g.<Integer>printArray( intArray );
System.out.println( "Printing Character Array" );
g.<Character>printArray( charArray );
}
}
Bounds for Type Variables
Placing a restrictions on type variables on a class or a method.
Program

50

class boundtypevariables<T extends Number> {


private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}

Output
Integer Value :10
Float Value :10.50

public static void main(String[] args) {


boundtypevariables<Integer> integerBox = new boundtypevariables<Integer>();
// boundtypevariables<String> stringBox = newboundtypevariables<String>();
boundtypevariables<Float> floatBox = new boundtypevariables<Float>();
integerBox.add(new Integer(10));
// stringBox.add(new String("Hello World"));
floatBox.add(new Float(10.5f));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
// System.out.printf("String Value :%s\n", stringBox.get());
System.out.printf("Float Value :%.2f\n\n", floatBox.get());
}
}

GENERIC CODE AND VIRTUAL MACHINE


According to JVM all objects are treated as ordinary classes.
Whenever a generic type is defined a corresponding raw type is automatically
provided
The name of the raw type is simply the name of the generic type, with the type parameters
removed.
The type variables are erased and replaced by their bounding types(or Object for
variables without bounds);
Type erasure
Type erasure works by replacing the type parameter by its bound at compile time.
If no bound is specified, the compiler assumes that the bound is Object. Specifying
Object as the upper bound and not specifying any bound is actually the same thing.
Otherwise it replaces type variables with the first bound, if bound is specified.
Here is a very simple example of generic code without bound is specified.
public class GenericMethod
{
public static <T> T get(T str)
{
return anObject;
}
public static void main(String[] args)
{
String reply = get(Hai);
}
}
The compiler transforms this into the following code:

public class GenericMethod


{
public static Object get(Object str)
{
return anObject;
}
public static void main(String[] args)
{
String reply = (String)get (Hai);
}
}

Translating Generic Expressions


Return type of a generic method is automatically casted to the appropriate type of the
object.
This is achieved by , the compiler translates the method call into two virtual machine
instructions
1) A call to the raw method
2) A cast of the returned Object to the appropriate type.
e.g., assume a class called as Pair<T> and it contains a method T getFirst()
Pair<String> p=new Pair(a,b);
---String s=p.getFirst();
Here the method getFirst() returns the type Object. Then this Object is casted automatically
into String

Translating Generic Methods


Type Erasure is also applied for generic methods.
E.g., consider a generic method
public static <T extends Comparable> T min(T[] a)
After applying type erasure, this method becomes like
public static Comparable min(Comparable[] a)
Note that the type parameter T has been erased, leaving only its bounded type Comparable
Erasure of method brings up complexities.
E.g.,
class DateInterval extends Pair<Date>
{
public void setSecond(Date second)
{

}
..
}
After type erasure this method becomes like
class DateInterval extends Pair
{

public void setSecond(Date second)


{
..
}
..
}

This class also contains another setSecond() method, inherited from its base class pair
public void setSecond(Object);
Now consider the statements to call setSecond() method of DateInterval class
Pair<Date> pair = new DateInterval();
pair.setSecond(aDate);
Instead of calling DateInterval.setSecond() method it calls Pair.setSecond() due to
interference of type erasure with polymorphism.
To overcome this problem , the compiler generates a bridge method in the
DateInterval class
public void setSecond(Object second)
{
setSecond(Date) second;
}

Inheritance and generic Types


In java, it is possible to assign an object of one type to an object of another type provided
that the types are compatible. example, you can assign an Integer to an Object, since
Object is one of Integer's supertypes:
Object someObject = new Object();
Integer someInteger = new Integer(10);
someObject = someInteger; // OK

In object-oriented terminology, this is called an "is a" relationship. Since an Integer


is a kind of Object, the assignment is allowed. But Integer is also a kind of Number, so
the following code is valid as well:
public void someMethod(Number n) { /* ... */ }
someMethod(new Integer(10)); // OK
someMethod(new Double(10.1)); // OK
The same is also true with generics. You can perform a generic type invocation,
passing Number as its type argument, and any subsequent invocation of add will be
allowed if the argument is compatible with Number:
Box<Number> box = new Box<Number>();
box.add(new Integer(10)); // OK
box.add(new Double(10.1)); // OK
Now consider the following method:

public void boxTest(Box<Number> n) { /* ... */ } // invalid

What type of argument does it accept? By looking at its signature, you can see that it accepts
a single argument whose type is Box<Number>. But what does that mean? Are you allowed to
pass in Box<Integer> or Box<Double>, as you might expect? The answer is "no", because
Box<Integer> and Box<Double> are not subtypes of Box<Number>.
Pictorial Representation

Note: Given two concrete types A and B (for example, Number and Integer),
MyClass<A> has no relationship to MyClass<B>, regardless of whether or not A and B are
related. The common parent of MyClass<A> and MyClass<B> is Object.

How to make relationships


Generic classes or interfaces are not related merely because there is a relationship between
their types. However, you can use wildcards to create a relationship between generic
classes or interfaces.
Given the following two regular (non-generic) classes:
class A { /* ... */ }
class B extends A { /* ... */ }
It would be reasonable to write the following code:
B b = new B();
A a = b;
This example shows that inheritance of regular classes follows this rule of subtyping: class
B is a subtype of class A if B extends A.
This rule does not apply to generic types:
List<B> lb = new ArrayList<>();
List<A> la = lb; // compile-time error
Given that Integer is a subtype of Number, what is the relationship between List<Integer>
and List<Number>?

The common parent is List<?>.


Although Integer is a subtype of Number, List<Integer> is not a subtype of
List<Number> and, in fact, these two types are not related. The common parent of
List<Number> and List<Integer> is List<?>.
In order to create a relationship between these classes so that the code can access Number's
methods through List<Integer>'s elements, use an upper bounded wildcard:
List<? extends Integer> intList = new ArrayList<>();
List<? extends Number> numList = intList; // OK. List<? extends Integer> is a
subtype of List<? extends Number>
Because Integer is a subtype of Number, and numList is a list of Number objects, a
relationship now exists between intList (a list of Integer objects) and numList.

UNIT-V

CONCURRENT PROGRAMMING - INTRODUCTION


There are two distinct types of multitasking: process-based and thread-based.
1. Process-based multitasking
is the feature that allows your computer to run two or more programs
concurrently.
For example, process-based multitasking enables you to run the Java compiler at the
same time that you are using a text editor.
2. A thread-based multitasking environment,
allows you to execute more than one part of the single program simultaneously /
concurrently.
For example within single program, one thread can used display live time in the topright corner screen, and the other thread can display animation in the whole screen
Thread definition: is a tiny program running concurrently.
Difference between thread and process
Thread
Process
is a light-weight process
is a heavy-weight process
Threads do not require separate address space for its execution. Each process requires separate
It runs in the address space of the process to which it belongs to address space to execute

Thread life cycle/Thread States


Thread Life cycle specifies how a thread gets processed in the java program. Threads exist in
several states. They are
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed waiting
6. Terminated
Pictorial representation of thread life cycle

1. New State: After the creations of Thread instance the thread is in this state but before the
start() method invocation. At this point, the thread is considered not alive.
2. Runnable state/ Runnable (Ready-to-run) state A thread start its life from Runnable
state. A thread first enters runnable state after the invoking of start() method but a thread can
return to this state after either running, waiting, sleeping or coming back from blocked
state also. On this state a thread is waiting for a turn on the processor.
There are 3 ways by which a thread can enter in waiting state
3. Waiting state: sometimes one thread has to undergo in waiting state because another
thread starts executing. This can be achieved by using wait() method
4. Timed waiting state
Keeping particular thread waiting for some time interval.
This allows executing high prioritized thread first.
After the timing gets over, the thread in waiting state enters in runnable state.
This can be achieved by using sleep() method
5. Blocked state
When a thread issues an I/O request then OS sends it in blocked state until the I/O
operation gets completed.
After the I/O completion the thread is sent back to the runnable state.
This can be achieved by using suspend() method
6. Terminated state
After successful completion of the execution the thread in runnable state enters the
terminated state.

Thread Class and the Runnable Interface


Java's multithreading can be created by using Thread class, its methods, and its
companion interface, Runnable.

task for a Thread is written in the run( ) method of Runnable interface.


The signature of run method and Runnable interface shown below:
public interface java.lang.Runnable{
public abstract void run();
}
Pictorial representation of Implementation of thread
Implementation of thread

extends

implements

Thread class

Runnable Interface
overrides

run() method
Method in the Thread Class
METHOD
String getName( )
int getPriority( )
void getPriority( int priority)
boolean isAlive( )
synchronized void join( )
void run()
static native void sleep(long ms)
void start( )
void setName( String tname)
static native Thread currentThread( )
Thread.State getState()

MEANING
Obtain a thread's name.
Obtain a thread's priority
Change the priority of the invoking thread. Possible range
of values are :1(MIN) to 10 (MAX)
Determine if a thread is still running
Wait for a thread to terminate
Entry point for the thread
Suspend a thread for a ms millisecond time
Start a thread by calling its run method
To change the name of the thread
To obtain reference to the current Thread
Gets
the
state
of
the
thread;
one
of
NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAI
TING ,TERMINATED

Syntax for thread consturctors


1. Thread()
2. Thread( Runnable thObj);
3. Thread(Runnable threadOb, String threadName)
4. Thread( String threadName);

The Main Thread


When a Java program starts up, one thread begins running immediately. This is called the
main thread of your program, because it is the one that is executed when your program
begins.
The main thread is important for two reasons:
It is the thread from which other "child" threads will be produced / spawned

Often it must be the last thread to finish execution because it performs various
shutdown actions
Thread reference can be obtained by the method currentThread(), which is a public static
member of Thread.
Its general form is
static Thread currentThread( )
E.g.,
Output
Thread t = Thread.currentThread();
Current thread: Thread[main,5,main]
System.out.println("Current thread: " + t);

Creating new Thread


To create a new thread, your program will have two options:
i.
By instantiating Thread and implementing the Runnable interface
ii.
By extending Thread class
i. By Implementing Runnable interface
The easiest way to create a thread is to create a class that implements the Runnable
interface.
create a new class that implements Runnable interface
After creating a class that implements Runnable, instantiate an object of type Thread
within that class.
The implementing class must override the run( ) method, which is the entry point for
the new thread.
After the new thread is created, it will not start running until you call its start( )
method, which is declared within Thread. Whenever start( ) is called , the thread starts
executes code defined in the run( ) method.
The start( ) method is shown here:
void start( )
Program
class NewThread implements Runnable {
Thread t;
NewThread() {
Output
t = new Thread(this);
Main Thread: 5
t.start(); // Start the thread
Child Thread: 5
}
Child Thread: 4
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread

Child Thread: 3
Main Thread: 4
Child Thread: 2
Main Thread: 3
Child Thread: 1
Main Thread: 2
Main Thread: 1

try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
}
}
ii) By extending Thread class
The second way to create a thread is to
Create a new class that extends Thread class as its super class, and then create an
instance of that new class.
The extending class must override the run( ) method, which is the entry point for the new
thread.
It must also call start( ) to begin execution of the new thread. Here is the preceding
program rewritten to extend Thread:
Program
class threaddemo extends Thread {
threaddemo() {
// Create a new, second thread
start(); // Start the thread
}
Output
// This is the entry point for the second thread.
Main Thread: 5
public void run() {
Child Thread: 5
try {
Child Thread: 4
for(int i = 5; i > 0; i--) {
Main Thread: 4
System.out.println("Child Thread: " + i);
Child Thread: 3
Thread.sleep(500);
Child Thread: 2
}
Main Thread: 3
} catch (InterruptedException e) {
Child Thread: 1
System.out.println("Child interrupted.");
Main Thread: 2
}
Main Thread: 1
}
}
class ExtendThread {
public static void main(String args[]) {
new threaddemo(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
}

Interrupting Thread
A thread terminates when the run method returns by executing a return statement, after
executing the last statement in the method body or if an exception occurs that is not
caught in the method.
There is a way to force a thread to terminate. The interrupt() method can be use to
request termination of a thread
When the interrupt() method is called on a thread, the interrupted status of the thread is
set.
This is a boolen flag that is present in every thread.
If any thread is in sleeping or waiting state(i.e., sleep() or wait() is invoked) calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException.
If the thread is not in the sleeping or waiting state, calling the interrupt() method performs
normal behavior and doesnt interrupt the thread but sets the interrupt flag to true.
Methods for interrupting a thread provided by Thread class
1. public void interrupt()
2. public static boolean interrupted() => method returns true if the current thread has
been interrupted; false otherwise.
3. public boolean isInterrupted()
Program
class A extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
Output
}
Exception in thread "Thread-0"
public static void main(String args[]){
java.lang.RuntimeException: Thread interrupted...
A t1=new A();
java.lang.InterruptedException: sleep interrupted
t1.start();
at threada.A.run(ThreadA.java:13)
try{
t1.interrupt();
}catch(Exception e){System.out.println(e);}
}
}

Thread Properties
Various properties of thread are
1. Thread priorities
2. Daemon threads
3. Thread Group
4. Handlers for uncaught exception
1. Thread priorities
Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run.

In java every thread has a priority.


By default, a thread inherits the property of the thread constructed it.
Thread priority is a simple integer value that can be assigned to the particular thread.
Methods use to increase or decrease the priority is
void setPriority(int newpriority)
int getPriority();
the variable newpriority
can take value from Thread.MIN_PRIORITY(1) to
Thread.MAX_PRIORITY(10). You can also use Thread.NORMAL_PRORITY(5)
2. Daemon Thread
is a low priority thread that has no other role in life than to serve others(i.e., which runs in
the back ground). Therefore it is called as service provider threads
E.g., thread doing the garbage collection operation for java runtime system
Daemon threads will be terminated by the JVM when there are none of the other threads
running, it includes main thread of execution as well.
To specify that a thread is a daemon thread, call the setDaemon method with the
argument true. The signature is
void setDaemon(boolean flag);
To determine if a thread is a daemon thread, use the accessor method isDaemon().
E,g,
public class Dthread extends Thread{
public Dthread(){
output
setDaemon(true);
Is this thread Daemon? -ture
}
public void run(){
System.out.println("Is this thread Daemon? - "+isDaemon());
}
public static void main(String a[]){
Dthread dt = new Dthread();
// even you can set daemon constrain here also
// it is like dt.setDeamon(true)
// if u set after start() it throws java.lang.IllegalThreadStateException
dt.start();
}
}
3. Handlers for uncaught Exception

The run method of a thread cannot throw any checked exceptions, but it can be terminated
by an unchecked exception. During this handling process the thread dies
When a thread is about to terminate due to an uncaught exception the Java Virtual
Machine will query the thread for its Thread.UncaughtExceptionHandler interface using
Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException
method, passing the thread and the exception as arguments. The signature of
uncaughtException is
void uncaughtException(Thread t, Throwable e)
If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup
object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special
requirements for dealing with the exception, it can forward the invocation to the default
uncaught exception handler.
E.g.
public class Uncaughex {

public static void main(String[] args) {


Thread t = new Thread(new adminThread());
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println(t + " throws exception: " + e);
}
Output
});
Thread[Thread-0,5,main] throws exception:
// this will call run() function
java.lang.RuntimeException
t.start();
}
}
class adminThread implements Runnable {
public void run() {
throw new RuntimeException();
}
}

Thread Synchronization
When two or more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time.
The process by which this is achieved is called thread synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore).
A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread
can own a monitor at a given time.
When a thread acquires a lock, it is said to have entered the monitor. All other threads
attempting to enter the locked monitor will be suspended until the first thread exits the
monitor. These other threads are said to be waiting for the monitor.
In java You can synchronize your code or object in either of two ways.
i.
using synchronized method/keyword
ii.
using synchronized statement / block
1. using synchronized method/keyword
To ensure the object/ resource used by only one thread at a time, use synchronized
keyword in front of all the methods of the class from which, the object is instantiated
The synchronized keyword indicates that a method can be accessed by only one thread
at a time.
synchronized keyword can be applied only to methods, not variables, not classes, just
methods.
A synchronized declaration for a method is :
public synchronized returntype methodname(parameter list)
static method can also be synchronized
Syntax
public static synchronized returntype methodname(parameter list)
Program
class Callme {
synchronized void call(String msg) {
System.out.print("[" + msg);
The output: When the method is synchroized
try {
[Hello]
Thread.sleep(1000);
[World]
} catch (InterruptedException e) {
[Synchronized]
Output: when the method is not synchronized
[Hello[World[Synchronized]
]
]

System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
}
}
2. using synchronized block
Sometime you want to synchronize access to objects of a class that was not designed for
multithreaded access.
That is, the class does not use synchronized methods.
Further, this class was not created by you, but by a third party and you do not have access
to the source code.
Thus, you can't add synchronized to the appropriate methods within the class.
The solution to this problem is quite easy:
You simply put calls to the methods defined by this class inside a synchronized block.
This is the general form of the synchronized statement:
synchronized(object) {
/ / statements to be synchronized
}
Here,
object
is
a
reference
to
the
object
being
synchronized.
the above example is modified, using a synchronized block within the run( ) method:
1. In the above program first remove synchronized keyword, from method definition call( )
of class CallMe
2. second modify the run( ) method of Caller class similar to the following:
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}

Here, the call( ) method is not modified by synchronized.


Instead, the synchronized statement is used inside Caller's run() method.
This causes the same output as the preceding example

Executors
Creating a threadpool.
Threadpool contains a number of idle threads that are ready to run.
or
A thread pool manages the pool of worker threads, it contains a queue that keeps tasks
waiting to get executed.
Pictorial representation of threadpool

You give a Runnable to the pool and one of the thread calls the run method.
When the run method exists, the thread doesnt die but stays around to serve the next
request
java.util.concurrent.Executors
provide
implementation
of
java.util.concurrent.Executor interface to create the thread pool in java.
The Executors class has a number of static factory methods for constructing thread pools
Method
Description
newFixedThreadPool
Creates a fixed size thread pool and idle threads are
kept indefinitely
newCachedThreadPool
New threads are created as needed , idle threads are
kept for 60 seconds
newSingleThreadExecutor
A pool with a single thread that executes the
submitted tasks sequentially
newScheduledThreadPool
A fixed-thread pool for scheduled execution, a
replacement for java.util.Timer
newSingleThreadScheduledExectuor
A single-thread pool for scheduled execution
Program
import java.util.concurrent.*;
class WorkerThread implements Runnable {
String msg
WorkerThread(String s)
{
msg=s; }
public void run() {
System.out.println(Thread.currentThread().getName()+" Start message = "+message);
processmessage();
System.out.println(Thread.currentThread().getName()+" End");

}
void processmessage() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) { }
}
}
class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(5);
for (int i = 0; i < 3; i++) {
Runnable worker = new WorkerThread("" + i);
exec.execute(worker);
}
exec.shutdown();
}
}

Output
pool-1-thread-1 Start message = 0
pool-1-thread-3 Start message = 2
pool-1-thread-2 Start message = 1
pool-1-thread-1 End
pool-1-thread-3 End
pool-1-thread-2 End

THREAD SAFE COLLECTIONS


If multiple threads concurrently modify a data structure such as a hash table, then it is
easily possible to damage the data structure
for example
one thread begins to insert a new element and it is preempted while it is in the middle of
rerouting the links between the hash table bucket.
If another thread starts traversing the same list, it may follow invalid links and create
havoc(meaning disorder) perhaps throwing exceptions or being trapped in an infinite loop
to avoided this, locks can be applied on the data structure, instead we can choose thread
safe collection classes.
java.util.concurrent package provides efficient implementation of maps, sorted sets and
queues using
1 ConcurrentHashMap,ConcurrentSkipListMap: constructs a hash map that can be
safely accessed by multiple threads
2 ConcurrentSkipListSet: constructs a sorted set that can be safely accessed by
multiple threads
3 ConcurrentLinkedQueue : constructs an unbounded, nonblocking queue that can be
safely accessed by multiple threads
These collections uses sophisticated algorithms that minimize contention(meaning
conflict) by allowing concurrent access to different parts of the data structure
Thread safety can be achieved from core collection interface such as Collection, Set, List,
Map, SortedSet and SortedMap. Each interface has one factory method. They are
public static Collection synchronizedCollection(Collection c);
public static Set synchronizedSet(Set s);
public static List synchronizedList(List list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static SortedSet synchronizedSortedSet(SortedSet s);
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);
Program
import java.util.concurrent.*;
public class ConcurrentSkipListSetTest {

ConcurrentSkipListSet<String> csls= new ConcurrentSkipListSet<String>();


class AddThread implements Runnable {
public void run() {
//adds specified element in the set
csls.add("A"); csls.add("B"); csls.add("C);
System.out.println(First Element + csls.first());
System.out.println(Last Element : + csls.last());
Output
}
First Element A
}
Last Element : C
class SubThread implements Runnable {
public void run() {
After Removing A from the set :[B,C]
csls.remove("A");
System.out.println(After Removing A from the set : + csls);
}
}
public static void main(String... args) {
ConcurrentSkipListSetTest ob = new ConcurrentSkipListSetTest();
new Thread(ob.new AddThread()).start();
new Thread(ob.new SubThread()).start();
}
}

SYNCHRONIZERS
Java.util.concurrent package contains several classes that help manage a set of
collaborating threads.
The classes are CyclicBasrrier, CountDownLatch, Exchanger, semaphores,
SynchrronousQueue,
which
facilitate
coordination
between
threads.

THREADS AND SWINGS

After Swing components have been displayed on the screen, they should only be operated
on by the event-handling thread.
The event-handling thread (or just event thread) is started auto-matically by the Java VM
when an application has a graphical interface.
The event thread calls methods like paint()on Component,actionPerformed() on
ActionListener , and all of the other event-handling methods.
Most of the time, modifications to Swing components are done in the event-handling
methods.
Because the event thread calls these methods, it is perfectly safe to directly change
components in event-handling code
One of the goals for the developers of Swing was to make the toolkit as fast as possible.
If the components had to be multithread-safe, there would need to be a lot of synchronized
statements and methods.
Using SwingUtilities.invokeAndWait() and invokeLater()
To make swing compenets multithread safe , java provides two methods invokeAndWait()
and invokeLater() method
1. invokeAndWait()
The developers of the Swing toolkit realized that there would be times when an external
thread would need to make changes to Swing components.
They created a mechanism that puts a reference to a chunk of code on the event queue.
When the event thread gets to this code block, it executes the code.
invokeAndWait() method is used to put references to blocks of code onto the event
queue:.
Syntax of invokeAndWait() method of SwingUtilities class is
public static void invokeAndWait(Runnable target) throws InterruptedException,
InvocationTargetException
The parameter target is a reference to an instance of Runnable.
The Runnable interface is simply being used as a means to identify the entry point for the
event thread.
An InterruptedException is thrown if the thread that called invokeAndWait() is
interrupted before the block of code referred to by target completes. An
InvocationTargetException (a class in the java.lang.reflect package) is thrown if an
uncaught exception is thrown by the code inside run().
The event thread will end up calling the run() method of the Runnable when its turn
comes up on the event queue.
E.g.,
Output
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.swing.*;
class InvokeAndWaitDemo
{
static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + : + msg);
}
public static void main(String[] args) {

main:sleeping for 3 seconds


main:creating code block for event thread
main:about to invokeAndWait()
AWT-EventQueue-0:about to do setText()
main:back from invokeAndWait()

final JLabel label = new JLabel();


JPanel panel = new JPanel(new FlowLayout());
panel.add(label);
JFrame f = new JFrame(InvokeAndWaitDemo);
f.setContentPane(panel);
f.setSize(300, 100);
f.setVisible(true);
try {
print(sleeping for 3 seconds);
Thread.sleep(3000);
print(creating code block for event thread);
Runnable setTextRun = new Runnable() {
public void run() {
print(about to do setText());
label.setText(New text!);
}// run method end
};// anonymuns class end
print(about to invokeAndWait());
SwingUtilities.invokeAndWait(setTextRun);
print(back from invokeAndWait());
} catch ( InterruptedException ix ) {
print(interrupted while waiting on invokeAndWait());
} catch ( InvocationTargetException x ) {
print(exception thrown from run());
}
}
}

Das könnte Ihnen auch gefallen