Академический Документы
Профессиональный Документы
Культура Документы
Dundigal, Hyderabad
JAVA
PROGRAMMING
concepts.
UNIT - I
Objectives
TOPICS
OOP Concepts: - Data abstraction, encapsulation, inheritance,
benefits of inheritance, polymorphism, classes and objects,
Procedural and object oriented programming paradigms.
INTRODUCTION
Layers of Computer Software
Since the invention of the computer, many programming approaches
have been tried. These include techniques such as modular
programming, top-down programming, bottom-up programming and
structured programming. The primary motivation in each is to
handle the complexity of programs.
INTRODUCTION
Categories of Programming Languages:
1. Monolithic Programming Language
2. Procedural Programming Language
3. Structured Programming Language
4. Object Oriented Programming Language
Monolithic Programming Language: Monolithic Programming Language
contains number of lines of Data.
It does not have subroutine concept.
The program code is duplicated each time it is to be used.
For e.g. : Assembly Language ,BASIC
INTRODUCTION
Structured Programming Language:
Programs are divided into individual Procedures that performs discrete tasks
Procedure are independent of each other
Procedures have their own local data and Logic
Introduction of user defined datatypes
Data Security was a problem
For e.g.: Pascal ,C
Functions that operate on the data of an object are tied together in the
data structure.
Procedural Vs OOP
Procedure Oriented Programming
Program is divided into functions, every function has its own data and
global data.
Main program
Function-2
Function-1
Function-4
Function-6
Structure
programs
Global data
Function-3
Function-5
Function-7
of
Global data
Function-8
procedure-oriented
Function-1
Function-2
Function-3
Local data
Local data
Local data
Procedural Vs OOP
Object Oriented Programming (OOP)
OOP decompose the problem into number of entities called objects and it
contains the data and functions.
Object A
Object B
Data
Methods
Data
Communication
Methods
Object C
Methods
Data
Organization of Data & Methods in
OOP
Procedural Vs OOP
Procedure Vs Object Oriented Programming
functions.
Procedural Vs OOP
Characteristics of Object-Oriented Programming
10
Procedural Vs OOP
Top Down Vs Bottom Up Approach
Top Down approach:
A Single module will be split into several smaller modules
General to Specific
Bottom Up approach:
Lot of small modules will be grouped to form a single large module
Specific to General
If the requirements are clear at the first instance, we can go for Top
Down approach.
11
OOP CONCEPTS
Object Oriented Programming Concepts:
Classes
Objects
Data Abstraction
Encapsulation
Inheritance
Polymorphism
12
OOP CONCEPTS
Class & Object
13
OOP CONCEPTS
Data Abstraction
Procedure Abstraction
Data Abstraction
14
OOP CONCEPTS
Encapsulation
That is, the data and methods are given in the class definition.
15
OOP CONCEPTS
Inheritance
OOP CONCEPTS
Benefits of Inheritance
1) Software reusability (among projects) : Functions written once can be
reused. No need to spend time in rewriting the code
2) Code sharing (within a project) : Many users and projects can use the
same classes.
:Guarantees that
interfaces to similar objects are in fact similar and the user is not
17
OOP CONCEPTS
5) Rapid
prototyping
(quickly
assemble
from
pre-existing
components):
and
frameworks
Polymorphism
permits
(high-level
the
reusable
programmer
to
hiding
:Reduces
inter
connections
between
OOP CONCEPTS
Polymorphism
Poly Many
Morph Form
Compile time
Polymorphism
Runtime
Polymorphism
19
OOP CONCEPTS
Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the
use of existing classes.
Java History
Computer language innovation and development occurs for two
fundamental reasons:
1) to adapt to changing environments and uses
2) to implement improvements in the art of programming
Before Java: C
Designed by Dennis Ritchie in 1970s.
Before C: BASIC, COBOL, FORTRAN, PASCAL
C- structured, efficient, high-level language that could replace assembly
code when creating systems programs.
Designed, implemented and tested by programmers.
21
Java History
Before Java: C++
Designed by Bjarne Stroustrup in 1979.
Response to the increased complexity of programs and respective
improvements in the programming paradigms and methods:
1) assembler languages
2) high-level languages
3) structured programming
4) object-oriented programming (OOP)
OOP methodology that helps organize complex programs through the use
of inheritance, encapsulation and polymorphism.
C++ extends C by adding object-oriented features.
22
Java History
In 1990, Sun Microsystems started a project called Green.
23
Java History
Internet programming presented a BIG business opportunity. Much
bigger than programming for consumer electronics.
A common story is that the name Java relates to the place from where
the development team got its coffee. The name Java survived the trade
mark search.
24
Features of Java
The key considerations were summed up by the Java team in the following
list of buzzwords or features :
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
25
Features of Java
simple Java is designed to be easy for the professional programmer to
learn and use.
object-oriented: a clean, usable, pragmatic approach to objects, not
restricted by the need for compatibility with other languages.
Robust: restricts the programmer to find the mistakes early, performs
compile-time (strong typing) and run-time (exception-handling)
checks, manages memory automatically.
Multithreaded: supports multi-threaded programming for writing program
that perform concurrent computations.
Architecture-neutral: Java Virtual Machine provides a platform
independent environment for the execution of Java byte code
Interpreted and high-performance: Java programs are compiled into an
intermediate representation byte code:
a) can be later interpreted by any JVM
b) can be also translated into the native machine code for
efficiency.
26
Features of Java
Distributed: Java handles TCP/IP protocols, accessing a resource through
its URL much like accessing a local file.
Dynamic: substantial amounts of run-time type information to verify and
resolve access to objects at run-time.
Secure: programs are confined to the Java execution environment and
cannot access other parts of the computer.
27
Data Types
28
Data Types
Java defines eight simple types:
1) byte 8-bit integer type
2) short 16-bit integer type
3) int 32-bit integer type
29
Data Types
byte: 8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data streams.
short: 16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.
int: 32-bit integer type.
Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
3) Expressions involving the byte, short and int values are promoted
to int before calculation.
30
Data Types
long: 64-bit integer type.
Range: -9223372036854775808 to
9223372036854775807.
Example: long l = 10000000000000000;
Usage: 1) useful when int type is not large enough to hold the desired
value
float: 32-bit floating-point number.
Data Types
char: 16-bit data type used to store characters.
Range: 0 to 65536.
Example: char c = a;
Usage:
1) Represents both ASCII and Unicode character sets; Unicode defines a
character set with characters found in (almost) all human languages.
2) Not the same as in C/C++ where char is 8-bit and represents ASCII
only.
boolean: Two-valued type of logical values.
Range: values true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational operators, such as 1<2
2) required by branching expressions such as if or for
32
33
34
}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
35
36
Type Conversion
Size Direction of Data Type
Widening Type Conversion
Smaller Data Type Larger Data Type
37
Type Conversion
Widening Type Converstion
Implicit conversion by compiler automatically
38
Type Conversion
Narrowing Type Conversion
Programmer should describe the conversion explicitly
39
Type Conversion
40
Operators
Java operators are used to build value expressions.
Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise
Arithmetic assignments:
+=
v += expr;
v = v + expr ;
-=
v -=expr;
v = v - expr ;
*=
v *= expr;
v = v * expr ;
/=
v /= expr;
v = v / expr ;
%=
v %= expr;
v = v % expr ;
41
Operators
Arithmetic Operators:
+
op1 + op2
ADD
op1 - op2
SUBSTRACT
op1 * op2
MULTIPLY
op1 / op2
DIVISION
op1 % op2
REMAINDER
Relational operator:
==
Equals to
!=
Not equals to
>
Greater than
<
Less than
>=
<=
Operators
Logical operators:
&
Logical AND
op1 | op2
Logical OR
Short-circuit AND
||
op1 || op2
Short-circuit OR
! op
Logical NOT
op1 ^ op2
Logical XOR
&&
Relational operator:
~
~op
&
op1 |op2
op1 ^ op2
>>
<<
Operators Hierarchy
Operator
Order of
evaluation
Operation
( )
left - right
++ --
right - left
preincrement, predecrement
++ --
right - left
postincrement, postdecrement
left - right
left - right
= += -= *= /= right - left
%=
p re ce d e n ce
le ve l
1
3
4
o p e ra to r
+
*
/
%
+
+
=
assignment
o p e ra tio n
u n a ry p lu s
u n a ry m in u s
m u ltip lica tio n
d ivis io n
re m a in d e r
a d d itio n
s u b tra ctio n
s trin g
co n ca te n a tio n
a s s ig n m e n t
a s s o cia te s
R to L
L to R
L to R
R to L
44
Expression
System.out.println("value1 == value2");
45
Expression
The data type of the value returned by an expression depends on the
elements used in the expression.
The expression number = 0 returns an int because the assignment
operator returns a value of the same data type as its left-hand operand;
in this case, number is an int.
As you can see from the other expressions, an expression can return
other types of values as well, such as boolean or String.
The Java programming language allows you to construct compound
expressions from various smaller expressions as long as the data type
required by one part of the expression matches the data type of the
other.
Here's an example of a compound expression:
1*2*3
46
Enumerated type
3
47
Control Flow
Java control statements cause the flow of execution to advance and branch
based on the changes to the state of the program.
Control statements are divided into three groups:
48
Control Flow
Iteration Statements
Java iteration statements enable repeated execution of part of a program until a certain
termination condition becomes true.
Java provides three iteration statements:
1) while
2) do-while
3) for
Jump Statements
Java jump statements enable transfer of control to other parts of program.
Java provides three jump statements:
1) break
2) continue
3) return
In addition, Java supports exception handling that can also alter the control flow of a
program.
49
Compilation : javac
Execution: java
MyProgram.java
MyProgram
50
String[] args is a single parameter for the method. String[] is the type of the
parameter, indicating an array of Strings. args is the name of the parameter.
Parameters must be named.
51
Array
Array Creation
After declaration, no array actually exists.
In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
This creates a new array to hold size elements of datatype type, which
reference will be kept in the variable array-variable.
Array Indexing :
Later we can refer to the elements of this array through their indexes:
array-variable[index]
The array index always starts with zero!
The Java run-time system makes sure that all array indexes are in the correct
range, otherwise raises a run-time error.
52
Arrays
Array Initialization:
Arrays can be initialized when they are declared:
int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
Note :
1) there is no need to use the new operator
2) the array is created large enough to hold all specified elements
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays:
1) declaration: int array[][];
2) creation:
int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
53
System.out.print("Hello ");
System.out.println("world");
Console Input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String text = in.readLine();
Scanner sc = new Scanner(System.in);
int pop =sc.nextInt();
String preName = sc.nextLine();
String preAddr = sc.nextLine();
54
formatting output
print and println Methods:
Invoking print or println outputs a single value after converting the value using the
appropriate toString method.
We can see this in the Root example:
public class Root
{
public static void main(String[] args)
{
int i = 2;
double r = Math.sqrt(i);
System.out.print("The square root of ");
System.out.print(i);
System.out.print(" is ");
System.out.print(r);
System.out.println(".");
i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + "."); } }
Here is the output of Root:
The square root of 2 is 1.4142135623730951.
The square root of 5 is 2.23606797749979.
55
formatting output
format Method:
The format method formats multiple arguments based on a format string. The format
string consists of static text embedded with format specifiers; except for the format
specifiers, the format string is output unchanged.
56
Class
A class is a blueprint that defines the variables and methods common to all
objects of a certain kind.
Example: your dog is a object of the class Dog.
An object holds values for the variables defines in the class.
An object is called an instance of the Class
57
Class Definition
type instance-variable-n;
type method-name-1(parameter-list) { }
type method-name-2(parameter-list) { }
type method-name-m(parameter-list) { }
}
58
Object
Object Creation:
A variable is declared to refer to the objects of type/class String:
String s;
The value of s is null; it does not yet refer to any object.
A new String object is created in memory with initial abc value:
String s = new String(abc);
Now s contains the address of this new object.
59
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
}
}
class sum
{
int a,b,sum;
void get()
{
a=10;
b=5;
}
void sum()
{
sum=a+b;
//System.out.print("sum is "+sum);
}
}
class sum1
{
public static void main(String args[])
{
sum s1=new sum();
s1.get();
s1.sum();
60
Constructor
It is called immediately after the object is created but before the new operator
completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default return type of a class
When the class has no constructor, the default constructor automatically initializes
all its instance variables with zero.
61
Example: Constructor
class Box {
double width;
double height;
double depth;
Box() {
//constructor
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume()
{
return width * height * depth;
}
}
62
Parameterized Constructor
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth; }
}
Example Program : Constructors
63
Methods
Components:
1) type - type of values returned by the method. If a method does not return
any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists separated by commas
4) return value indicates what value is returned by the method.
64
Example: Method
Classes declare methods to hide their internal data structures, as well as for their
own internal use: Within a class, we can refer directly to its member variables:
Eg:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
65
Parameterized Method
66
Access Control
Private fields or methods for a class only visible within that class.
Private members are not visible within subclasses, and are not inherited.
Protected members of a class are visible within the class, subclasses
and also within all classes that are in the same package as that class.
67
Keyword this
Keyword this allows a method to refer to the object that invoked it.
Can be used by any object to refer to itself in any class method
It can be used inside any method to refer to the current object
68
Garbage Collection
Garbage collection is a mechanism to remove objects from memory when they are no
longer needed.
finalize() Method
A constructor helps to initialize an object just after it has been created.
In contrast, the finalize method is invoked just before the object is destroyed:
1) implemented inside a class as:
protected void finalize() { }
2) implemented when the usual way of removing objects from memory is insufficient,
and some special actions has to be carried out
69
Method Overloading
It is legal for a class to have two or more methods with the same name.
70
Example: Overloading
class OverloadDemo
{
void test()
{ System.out.println("No parameters");
void test(int a)
{
System.out.println("a: " + a);
71
Constructor Overloading
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{ width = w; height = h; depth = d; }
Box()
{ width = -1; height = -1; depth = -1; }
Box(double len)
{ width = height = depth = len;
double volume()
{ return width * height * depth; }
}
72
Parameter Passing
Two types of variables:
1) simple types
2) class types
Two corresponding ways of how the arguments are passed to
methods:
1) by value a method receives a copy of the original
value; parameters of simple types
2) by reference a method receives the memory address of
the original value, not the value itself;
parameters of class types
73
Call by value
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: );
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}
74
Call by reference
As the parameter hold the same address as the argument, changes to the object
inside the method do affect the object used by the argument:
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: );
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}
75
Recursion
1) all method parameters and local variables are allocated on the stack
2) arguments are prepared in the corresponding parameter positions
3) the method code is executed for the new arguments
4) upon return, all parameters and variables are removed from the stack
5) the execution continues immediately after the invocation point
76
Example: Recursion
class Factorial
{
int fact(int n)
{
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
}
}
77
String Handling
String is probably the most commonly used class in Java's class library.
The obvious reason for this is that strings are a very important part of
programming.
The first thing to understand about strings is that every string you create is
actually an object of type String. Even string constants are actually String
objects.
For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
Java defines one operator for String objects: +.
It is used to concatenate two strings. For example, this statement
String myString = "I" + " like " + "Java.";
results in myString containing "I like Java."
78
String Handling
1.
2.
3.
4.
5.
6.
7.
8.
9.
79
String Handling
1.
2.
3.
byte g etBytes() :Encodes this String into a sequence of bytes using the platform's
default charset, storing the result into a new byte array.
4.
5.
void getChars(int srcBeg in, int srcEnd, char[] dst, int dstBeg in): Copies
characters from this string into the destination character array.
80
String Handling
1.
2.
int indexOf(int ch) : Returns the index within this string of the first occurrence of
the specified character.
3.
int indexOf(int ch, int fromIndex) :Returns the index within this string of the
first occurrence of the specified character, starting the search at the specified index.
4.
int indexOf(String str): Returns the index within this string of the first occurrence
of the specified substring .
5.
int indexOf(String str, int fromIndex) :Returns the index within this string of the
first occurrence of the specified substring , starting at the specified index.
6.
7.
int lastIndexOf(int ch) :Returns the index within this string of the last occurrence
of the specified character.
81
String Handling
1. int lastIndexOf(int ch, intfromIndex) :
Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.
2. int lastIndexOf(String str):
Returns the index within this string of the rightmost occurrence of the specified
substring .
3. int lastIndexOf(String str, int fromIndex) :
Returns the index within this string of the last occurrence of the specified substring ,
searching backward starting at the specified index.
4. int length() : Returns the length of this string .
5. boolean matches(String regex): Tells whether or not this string matches the g iven
regular expression.
6. boolean regionMatches(boolean ignoreCase, int offset, String other, int ooffset, int
len) : Tests if two string regions are equal.
82
String Handling
1.
boolean reg ionMatches(int toffset, String other, int ooffset, int len) : Tests if
two string regions are equal.
2.
3.
String Handling
boolean startsWith(String prefix, int toffset): Tests if this string starts with the
specified prefix beg inning a specified index.
CharSequence subSequence(int beg inIndex, int endIndex) :Returns a new character
sequence that is a subsequence of this sequence.
String substring (int beg inIndex):Returns a new string that is a substring of this
string .
String substring (int beg inIndex, int endIndex): Returns a new string that is a
substring of this string .
char[] toCharArray() :Converts this string to a new character array.
String toLowerCase(): Converts all of the characters in this String to lower case using
the rules of the default locale.
String toLowerCase(Locale locale) :Converts all of the characters in this String to
84
lower case using the rules of the g iven Locale.
String Handling
String toString () : This object (which is already a string !) is itself returned.
String toUpperCase() :Converts all of the characters in this String to upper case using
the rules of the default locale.
85
UNIT - II
Objectives
To understand basic concepts of inheritance, polymorphism
To know the differences in interfaces and abstract classes
To know the creation and importing packages
86
TOPICS
Inheritance Inheritance hierarchies, super and sub classes,
Member access rules, super keyword, preventing inheritance: final
classes and methods, the Object class and its methods.
Package,
Inheritance
-The mechanism of deriving a new class from an existing class is
known as inheritance.
-Existing class is known as base class or parent class or super
class and new class is known as derived class or child class or sub
class.
88
Inheritance
Types of Inheritances:
1.-Single Inheritance
2.Multiple Inheritance
3.Hierarchical Inheritance
4.Multilevel Inheritance
89
Inheritance
Syntax of Derived class:
class subclass-name extends superclass-name {
// body of class
}
Remember
A class member that has been declared as private will remain
private to its class. It is not accessible by any code outside its
class, including subclasses.
Super Keyword
super has two general forms.
The first calls the superclass constructor.
The second is used to access a member of the superclass that has been
hidden, by a member of a subclass.
Using super to Call Superclass Constructors
A subclass can call a constructor method defined by its superclass by
use of the following form of super:
super(parameter-list);
parameter-list specifies any parameters needed by the constructor in
the superclass.
super( ) must always be the first statement executed inside a
subclass constructor.
92
Super Keyword
The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used.
general form:
super.member
Here, member can be either a method or an instance variable.
This second form of super is most applicable to situations in which member
names of a subclass hide members by the same name in the superclass.
Ex:
class A {
int i;
}
class B extends A {
int i;
B(int a, int b) {
super.i = a;
i = b;
}
93
Super Keyword
In a class hierarchy constructors are called in order of derivation, from
superclass to subclass.
super() must be the first statement executed in a subclass
constructor.
If super() is not used, the default constructor of each superclass will
be executed.
Implicitly default form of super ( super() ) will be invoked in each
94
95
96
// ...
98
Polymorphism
Polymorphism: to assign multiple meanings to the same method name
Implemented using late binding.
Late binding or dynamic binding (run-time binding):
Method to be executed is determined at execution time, not at compile
time.
Method Overriding
When a method in a subclass has the same
name
signature and
return type
as a method in its superclass, then the method in the subclass is
said to be overriden the method in the superclass.
When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
100
101
102
103
interfaces
interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body.
Any number of classes can implement an interface.
One class can implement any number of interfaces.
Defining an Interface
The general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Example:
interface Callback {
void
callback(int param);
}
Contd..
Implementing interfaces
Once an interface has been defined, one or more classes can implement that
interface.
The general form of a class that implements an interface :
access class classname [extends superclass][implements interface [,interface...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a
comma.
The methods that implement an interface must be declared as public.
The type signature of the implementing method must match exactly the type signature
specified in the interface definition
//Example for a class which contain both interface and non interface methods
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println(Non Interface
Method.");
}
interface Callback {
param);
void callback(int
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
//Callback cb;
//Client c=new Client();
//cb=c;
//cb.callback(42);
}
}
Output:
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as abstract.
abstract class Incomplete implements Callback{
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
Here, the class Incomplete does not implement callback( ) and must be
declared as abstract.
Any class that inherits Incomplete must implement callback( ) or be declared
abstract itself.
Variables in Interfaces
You can define variables in an interface but implicitly they are final variables.
That is you cant modify them.
FinalDemo.java
interface FinalDemo{
int i=100;
void show();
}
FinalTest.java
class FinalImpl implements FinalDemo{
public void show(){
System.out.println("FinalTest :Show()");
}
}
class FinalTest{
public static void main(String sree[]){
FinalImpl fi=new FinalImpl();
fi.show();
//fi.i=200; cant assign a value to variable i
System.out.println("FinalDemo Varaible i :"+fi.i);
}
}
Output:
FinalTest :Show()
FinalDemo Varaible i :100
System.out.println("Implement
meth2().");
}
public void meth3() {
System.out.println("Implement
meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new
MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Output:
Implement meth1().
Implement meth2().
Implement meth3().
interface Callback {
void callback(int param);
}
class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}
Output:
callback called with 42
Another version of callback
p squared is 1764
Class Vs Interface
The methods of an Interface are all abstract methods. They cannot have bodies.
An interface can only define constants.
You cannot create an instance from an interface.
Interfaces have no direct inherited relationship with any particular class, they are
defined independently.
A class can implement more than one interface. By contrast, a class can only
inherit a single superclass (abstract or otherwise).
When an object class is written, it is the duty of the programmer to provide sub classes
to it.
An interface is written when the programmer wants to leave the implementation to the
third party vendors.
An abstract class contains some abstract methods and also some concrete methods.
An interface contains only abstract methods.
All the abstract methods of the abstract class should be implemented in its sub
classes.
All the (abstract) methods of the interface should be implemented in its
implementation classes.
Interfaces have no direct inherited relationship with any particular class, they are
defined independently. Interfaces themselves have inheritance relationship among
themselves.
Uses of Interface
To reveal an object's programming interface (functionality of the object) without
revealing its implementation.
This is the concept of encapsulation.
The implementation can change without affecting the caller of the
interface.
import java.util.Scanner;
interface GeometricShape{
void area();
void perimeter();
}
class ExecuteMainA{
public static void main(String args[]){
Triangle t=new Triangle();
t.area();
t.perimeter();
Circle c=new Circle();
c.area();
c.perimeter();
Rectangle r=new Rectangle();
r.area();
r.perimeter();
}
}
Inner Classes
The class that includes the inner class is called the outer class
There is no particular location where the definition of the inner
class (or classes) must be place within the outer class
Placing it first or last, however, will guarantee that it is easy to find
129
130
Inner/Outer Classes
131
They can make the outer class more self-contained since they are
defined inside a class
Both of their methods have access to each other's private methods
and instance variables
132
Within the definition of the inner or outer classes, the modifiers public and
private are equivalent
133
134
135
136
OuterClassName.this.methodName()
137
138
OuterClass.InnerClass innerObject =
new OuterClass.InnerClass();
innerObject.nonstaticMethod();
innerObject.staticMethod();
OuterClass.InnerClass.staticMethod();
139
140
If an object of the inner class is created within a static method of the outer
class
If the inner class must have static members
141
142
143
144
145
146
Anonymous Classes
If an object is to be created, but there is no need to name the object's class,
then an anonymous class definition can be used
The class definition is embedded inside the expression with the new
operator
An anonymous class is an abbreviated notation for creating a simple local
object "in-line" within any expression, simply by wrapping the desired
code in a "new" expression.
Anonymous classes are sometimes used when they are to be assigned to a
variable of another type
The other type must be such that an object of the anonymous class is also
an object of the other type
The other type is usually a Java interface
Not every inner class should be anonymous, but very simple "one-shot"
local objects are such a common case that they merit some syntactic sugar.
147
Anonymous Classes
148
Anonymous Classes
149
Anonymous Classes
150
Packages
( Putting Classes Together )
Introduction
The main feature of OOP is its ability to support the reuse of code:
Using the classes ( directly )
Extending the classes (via inheritance)
Extending interfaces
The features in basic form limited to reusing the classes within a program.
What if we need to use classes from other programs without physically copying
them into the program under development ?
Defining Packages
Packages are Javas way of grouping a number of related classes and/or interfaces
together into a single unit. That means, packages act as containers for classes.
In packages classes can be unique compared with classes in other packages, i.e,
two classes in two different packages can have the same name. If there is a
naming clash, then classes can be accessed with their fully qualified name.
Contd..
In general, a Java source file can contain any (or all) of the following four
internal parts:
A single package statement (optional).
Any number of import statements (optional).
A single public class declaration (required).
Any number of classes private to the package (optional).
java.lang
Contains classes for primitive types, strings, math functions,
threads, and exception
java.util
Contains classes such as vectors, hash tables, date etc.
java.io
Stream classes for I/O
java.awt
Classes for implementing GUI windows, buttons, menus etc.
java.net
Classes for networking
java.applet
Classes for creating and implementing applets
Creating Packages
To create a package is quite easy: simply include a package command as the first
statement in a Java source file.
Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default
package, which has no name.
package pkgname;
package MyPackage;
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
More than one file can include the same package statement.
You can create a hierarchy of packages.
To do so, simply separate each package name from the one above it by use of a
period.
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development
system.
package mypackage.mypackageA;
public class S1
{
public S1( )
{
System.out.println("This is Class S1");
}
}
Name the source file as S1.java and compile it and
store the S1.class file in mypackageA directory
package mypackage.mypackageA;
public class S2
{
public S2( )
{
System.out.println("This is Class S2");
}
}
Name the source file as S2.java and compile it and
store the S2.class file in mypackageA directory
package mypackage.mypackageB.IJK;
public class A
{
public A( )
{
System.out.println("This is Class A in IJK");
}
}
Name the source file as A.java and compile it and
store the A.class file in IJK directory
java.lang.Math.sqrt(x);
import java.lang.Math
Math.sqrt(x);
import
package.class;
Implicit in all programs:
import
java.lang.*;
package statement(s)import
must appear
first
package.*;
// A simple package
//AccountBalance.java
class AccountBalance {
package MyPack;
public static void main(String args[]) {
class Balance {
Balance current[] = new Balance[3];
String name;
current[0] = new Balance("K. J. Fielding", 123.23);
double bal;
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
Balance(String n, double b){
for(int i=0; i<3; i++)
name = n;
current[i].show();
bal = b;
}
}
}
void show() {
if(bal<0)
System.out.print("-->
");
//To compile
System.out.println(name + ":
javac AccountBalance.java
$" + bal);
}
//To run
}
java MyPack.AccountBalance
//java AccountBalance
invalid
Access Control
Java addresses four categories of visibility for class members:
Subclasses in the same package.
A class has only two possible access levels: default and public.
//VarProtection.java
package pack1;
public class VarProtection {
int n = 1;
private int pri = 2;
protected int pro = 3;
public int pub = 4;
public VarProtection() {
System.out.println("Individual class constructor");
System.out.println("default value is: " + n);
System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}
To Compile:
d:\>javac d . VarProtection.java
//SameSub .java:
package pack1;
class SameSub extends VarProtection{
SameSub(){
System.out.println("subclass constructor");
System.out.println("default value is: " + n);
// System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}
To Compile:
d:\>javac d . SameSub.java
// SameDiff.java
package pack1;
class SameDiff{
SameDiff(){
VarProtection v1 = new VarProtection();
System.out.println("Delegationclass constructor");
System.out.println("default value is: " +v1. n);
// System.out.println("private value is: " +v1. pri);
System.out.println("protected value is: " +v1. pro);
System.out.println("public value is: " + v1.pub);
}
}
To Compile:
d:\>javac d . SameDiff.java
//OtherSub.java
package pack2;
import pack1.*;
class OtherSub extends VarProtection{
OtherSub(){
System.out.println("Different Package subclass constructor");
//System.out.println("default value is: " + n);
// System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}
To Compile:
d:\>javac d . OtherSub.java
// OtherDiff.java
package pack2;
import pack1.*;
class OtherDiff{
OtherDiff(){
VarProtection v2=new VarProtection();
System.out.println("Different Package non-subclass
constructor");
// System.out.println("default value is: " +v2. n);
// System.out.println("private value is: " + v2.pri);
// System.out.println("protected value is: " + v2.pro);
System.out.println("public value is: " + v2.pub);
}
}
To Compile:
d:\>javac d . OtherDiff.java
To Compile:
// Demo package p1.
d:\>javac d . MainTest.java
package pack1;
To Run:
class MainTest{
d:\>java pack1.MainTest
public static void main(String
args[]){
VarProtection v=new
VarProtection();
SameDiff s2=new
SameDiff();
SameSub s1=new
SameSub();
package pack2;
}
import pack1.*;
}
class OtherMainTest{
public static void main(String
args[]){
OtherSub os=new
OtherSub();
To Compile:
OtherDiff od=new
d:\>javac d . OtherMainTest.java
OtherDiff();
To Run:
}
d:\>java pack2.OtherMainTest
}
Importing Packages
There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package.
Java includes the import statement to bring certain classes, or entire packages,
into visibility.
Once imported, a class can be referred to directly, using only its name.
In a Java source file, import statements occur immediately following the
package statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
import java.util.Date;
import java.io.*;
All of the standard Java classes included with Java are stored in a package called
java.
The basic language functions are stored in a package inside of the java package
called java.lang.
Normally, you have to import every package or class that you want to use, but
java.lang is implicitly imported by the compiler for all programs.
This is equivalent to the following line being at the top of all of your programs:
import java.lang.*;
When a package is imported, only those items within the package declared as public will
be available to non-subclasses in the importing code. For example, if you want the
Balance class of the package MyPack shown earlier to be available as a stand-alone
class for general use outside of MyPack, then you will need to declare it as public and
put it into its own file, as shown here:
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
As an experiment, remove the public specifier from the Balance class and then
try compiling TestBalance. As explained, errors will result.
package sortapp;
public interface SortInterface{
void sort();
}
package sortapp.subsortapp;
import sortapp.*;
public class SortImpl implements SortInterface{
public void sort(){
System.out.println("linear sort is used");
}
}
package searchingapp;
public interface SearchInterface{
void search();
}
package searchingimpl;
import searchingapp.*;
public class SearchImpl implements SearchInterface{
public void search(){
System.out.println("lenear search is used");
}
}
import sortapp.subsortapp.SortImpl;
import searchingimpl.SearchImpl;
public class ExecutePackage
{
public static void main(String a[]){
SortImpl s1=new SortImpl();
s1.sort();
SearchImpl s2=new SearchImpl();
s2.search();
}
}
2.
III UNIT
Exception handling Dealing with errors, benefits of exception
handling, the classification of exceptions- exception hierarchy,
checked exceptions and unchecked exceptions, usage of try,
catch, throw, throws and finally, re throwing exceptions, exception
specification, built in exceptions, creating own exception sub
classes.
Multithreading - Differences between multiple processes and
multiple threads, thread states, creating threads, interrupting
threads, thread priorities, synchronizing threads, inter-thread
communication, producer consumer pattern.
188
Objectives
To know what is exception and what is exception handling.
To distinguish exception types: Error (fatal) vs. Exception (nonfatal), and checked vs. uncheck exceptions.
To declare exceptions in the method header.
To throw exceptions out of a method.
To write a try-catch block to handle exceptions.
To explain how an exception is propagated.
To rethrow exceptions in a try-catch block .
To use the finally clause in a try-catch block.
To know when to use exceptions.
To know differences between multiple processes and multiple
threads
To know thread states
To know the creating threads, interrupting threads
To know thread priorities
To know the synchronizing threads
To know inter-thread communication producer consumer pattern.
189
Logical Errors: These are the errors committed by the programmer in the
logic of the program. These errors are not detected by the compiler or
interpreter.
190
Exception
The Runtime error is called Exception.
191
Exception Handling
During a Program execution an unexpected situation such as inability to
192
Exception Handling
In java Exceptions are objects. There is a predefined class called Exception
in java.lang package. This is the super class for all exceptions.
Ex: 1. class ExceptionDemo
2. {
3.
public static void main(String args[])
4.
{
5.
int a=5/0;
6.
System.out.println(a=+a);
7.
}
8. }
The division of any value by zero is not defined in java. So this line (5th
line)
will throw the Divide by Zero Exception.
At Line no.5 an Arithmetic Exception class object is created and thrown
out of the main method and the execution stops.
193
194
195
Exception Hierarchy
The Exception hierarchy consists of all possible exceptions that can occur
in a java program.
The Throwable is the super class for all exceptions and it is the subclass
of Object class.
The Throwable inturn has two subclasses Exception and Error.
196
Types of Exceptions
A. Unchecked Exceptions
All Exceptions that extend the RuntimeException or any one of its
subclass are unchecked exceptions
Unchecked Exceptions are unchecked by compiler.
Whether you catch the exception or not compiler will pass the compilation
process.
If Unchecked exception is caught then exception handling code will be
executed and programs execution continues.
If Unchecked exception is not caught then java interpreter will provide the
default handler. But in this case execution of the program will be stopped
by displaying the name of the exceptions object.
197
UncheckedExceptions Example
class Exceptiondemo1
{
public static void main(String arhs[])
throws ArithmeticException
{
int a=10;
int b= 5;
int c =5;
No Need to mention for
int x = a/(b-c);
Unchecked Exceptions
System.out.println("c="+c);
int y = a/(b+c);
System.out.println("y="+y);
Can Throw an Exception
}
} D:\java>javac Exceptiondemo1.java << Compilation Step Pass>>
D:\java>java Exceptiondemo1
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Exceptiondemo1.main(Exceptiondemo1.java:8)
199
D:\java>javac Exceptiondemo2.java
D:\java>java Exceptiondemo2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Exceptiondemo2.main(Exceptiondemo2.java:5)
D:\java>java Exceptiondemo2 pankaj
Exception in thread "main" java.lang.NumberFormatException: For input string:
"pankaj at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:12 24)
at java.lang.Double.parseDouble(Double.java:482)
at Exceptiondemo2.main(Exceptiondemo2.java:5)
200
Unchecked Exception
Put the Related/Dependent Statements in try block
class extest
{
public static void main(String args[])
{
try
{
int a =Integer.parseInt(args[0]);
int b = a+10;
System.out.println("b="+b);
}
catch(Exception e) {}
}
}
201
Types of Exceptions
B. checked Exceptions
202
203
Checked Exceptions
int a = Integer.parseInt(in.readLine());
int b = Integer.parseInt(in.readLine());
System.out.println("Sum is :"+(a+b));
}
}
Exceptiondemo3.java:9: unreported exception java.io.IOException; must be caught or declared
to be thrown
int a = Integer.parseInt(br.readLine());
^
Exceptiondemo3.java:10: unreported exception java.io.IOException; must be caugh or
declared to be thrown
int b = Integer.parseInt(br.readLine());
^
205
int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println("Sum is :"+(a+b));
}
}
1.throws clause is used with methods to indicate type of Exception a method can throw
2.Specifically required for Checked Exceptions [ To Pass Compilation process]. It can/may be used
for unchecked exceptions also.
3.A method can throw as many exceptions.
206
Method 2 << Put the statements in try catch block and catch >>
import java.io.*;
class Exceptiondemo3
{
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);
try {
int a = Integer.parseInt(in.readLine());
int b = Integer.parseInt(in.readLine());
System.out.println("Sum is :"+(a+b));
}
catch(IOException e) { }
}
}
207
Exception Handling
Exception Handling Requires the Following four steps
1.Finding the problem (Identify the statements whose execution
may result in Exception. Put all those statements in a try{..}
block)
2.Inform that an exception is thrown (Throw the Exception)
3.Receive the exception ( Catch the exception using catch{..}
block)
4.Provide exception handling code in catch block.
208
Important Points :
1.try {} block may have one or multiple
statements.
2. try{} block may throw a single type of
Exception or multiple exceptions. But at a
time it can throw only single type of
exception.
3. There can be multiple catch() { .. } blocks
associated with single try{} block.
4. If try{} block can throw multiple exceptions
then user should catch all exceptions. (one
catch block for each type of exception)
209
Catching an Exception
class Exceptiondemo1
{
public static void main(String args[])
{
int a=10;
int b= 5;
int c =5;
try
{
int x = a/(b-c);
D:\java>java Exceptiondemo1
System.out.println("c="+c);
java.lang.ArithmeticException: / by zero
}
y=1
catch(ArithmeticException e)
{
System.out.println(e.toString());
}
int y = a/(b+c);
System.out.println("y="+y);
}
}
210
catch(ArithmeticException e)
{
System.out.println(e.toString());
}
catch(NumberFormatException e)
{
System.out.println(e.toString());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
}
System.out.println("Hello This is Exception Test");
} // End of main() method
}// End of class Exceptiondemo4
211
OUTPUT
What will be o/p if you execute it like
1.Java Exceptiondemo4
2.java Exceptiondemo4 1
3.3. java exceptiondemo4 oop
212
213
or
try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
}
catch(AException e) {
catch(BException e) {
catch(CException e) {
catch(DException e) {
.
.
.
.
}
}
}
}
214
class nestedtry
{
public static void main(String args[])
{
int a[] = { 2,5,6};
try // outer try
{
int b = Integer.parseInt(args[0]);
try // inner try
{
int c[] = { 4,5,6};
int d = c[b]/(c[b]-4);
} // End of inner try
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Inner try");
}
catch(ArithmeticException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Inner try");
}
} // End of outer try
215
D:\java>java nestedtry
Exception :
java.lang.ArrayIndexOutOfBoundsException: 0
By Outer try
D:\java>java nestedtry 4
Exception : java.lang.ArrayIndexOutOfBoundsException: 4
By Inner try
216
XException
YException
ZException
ZException
extends
extends
extends
extends
RunTimeException { }
AritmeticException { }
ArrayIndexOutOfException { }
IndexOutOfBoundsException { }
217
218
EXAMPLE 1:
class InvalidBOXException extends RuntimeException
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
Optional as InvalidBOXException is
{
Unchecked
private double length;
private double width;
private double height;
BOX(double l, double w, double h) throws InvalidBOXException
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Invalid BOX Object creation");
length = l;
width = w;
height = h;
}
219
System.out.println(Area of b2:+b2.Area());
}
}
D:\java\bin>java exceptiontest1
An attempt is made to create an Invalid BOx object
Exception in thread "main" InvalidBOXException: Inavlid BOX Object
creation
at BOX.<init>(exceptiontest1.java:18)
at exceptiontest1.main(exceptiontest1.java:35)
220
object
Area of b2:220.0
221
<RUNTIME Error>
D:\java\bin>java exceptiontest1
Exception in thread "main"
java.lang.NullPointerException
at
exceptiontest1.main(exceptiontest1.java:3
6)
222
Checked Exceptions
Make your exception class extends Exception class or any one of its
subclass except RumtimeException.
Checked Exceptions needs to either caught or informed by use of throws
clause
Note down that throw clause is used to throw the exception where as
throws clause is used to inform that an exception is thrown by the method.
Throw clause is used inside method body where as throws clause is used
with first line of the method.
Throws clause can be used to inform both type of exceptions. But in case a
method is throwing a unchecked exception then it is not compulsory to
inform.
In case a method is throwing a checked Exception, then it has either to
caught the exception or informs by using throws clause or it can do both.
223
EXAMPLE 1:
class InvalidBOXException extends Exception
Checked Exception
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
{
Any Method or constructor which throws an
private double length;
checked Type Exception must inform it thru
private double width;
throws clause
private double height;
BOX(double l, double w, double h)
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Inavlid BOX Object creation");
length = l;
width = w;
height = h;
}
224
EXAMPLE 1:
class InvalidBOXException extends Exception
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
{
private double length;
private double width;
private double height;
BOX(double l, double w, double h) throws InvalidBOXException
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Inavlid BOX Object creation");
length = l;
width = w;
height = h;
}
226
D:\java\bin>java exceptiontest1
An attempt is made to create an Invalid BOx object
Exception in thread "main" InvalidBOXException: Inavlid BOX Object creation
at BOX.<init>(exceptiontest1.java:18)
at exceptiontest1.main(exceptiontest1.java:36)
227
228
try
{
..
..
.
}
catch(.)
{ . }
catch(..)
{ . }
..
..
finally
{
..
..
}
229
Example(finally clause)
class ex10
{
public static void main(String args[])
{
int a=10;
int b = 20;
try
{
int b1=Integer.parseInt(args[0]);
int x = a/(a-b1);
try
{
int y = b/(b-b1);
}
finally
{
System.out.println("Inner Block executed");
finally
}
{
}
System.out.println("Outer Block executed");
}
}
230
}
Output
D:\java\bin>java ex10
Outer Block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ex10.main(ex10.java:9)
D:\java\bin>java ex10 45
Inner Block executed
Outer Block executed
D:\java\bin>java ex10 10
Outer Block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ex10.main(ex10.java:10)
D:\java\bin>java ex10 20
Inner Block executed
Outer Block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ex10.main(ex10.java:13)
231
Multithreading
There is no communication between processors Within the process threads are communicated
directly
232
234
Thread()
Created
start()
notify()
Runnable
Blocked
sleep()
wait()
Dead
235
Thread1
start()
Thread2
Thread Object
run()
236
Thread()
Created
start()
notify()
Runnable
Blocked
sleep()
wait()
Dead
237
Creating Threads
Thread class constructors:
1.Thread ()
2.Thread (String Threadname )
3.Thread (Runnable obj)
4.Thread (Runnable obj, String name )
5.Thread (ThreadGroup tg,String Threadname )
Methods :
1. String getName (): It obtains the name of the thread .
2. Void setName (String str): It sets the name of the thread .
3. Int getPriority (): It obtains the priority of the thread .
4. Void set Priority(int ) : It sets the priority of the thread
5. Boolean is Alive( ): Determines if a thread is still running or not .It returns
true if the thread upon which it is called is still running ,else false.
238
Creating Threads
Thread class constructors:
1.Thread ()
2.Thread (String Threadname )
3.Thread (Runnable obj)
4.Thread (Runnable obj, String name )
5.Thread (ThreadGroup tg,String Threadname )
Methods :
1. String getName (): It obtains the name of the thread .
2. Void setName (String str): It sets the name of the thread .
3. Int getPriority (): It obtains the priority of the thread .
4. Void set Priority(int ) : It sets the priority of the thread
5. Boolean is Alive( ): Determines if a thread is still running or not .It returns
true if the thread upon which it is called is still running ,else false.
239
Creating Threads
Thread class constructors:
1.Thread ()
2.Thread (String Threadname )
3.Thread (Runnable obj)
4.Thread (Runnable obj, String name )
5.Thread (ThreadGroup tg,String Threadname )
Methods :
1. String getName (): It obtains the name of the thread .
2. Void setName (String str): It sets the name of the thread .
3. Int getPriority (): It obtains the priority of the thread .
4. Void set Priority(int ) : It sets the priority of the thread
5. Boolean is Alive( ): Determines if a thread is still running or not .It returns
true if the thread upon which it is called is still running ,else false.
240
241
After you create a class that implements Runnable, you will instantiate an object of
type Thread from within that class.
Thread constructors:
Thread(Runnable threadOb, String threadName)
After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread.
start( ) executes a call to run( ).
Syntax:
void start()
Thread1
start()
Thread2
Thread Object
Runnable Object
run()
run()
242
Threads
Extending Threads class:
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that 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.
Notice the call to super( ) inside NewThread. This invokes the following form of the
Thread constructor:
public Thread(String threadName)
Here, threadName specifies the name of the thread.
243
Multiple Threads
Creating Multiple Threads
We can create as many threads as needed .
244
Thread Priorities
Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run. In theory, higher-priority threads get more CPU time than lower-priority
threads.
It is possible to set priority to each thread b the user, by using the setPriority( ) method,
which is a member of Thread.
Syntax:
final void setPriority(int level)
level : System defined thread priorities :
Thread.MIN_PRIORITY
1
Thread.MAX_PRIORITY
10
Thread.NORM_PRIORITY
5
The default priority is Thread.NORM_PRIORITY
These Priorities are defined as static final variables within Thread .
PriorityThread
245
Synchronizing Threads
When two or more threads need access to a shared resource, they need some
way to ensure that the resource will be used by only one thread at a time. The
process by which this is achieved is called synchronization.
In Java, every object has a lock.
To obtain the lock, you must synchronize with the object.
The simplest way to use synchronization is by declaring one or more methods to
be synchronized
When a synchronized method is invoked, the calling thread attempts to obtain the
lock on the object.
if it cannot obtain the lock, the thread goes to sleep until the lock becomes
available
Once the lock is obtained, no other thread can obtain the lock until it is released.
ie, the synchronized method terminates
When a thread is within a synchronized method, it knows that no other
synchronized method can be invoked by any other thread
Therefore, it is within synchronized methods that critical data is updated
246
notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c
The highest priority thread will run first.
247
Thread Groups
248
Thread Groups
Methods that Operate on the ThreadGroup
getMaxPriority(), setMaxPriority(int)
getName() // name of the thread
getParent()
parentOf(ThreadGroup) // boolean
toString()
activeCount(),
activeGroupCount() // # of active descendent threads, and groups
suspend(); //deprecated; suspend all threads in this group.
resume();
stop();
249
Daemon Thread
Daemon thread in Java :
Are those thread which runs in background and mostly created by JVM for
performing background task like Garbage collection
Difference between Daemon and Non Daemon(User Threads)
In one line main difference between daemon thread and user thread is that as
soon as all user thread finish execution java program or JVM terminates itself,
JVM doesn't wait for daemon thread to finish there execution.
As soon as last non daemon thread finished JVM terminates no matter how
many Daemon thread exists or running inside JVM.
Daemon Thread are treated differently than User Thread when JVM terminates,
finally blocks are not called, and JVM just exits.
250
Unit-4
Legacy Implementations - The collection classes from earlier releases, Vector and
Hashtable, have been retrofitted to implement the collection interfaces.
Array Utilities - Utility functions for arrays of primitives and reference objects. Not,
strictly speaking, a part of the Collections Framework, this functionality is being
added to the Java platform at the same time and relies on some of the same
infrastructure.
Benefits
Helpful to developers by providing all standard data structures
algorithms to let the developer concentrate more on
functionality rather than the lower level details
Collection
Set
SortedSet
List
Map
Queue
SortedMap
AbstractCollection
AbstractList
AbstractMap
AbstractQueue
AbstractSequential
AbstractSet
ArrayDeque
ArrayList
Arrays Linked
BitSet Linked
Calendar
Collections
Currency
Date
Dictionary
EnumMap
EnumSet
EventListenerProxy
EventObject
FormattableFlags
Formatter
GregorianCalendar
List HashMap
HashSet
Hashtable
IdentityHash
HashMap
HashSet
LinkedList
ListResourceBundle
Locale
Observab
PriorityQueue
Properties
PropertyPermission
PropertyResourceBundle
Random
ResourceBundle
Scanner
ServiceLoader
SimpleTimeZone
Stack
StringTokenizer
Map Timer
TimerTask
TimeZone
TreeMap
TreeSet
UUID
Vector
WeakHashMap
Collection
List Queue
Comparator
ListIterator
RandomAccess
Deque (Added by Java SE 6.)
Map Set
Enumeration
Map.Entry
SortedMap
EventListener
NavigableMap (Added by Java SE 6.)
SortedSet
Formattable
NavigableSet (Added by Java SE 6.)
Iterator
Observer
ArrayList
ArrayList Class:
ArrayList Implements a dynamic array by extending AbstractList.
The ArrayList class extends AbstractList and implements the List interface.
ArrayList is a generic class that has this declaration:
class ArrayList<E>
Here, E specifies the type of objects that the list will hold.
ArrayList
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list.
The second constructor builds an array list that is
initialized with the elements of the collection c.
The third constructor builds an array list that has the
specified initial capacity.
The capacity is the size of the underlying array that is
used to store the elements.
The capacity grows automatically as elements are
added to an array list.
// Demonstrate ArrayList.
ArrayList
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +al.size());
System.out.println("Contents of al: " + al);
}
}
ArrayList
The output from this program
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Vector
Vector implements a dynamic array.
It is similar to ArrayList, but with two differences:
Vector is synchronized, and it contains many legacy methods
that are not part of the Collections.
Framework.
Vector was reengineered to extend AbstractList and to
implement the List interface.
A Vector can have its contents iterated by the enhanced for
loop.
Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection<? extends E> c)
The first form creates a default vector, which has an initial size of 10.
The second form creates a vector whose initial capacity is specified by
size.
The third form creates a vector whose initial capacity is specified by
size and whose increment is specified by incr.
The increment specifies the number of elements to allocate each time
that a vector is resized upward.
The fourth form creates a vector that contains the elements of
collection c.
int capacityIncrement;
int elementCount;
Object[ ] elementData;
The increment value is stored in capacityIncrement.
The number of elements currently in the vector is stored in
elementCount.
The array that holds the vector is stored in elementData.
v.addElement(7);
System.out.println("Current capacity: " +v.capacity());
v.addElement(9);
v.addElement(10);
System.out.println("Current capacity: " +v.capacity());
v.addElement(11);
v.addElement(12);
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3.");
// Enumerate the elements in the vector.
// Use an enhanced for loop to display contents.
System.out.println("\nElements in vector:");
for(int i : v)
System.out.print(i + " ");
System.out.println();
}
Output:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3
Elements in vector:
1 2 3 4 5 6 7 9 10 11 12
UNIT-5
272
Events
An event is an Object that describes a state change in a Source.
Some of the activities that causes event to be generated are :
*Pressing a Button.
*Entering a character through Key Board.
*Selecting an item form a list etc.
Events may also occur that are not directly caused by interactions with
a user interface.
For example:
* An event may be generated when a timer expires
* A counter exceeds a value
273
Event Sources
A Source is an object that generates an event.
Some general Event Sources are:
Button
CheckBox
List
MenuItem
Window
TextItems,etc
274
Event Sources
A source must register listeners in order for the listeners to
receive notifications about a specific type of event. Each type
of event has its own registration method.
For implementing event listener we have to import the following
Statement:
import java.awt.event.*;
275
Event Sources
Here is a general form for adding a listener to an event source :
Public void assTyprListener(TypeEvent e)
* Type is the name of the event.
* e is the reference of the event listener.
Some sources may allow only one listener to register. The general form of such
a method is :
public void addTypeListener(TypeListener el)throws
java.util.TooManyListenersException
276
Event Sources
Some of the user interface components that can generate the events.
Event
Source Description
Button
Check box
Choice
List
Menu
Item Generates action events when a menu item is selected; generates item events
when a checkable menu item is selected or deselected.
Scroll bar
Text
components
Window
277
Event Classes
There are a number of event classes provided by
java.But we will discuss only some AWT event classes
here.
At the root of the Java event class hierarchy is
EventObject, which is in java.util. It is the
superclass for all events. Its one constructor is shown
here:
EventObject(Object src)
Here, src is the object that generates this event.
278
Event Classes
EventObject contains two methods:
getSource( )
toString( )
getSource( ): Returns the source of the event. Its
general form is shown here:
Object getSource( )
toString( ): Returns the string equivalent of the event.
Its general form is shown here:
String toString()
279
Event Classes
EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT events that are
handled by the delegation event model.
280
Event Classes
Some AWT Event classes are listed below.
Event
Class Description
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
Generated when a check box or list item is clicked; also occurs when a choice selection is
made or a checkable menu item is selected or deselected.
KeyEvent
MouseEvent
Generated when the mouse is dragged, moved, clicked, pressed, or released;also generated
when the mouse enters or exits a component.
MouseWheelEvent
TextEvent.
WindowEvent
281
Event Listeners
A Listener is an object that is notified when an event
occurs.
It has two major requirements.
First, it must have been registered with one or more
sources to receive notifications about specific types of
events.
Second, it must implement methods to receive and
process these notifications.
For example:
MouseMotionListener Interface define two events:
*. When mouse is dragged.
* When mouse is moved.
282
Event Listeners
Interface
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
MouseWheelListener
TextListener
WindowFocusListener
WindowListener
Description
Defines one method to receive action events
Defines one method to receive adjustment events
Defines four methods to recognize when a component is hidden,
moved, resized, or shown.
Defines two methods to recognize when a component is added to
or removed from a container
Defines two methods to recognize when a component gains or loses
keyboard focus.
Defines one method to recognize when the state of an item changes
Defines three methods to recognize when a key is pressed, released,
or typed.
Defines five methods to recognize when the mouse is clicked, enters
a component, exits a component, is pressed, or is released.
Defines two methods to recognize when the mouse is dragged or
moved.
Defines one method to recognize when the mouse wheel is moved.
Defines one method to recognize when a text value changes.
Defines two methods to recognize when a window gains or loses
input focus.
Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
283
285
286
287
288
289
For ex:
Somecomponent.addActionListener(instance of myclasss);
Include code that implements the methods in listener interface.
For ex:
public void actionPerformed(ActionEvent e)
{
//code that reacts to the action
}
290
291
292
293
294
295
296
297
298
299
300
302
InputEvent Class:
The abstract class InputEvent is a subclass of ComponentEvent
and is the superclass for component input events. Its subclasses are
KeyEvent and MouseEvent.
The InputEvent class defines several integer constants.
Actual Modifiers:
ALT_MASK
BUTTON2_MASK
META_MASK
ALT_GRAPH_MASK
BUTTON3_MASK
SHIFT_MASK
BUTTON1_MASK
CTRL_MASK
Extended Modifiers:
ALT_DOWN_MASK
BUTTON2_DOWN_MASK
META_DOWN_MASK
ALT_GRAPH_DOWN_MASK
BUTTON3_DOWN_MASK
SHIFT_DOWN_MASK
BUTTON1_DOWN_MASK
CTRL_DOWN_MASK
303
304
305
306
307
There are many other integer constants that are defined by KeyEvent.
For example, VK_0 through VK_9 and
VK_A through VK_Z define the ASCII equivalents of the
numbers and letters.
Here are some others: (Vk-Virtual Key)
VK_ALT
VK_DOWN
VK_LEFT
VK_RIGHT
VK_CANCEL
VK_ENTER
VK_PAGE_DOWN
VK_SHIFT
VK_CONTROL
VK_ESCAPE VK_PAGE_UP
VK_UP
308
309
310
There are eight types of mouse events. The MouseEvent class defines
the following integer constants that can be used to identify them:
MOUSE_CLICKED
MOUSE_DRAGGED
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
MOUSE_PRESSED
MOUSE_RELEASED
MOUSE_WHEEL
311
312
313
It is a subclass of MouseEvent.
Not all mice have wheels. Mouse wheels are used for scrolling.
MouseWheelEvent defines these two integer constants:
314
316
317
318
319
320
321
322
ActionListener Interface:
This interface defines the actionPerformed( ) method
that is invoked when an action event
occurs.
Synatx:
void actionPerformed(ActionEvent ae)
AdjustmentListener Interface:
This interface defines the adjustmentValueChanged( )
method that is invoked when an adjustment event occurs.
Syntax:
void adjustmentValueChanged(AdjustmentEvent ae)
323
ComponentListener Interface:
This interface defines four methods that are invoked when a
component is resized, moved,
shown, or hidden.
Synatx:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerListener Interface:
This interface contains two methods. When a component is
added/removed to a container.
Syntax:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
324
FocusListener Interface:
325
KeyListener Interface:
This interface defines three methods. The methods are
invoked when a key is pressed and released or typed.
Synatx:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Interface:
This interface defines five methods. If the mouse is pressed
and released or When the mouse enters a component or
When it leaves.
Synatx:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
326
MouseMotionListener Interface:
This interface defines two methods. These methods called
when mouse is dragged or when the mouse is moved multiple
Syntax:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
MouseWheelListener Interface:
This interface defines the mouseWheelMoved( ) method that
is invoked when the mouse wheel is moved.
Syntax:
void mouseWheelMoved(MouseWheelEvent mwe)
327
TextListener Interface:
328
WindowListener Interface:
This interface defines seven methods. These methods are
invoked when a window is activated or deactivated or iconified
or deiconified,or window is opened or closed.
Syntax:
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
329
330
331
332
333
334
335
336
337
Listener Interface
ComponentAdapter
ComponentListener
ContainerAdapter
ContainerListener
FocusAdapter
FocusListener
KeyAdapter
KeyListener
MouseAdapter
MouseListener
MouseMotionAdapter
MouseMotionListener
WindowAdapter
WindowListener
338
Applets:
340
343
Applet
Simple Applet Display Methods:
drawString( ): to output a string to an applet, which is a member of the Graphics class.
Typically, it is called from within either update( ) or paint( ).
Syntax:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y.
void setBackground(Color newColor)
void setForeground(Color newColor)
newColor:
Color.black
Color.gray
Color.blue
Color.cyan
Color.darkGray
Color.green
Color.lightGray
Color.magenta
Color.white
Color.orange
Color.pink
Color.red
Color.yellow
344
Applet
Color getBackground( )
Color getForeground( )
Types of Applet
Two varieties of applets.
1. Applet : These applets use the Abstract Window Toolkit (AWT) to provide the
graphic user interface (or use no GUI at all). This style of applet has been
available since Java was first created.
2.
JApplet. Are based on the Swing class Japplet.Swing applets use the Swing
classes to provide the GUI. Swing offers a richer and often easier-to-use
user interface than does the AWT.
346
Creating Applet
To use an applet, it is specified in an HTMLfile.
One way to do this is by using the APPLET tag.
(The OBJECT tag can also be used, but Sun currently recommends the APPLET tag )
The applet will be executed by a Java-enabled web browser when it encounters the
APPLET tag within the HTMLfile.
To view and test an applet more conveniently, simply include a comment
at the head of your Java source code file that contains the APPLET tag.
This way, your code is documented with the necessary HTML statements
needed by your applet,
Test the compiled applet by starting the applet viewer with your Java source code
file specified as the target.
Example :
/*
<applet code=MyAppletwidth=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a
window that is 200 pixels wide and 60 pixels high.
Because the inclusion of an APPLET command makes testing applets easier.
347
Applet
The Applet Class:
Applet provides all necessary support for applet execution, such as
starting and stopping.
It also provides methods that load and display images, and methods
that load and play audio clips.
Applet extends the AWT class Panel. In turn, Panel extends Container,
which extends Component.
These classes provide support for Javas window-based, graphical
interface.
Applet provides all of the necessary support for window-based
activities.
348
Applet
void destroy( ) :Called by the browser just before an applet is terminated.
Your applet will override this method if it needs to perform any cleanup prior to its
destruction.
AccessibleContext getAccessibleContext( ) :Returns the accessibility context for the
invoking object.
AppletContext getAppletContext( ): Returns the context associated with the applet.
String getAppletInfo( ) :Returns a string that describes the applet.
AudioClip getAudioClip(URL url) :Returns an AudioClip object that encapsulates the
audio clip found at the location specified by url.
AudioClip getAudioClip(URL url, String clipName):Returns an AudioClip object that
encapsulates the audio clip found at the location specified by url and having the name
specified by clipName.
URL getCodeBase( ) :Returns the URL associated with the invoking applet.
URL getDocumentBase( ) :Returns the URL of the HTML document that invokes the applet.
Image getImage(URL url) :Returns an Image object that encapsulates the image found at the
location specified by url.
349
Applet
Image getImage(URL url,String imageName):Returns an Image object that encapsulates
the image found at the location specified by url and having the name specified by imageName.
350
Applet
void init( ) : Called when an applet begins execution. It is the first method called for
any applet.
boolean isActive( ): Returns true if the applet has been started. It returns false if the
applet has been stopped.
static final AudioClip newAudioClip(URL url) :Returns an AudioClip object that
encapsulates the audio clip found at the location specified by url. This method is
similar to getAudioClip( ) except that it is static and can be executed without the
need for an Applet object.
351
Applet
void play(URL url): If an audio clip is found at the location specified by url, the clip is
played.
void play(URL url, String clipName): If an audio clip is found at the location specified
by url with the name specified by clipName, the clip is played.
void resize(Dimension dim) :Resizes the applet according to the dimensions
specified by dim. Dimension is a class stored inside java.awt. It contains two integer
fields: width and height.
void resize(int width, int height) :Resizes the applet according to the dimensions
specified by width and height.
final void setStub(AppletStub stubObj) :Makes stubObj the stub for the applet. This
method is used by the run-time system and is not usually called by your applet. A
stub is a small piece of code that provides the linkage between your applet and the
browser.
352
Applet
Passing Parameter to Applets:
It is also possible to supply user defined parameters to An applet using
<PARAM> tags.
Each <PARAM> tag has a name attribute and a value attribute .Inside
the applet code .
The applet can refer to that parameter by name to find its value .
To retrieve the Parameter ,use the method
getParameter(): returns the value of the specified parameter in the
form of a String Object
Swings
Introduction :
Limitation of AWT:
MVC Architecture:
Component
Containers:
JApplet:
JFrame:
JComponent:
Icons& Labels:
TextField
354
Swings
Buttons:
JButton class
Checkboxes
RadioButtons
Combo boxes
Tabbed Panes
ScrollPanes
Trees
Tables
355
Swings
Introduction : AWT
The AWT defines a basic set of controls, windows, and dialog boxes
that support a usable, but limited graphical interface.
First, because of variations between operating systems, a
component might look, or even act, differently on different
platforms.
This potential variability threatened the overarching philosophy of
Java: write once, run anywhere.
Second, the look and feel of each component was fixed (because it
is defined by the platform) and could not be (easily) changed.
That the look and feel of a component is defined by the
platform, not by Java.
Third, the use of heavyweight components caused some frustrating
restrictions. Because the AWT components use native code
resources, they are referred to as heavyweight. For example, a
heavyweight component is always rectangular and opaque.
356
Swings
Swings:
Swing eliminates a number of the limitations inherent in the AWT, Swing does
not replace it.
Swing is built on the foundation of the AWT.
Swing was created to address the limitations present in the AWT.
It does this through two key features: lightweight components and a
pluggable look and feel.
Swing Components Are Lightweight
They are written entirely in Java and do not map directly to platformspecific peers.
More efficient and more flexible.
Lightweight components do not translate into native peers, the look and
feel of each component is determined by Swing, not by the underlying
operating system.
Each component will work in a consistent manner across all platforms. 357
Swings
Swing Supports a Pluggable Look and Feel
Swing supports a pluggable look and feel (PLAF).
Each Swing component is rendered by Java code rather than by native
peers, the look and feel of a component is under the control of Swing.
Separate the look and feel of a component from the logic of the
component, and this is what Swing does.
358
Swings
MVC Connection:
A visual component is a composite of three distinct aspects:
The way that the component looks when rendered on the screen
The way that the component reacts to the user
The state informati on associated with the component
No matter what architecture is used to implement a component, it must implicitly contain
these three parts
The MVC architecture has successful because each piece of the design corresponds to an
aspect of a component.
In MVC terminology, the model corresponds to the state information
associated with the component.
For example, in the case of a check box, the model contains
a field that indicates if the box is checked or unchecked.
The view determines how the component is displayed on the screen, including any aspects
of the view that are affected by the current state of the model.
The controller determines how the component reacts to the
user. For example, when the user clicks a check box, the controller reacts by changing the
model to reflect the users choice (checked or unchecked). This then results in the view
being updated.
359
Swings
By separating a component into a model, a view, and a controller, the
specific implementation of each can be changed without affecting the
other two.
For instance, different view implementations can render the same
component in different ways without affecting the model or the
controller.
Swings pluggable look and feel is made possible by its Model-Delegate
architecture.
Because the view (look) and controller (feel) are separate from the
model, the look and feel can be changed without affecting how the
component is used within a program.
360
Swings
Components and Containers:
A component is an independent visual control, such as a push button or
slider.
JComponent provides the functionality that is common to all
components. For example, JComponent supports the pluggable look and
feel.
JComponent inherits the AWT classes Container and Component.
A Swing component is built on and compatible with an AWT component.
Swings components defined within the package javax.swing.
361
Swings
Components and Containers:
JApplet JButton
JCheckBox
JCheckBoxMenuItem
JColorChooser
JComboBox
JComponent JDesktopPane
JDialog
JEditorPane
JFileChooser
JFormattedTextField JFrame
JInternalFrame
JLabel JLayeredPane JList Jmenu
JMenuBar
JMenuItem
JOptionPane
JPanel
JPasswordField
JPopupMenu
JProgressBar
JRadioButton
JRadioButtonMenuItem
JRootPane
JScrollBar
JScrollPane
JSeparator
Jslider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
Jtogglebutton
JToolBar
JToolTip
Jtree
Jviewport
JWindow
362
Swings
Containers:
A container holds a group of components.
Thus, a container is a special type of component that is designed to hold
other components.
Swing defines two types of containers.
The first are top-level containers:
JFrame, JApplet, JWindow, and JDialog (holds all the
component).
The second type of containers supported by Swing are lightweight
containers is JPanel.
363
Swings
FlowLayout
FlowLayout is the simplest of all layouts, and is the default
LayoutManager of the JPanel.
In FlowLayout, widgets are placed one after another going left to right.
This occurs until the end of the JPanel is reached, then a new row is
started.
Constructors for the FlowLayout.
FlowLayout();
FlowLayout(int alignment);
FlowLayout(int alignment, int horizontalSpace, int verticalSpace);
The first constructor is the default. By default, the spacing between
these widgets is about 5 pixels and the alignment is
364
FlowLayout.CENTER.
Swings
Swing Packages :
Swing is a very large subsystem and makes use of many packages.
javax.swing
javax.swing.colorchooser
javax.swing.filechooser
javax.swing.plaf.basic
javax.swing.plaf.multi
javax.swing.table
javax.swing.text.html
javax.swing.text.rtf
javax.swing.undo
javax.swing.border
javax.swing.event
javax.swing.plaf
javax.swing.plaf.metal
javax.swing.plaf.synth
javax.swing.text
javax.swing.text.html.parser
javax.swing.tree
365
Swings
Exploring Swing:ImageIcon:
Icons are specified by objects of type Icon, which is an interface defined by Swing.
The easiest way to obtain an icon is to use the ImageIcon class.
ImageIcon implements Icon and encapsulates an image. Thus, an object of type Image Icon can be passed as an
argument to the Icon parameter of JLabels constructor.
There are several ways to provide the image, including reading it from a file or downloading it from a URL.
ImageIcon constructor:
ImageIcon(String filename)
It obtains the image in the file named filename.
Methods:
Icon getIcon( )
String getText( )
void setIcon(Icon icon)
void setText(String str) : to change the text inside a label during program execution
Here, icon and str are the icon and text, respectively. JLabel
366
Swings
JLabel:
JLabel can be used to display text and/or an icon.
JLabel defines constructors.
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
align can be one of the constant :
LEFT, RIGHT, CENTER, LEADING, or TRAILING.
JLabelDemo
367
Swings
JTextField: JTextField allows you to edit one line of text.
JTextFields constructors:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
JTextFieldDemo
368
Swings
JButtons:
Swing defines four types of buttons:
JButton, JToggleButton, JCheckBox, and JRadioButton.
All are subclasses of the AbstractButton class, which extends
JComponent.
JButton class provides the functionality of a push button.JButton
allows an icon, a string, or both to be associated with the push button.
Jbuttons constructors
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button.
ActionEvent is generated
Unit -8 Program No:3
JButtonDemo
369
Swings
JCheck Boxes: JCheckBox class provides the functionality of a check box.
JCheckBox constructors:
JCheckBox(String str)
It creates a check box that has the text specified by str as a label.
When the user selects or deselects a check box, an ItemEvent is
generated.
JCheckBoxDemo
370
Swings
Radio Buttons:
Radio buttons are a group of mutually exclusive
buttons, in which only one button can be selected at
any one time. They are supported by the JRadioButton class.
JRadioButton provides several constructors.
JRadioButton(Icon i)
JRadioButton(Icon i ,boolean state)
JRadioButton(String str)
JRadioButton(String str, boolean state)
JRadioButton(String str,Icon i)
JRadioButton(String str, Icon i,boolean state)
371
Swings
A button group is created by the ButtonGroup class.
Its default constructor is invoked for this purpose.
Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
JRadioButtonDemo
372
Swings
JComboBox:Swing provides a combo box (a combination of a text field
and a drop-down list) through
the JComboBox class. A combo box normally displays one entry, but it
will also display a drop-down list that allows a user to select a different
entry.
JComboBox constructor
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box.
Methods:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
Object getSelectedItem( )
You will need to cast the returned value into the type of object stored in
373
the list.
Unit -8 Program No:8 JComboBoxDemo
Swings
JTabbedPane:
JTabbedPane encapsulates a tabbed pane. It manages a set of components
by linking them with tabs. Selecting a tab causes the component associated
with that tab to come to the forefront.
JTabbedPane defines constructor
JTabbedPane()
The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.
Swings
JScrollPane
JScrollPane is a lightweight container that automatically handles the
scrolling of Pane another component. The component being scrolled can
either be an individual component, such as a table, or a group of
components contained within another lightweight container, such as a
JPanel.
JScrollPane defines constructors.
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are
automatically displayed when the content of the pane exceeds the
dimensions of the viewport.
Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.
Unit -8 Program No:7
JScrollPane
375
Swings
Trees: A tree is a component that presents a hierarchical view of data.
The user has the ability to expand or collapse individual subtrees in this
display. Trees are implemented in Swing by the JTree class.
Constructors:
JTree(Object obj[ ])
JTree(Vector<?> v)
JTree(TreeNode tn)
376
Swings
JTree relies on two models: TreeModel and TreeSelectionModel.
A JTree generates a variety of events, but three relate specifically to trees:
TreeExpansionEvent,
TreeSelectionEvent,
TreeModelEvent.
A TreeExpansionEvent events occur when a node is expanded or collapsed.
A TreeSelectionEvent is generated when the user selects or deselects a node
within the tree.
A TreeModelEvent is fired when the data or structure of the tree changes.
The listeners for these events are
TreeExpansionListener
TreeSelectionListener
TreeModelListener
The tree event classes and listener interfaces are packaged in
377
javax.swing.event.
Swings
The DefaultMutableTreeNode class implements the MutableTreeNode
interface.
It represents a node in a tree. One of its constructors is shown here:
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node. The new tree
node doesnt have a parent or children.
To create a hierarchy of tree nodes, the add( ) method of
DefaultMutableTreeNode can be used.
Its signature is shown here:
void add(MutableTreeNode child)
Here, child is a mutable tree node that is to be added as a child to the
current node
378
Swings
JTree does not provide any scrolling capabilities of its own. Instead, a
JTree is typically placed within a JScrollPane. This way, a large tree can
be scrolled through a smaller viewport.
Here are the steps to follow to use a tree:
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.
379
Swings
JTable :
JTable is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to
a new position.
Depending on its configuration, it is also possible to select a row, column, or
cell within the table, and to change the data within a cell.
JTable does not provide any scrolling capabilities of its own. Instead, you will
normally wrap a JTable inside a JScrollPane.
JTable constructor:
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column headings.
380
Swings
JTable relies on three models.
1. The first is the table model, which is defined by the TableModel
interface. This model defines those things related to displaying data
in a two-dimensional format.
2. The second is the table column model, which is represented by
TableColumnModel. JTable is defined in terms of columns, and it
is TableColumnModel that specifies the characteristics of a
column. These two models are packaged in javax.swing.table.
3. The third model determines how items are selected, and it is
specified by the ListSelectionModel,
381
Swings
A JTable can generate several different events. The two most
fundamental to a tables operation are
1. ListSelectionEvent
2. TableModelEvent.
Here are the steps required to set up a simple JTable that can be used to
display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
382