Notes On Java
Notes On Java
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
Classes contain data members and methods that operate on the data members of
the class
documentation section
package statement
import statements
interface statements
Class definitions
main method class
{
main method definition
}
suggested
optional
optional
optional
optional
Compulsory
student;
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);
}
}
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
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
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:
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]);
Statement
Effect or result
Declare
Box
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
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
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.
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
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);
}
}
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;
{
//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
}
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.
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
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
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
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
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
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
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
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|
@return
@throws
@version
@see
Description
Specify the author of the program
Syntax
@author name-text
Example
@author IIICSE
@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)
@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 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
super(parameter-list);
- Here parameter-list specifies argument list that should match with the constructor
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
}
}
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.:
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);
}
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
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];
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
x2 object
x1 object
d object
x2 object
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); }
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
class Outer {
int outer_x = 100;
void test()
{
new
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
{
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.
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.
5.
6.
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.
Frame
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.
4.
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
Line2D
Ellipse2D
Rectangular
Shape
Rectangle2D
Rectangle
Class Name
Rectangle2D.Double
Rectangle2D.Double(double x, double
y, double w, double h)
Rectangle2D.Float
Ellipse2D.Double
Ellipse2D.Double(double x, double y,
double w, double h)
Line2D.Double
Class name
RectanglerShape
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
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
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)
void setForeground(Color c)
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();
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
import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;
Output
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.
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
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()
JCom
Comp
Comp
Comp
getWindow()
JScro
Wind
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 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") ;
l.setText("i am Exited") ;
l.setText("I am Entered"); }
l.setText("I am Pressed"); }
l.setText("I am Released);
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
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)
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
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.
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();
}
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.
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
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()
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.
FlowLayout
GridLayout
BorderLayout GridBagLayout
FlowLayout
CardLayout
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
Output
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();
}
}
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
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
try-catch
finally block
throws
throw
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.
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
}
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
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());
}
}
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;
}
}
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
CONFIG
FINE
FINER
FINEST
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)
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
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
Output
Integer Value :10
Float Value :10.50
}
..
}
After type erasure this method becomes like
class DateInterval extends Pair
{
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;
}
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.
UNIT-V
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.
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
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);
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.
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 {
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);
}
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
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.
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) {