Java PPT'S
Java PPT'S
Object
Class
Data Abstraction & Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
Object
Objects are the basic run time entities in an object-
oriented system. They may represent a person, a place,
a bank account, a table of data or any item that the
program has to handle.
Class
The entire set of data and code of an object can be made of a
user defined data type with the help of a class.
In fact, Objects are variables of the type class. Once a class has
been defined, we can create any number of objects belonging to
that class.
{
private:
EyeColor IColor;
NAME personname;
public:
};
Data abstraction
Abstraction refers to the act of representing essential features
without including the background details or explanations. since the
classes use the concept of data abstraction ,they are known as
abstraction data type(ADT).
class
FIGURE
Ob1 Ob3
class <ClassName>
{
attributes/variables;
Constructors();
methods();
}
INSTANCE
• Instance is an Object of a class which is an entity with its own
attribute values and methods.
• Creating an Instance
ClassName refVariable;
refVariable = new Constructor();
or
ClassName refVariable = new Constructor();
Java Class Hierarchy
• In Java, class “Object” is the base class to all other classes
– If we do not explicitly say extends in a new class definition,
it implicitly extends Object
– The tree of classes that extend from Object and all of its
subclasses are is called the class hierarchy
Animal
weight : int
+ getWeight() : int
Bird
+ fly() : void
Method Binding
Objects are used to call methods.
MethodBinding is an object that can be used to call an arbitrary
public method, on an instance that is acquired by evaluating the
leading portion of a method binding expression via a value
binding.
It is legal for a class to have two or more methods with the same
name.
Java has to be able to uniquely associate the invocation of a
method with its definition relying on the number and types of
arguments.
Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to implement
polymorphism.
Method Overriding.
There may be some occasions when we want an object to
respond to the same method but have different behavior
when that method is called.
That means, we should override the method defined in the
super class. This is possible by defining a method in a sub class
that has the same name, same arguments and same return
type as a method in the super class.
Then when that method is called, the method defined in the
sub class is invoked and executed instead of the one in the
super class. This is known as overriding.
Exceptions in Java
• Exception is an abnormal condition that arises in the code
sequence.
• Exceptions occur during compile time or run time.
• “throwable” is the super class in exception hierarchy.
• Compile time errors occurs due to incorrect syntax.
• Run-time errors happen when
– User enters incorrect input
– Resource is not available (ex. file)
– Logic error (bug) that was not fixed
Exception classes
Function Power
Give me two numbers (base & exponent)
I’ll return baseexponent
Implementation
Data Abstraction
• Data Abstractions organize data.
StudentType
Name (string)
Marks (num)
Grade (char)
Queue Object
Enqueue
Is Full
Data State
Is Empty Dequeue
Initialize
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
The development of Java was driven by both in equal
measures.
Many Java features are inherited from the earlier
languages:
B C C++ Java
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.
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.
Java: History
In 1990, Sun Microsystems started a project called Green.
Objective: to develop software for consumer electronics.
Project was assigned to James Gosling, a veteran of classic
network software design. Others included Patrick
Naughton, ChrisWarth, Ed Frank, and Mike Sheridan.
The team started writing programs in C++ for embedding
into
– toasters
– washing machines
– VCR’s
Aim was to make these appliances more “intelligent”.
Java: History (contd.)
L 1.5
Java: History (contd.)
Hence, the team built a new programming language called Oak,
which avoided potentially dangerous constructs in C++, such as
pointers, pointer arithmetic, operator overloading etc.
Introduced automatic memory management, freeing the
programmer to concentrate on other things.
Architecture neutrality (Platform independence)
Many different CPU’s are used as controllers. Hardware chips are
evolving rapidly. As better chips become available, older chips
become obsolete and their production is stopped. Manufacturers
of toasters and washing machines would like to use the chips
available off the shelf, and would not like to reinvest in compiler
development every two-three years.
So, the software and programming language had to be architecture
neutral.
Java: History (contd)
It was soon realized that these design goals of consumer electronics perfectly
suited an ideal programming language for the Internet and WWW, which
should be:
object-oriented (& support GUI)
– robust
– architecture neutral
Internet programming presented a BIG business opportunity. Much bigger
than programming for consumer electronics.
Java was “re-targeted” for the Internet
The team was expanded to include Bill Joy (developer of Unix), Arthur van
Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc.
In 1994, an early web browser called WebRunner was written in Oak.
WebRunner was later renamed HotJava.
In 1995, Oak was renamed Java.
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.
Java History
Designed by James Gosling, Patrick Naughton, Chris
Warth, Ed Frank and Mike Sheridan at Sun
Microsystems in 1991.
The original motivation is not Internet: platform-
independent software embedded in consumer
electronics devices.
With Internet, the urgent need appeared to break the
fortified positions of Intel, Macintosh and Unix
programmer communities.
Java as an “Internet version of C++”? No.
Java was not designed to replace C++, but to solve a
different set of problems.
The Java Buzzwords
The key considerations were summed up by the Java
team in the following list of buzzwords:
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
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.
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.
Portability: Many types of computers and
operating systems are in use throughout the
world—and many are connected to the Internet.
For programs to be dynamically downloaded to all
the various types of platforms connected to the
Internet, some means of generating portable
executable code is needed. The same mechanism
that helps ensure security also helps create
portability.
Indeed, Java's solution to these two problems is
both elegant and efficient.
L 1.13
Data Types
L 1.16
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.
Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage:
1) fractional part is needed
2) large degree of precision is not required
double: 64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers
L 1.18
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
L 1.20
Variables
declaration – how to assign a type to a variable
initialization – how to give an initial value to a variable
scope – how the variable is visible to other parts of the
program
lifetime – how the variable is created, used and destroyed
type conversion – how Java handles automatic type
conversion
type casting – how the type of a variable can be narrowed
down
Variables
L 2.2
Basic Variable Declaration
L 2.4
Variable Scope
Scope determines the visibility of program elements with respect
to other program elements.
In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{
…
}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
Variable Lifetime
L 2.8
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
type type, which reference will be kept in the
variable array-variable.
Array Indexing
L 2.13
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 ;
Basic Arithmetic Operators
+ op1 + op2 ADD
L 2.15
Relational operator
== Equals to Apply to any type
! ! op Logical NOT
>> op1 >> op2 Shifts all bits in op1 right by the value of
op2
<< op1 << op2 Shifts all bits in op1 left by the value of
op2
Expressions
An expression is a construct made up of variables,
operators, and method invocations, which are
constructed according to the syntax of the language, that
evaluates to a single value.
Examples of expressions are in bold below:
int number = 0;
anArray[0] = 100;
System.out.println ("Element 1 at index 0: " +
anArray[0]);
int result = 1 + 2; // result is now 3 if(value1 ==
value2)
System.out.println("value1 == value2");
L 2.19
Expressions
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
Control Statements
L 3.3
Jump Statements
L 4.3
Object Creation
L 4.5
Class
L 4.7
Example: Class Usage
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);
} }
Constructor
A constructor initializes the instance variables of an object.
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
constructor is the same classWhen the class has no
constructor, the default constructor automatically initializes
all its instance variables with zero.
Example: Constructor
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
L 5.2
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;
}
}
Methods
L 5.4
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:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Parameterized Method
L 5.6
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables
and methods.
• Encapsulation, safely sealing data within the capsule
of the class Prevents programmers from relying on
details of class implementation, so you can update
without worry
• Helps in protecting against accidental or wrong
usage.
• Keeps code elegant and clean (easier to maintain)
Access Modifiers: Public, Private,
Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Default(No visibility modifier is specified): it
behaves like public in its package and private
in other packages.
• Default Public keyword applied to a class,
makes it available/visible everywhere.
Applied to a method or variable, completely
visible.
L 6.2
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.
Visibility
public class Circle {
private double x,y,r;
// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
L 6.4
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."
L 8.4
The String class contains several methods that you can use.
Here are a few. You can
test two strings for equality by using
equals( ). You can obtain the length of a string by calling the
length( ) method. You can obtain the character at a specified
index within a string by calling charAt( ). The general forms
of these three methods are shown here:
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}}
107
Inheritance
Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Animal
weight : int
Inheritance
+ getWeight() : int should create an
is-a relationship,
meaning the
Bird child is a more
specific version
of the parent
+ fly() : void
108
Deriving Subclasses
In Java, we use the reserved word extends to establish an
inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}
109
Class Hierarchy
A child class of one parent can be the parent of another
child, forming class hierarchies
Animal
111
Defining Methods in the Child Class:
Overriding by Replacement
A child class can override the definition of an inherited method in
favor of its own
that is, a child can redefine a method that it inherits from its parent
the new method must have the same signature as the parent's method,
but can have different code in the body
112
Defining Methods in the Child Class:
Overriding by Refinement
Constructors in a subclass override the definition of an inherited constructor
method by refining them (instead of replacing them)
- Assume class Animal has constructors
Animal(), Animal(int weight), Animal(int weight, int livespan)
- Assume class Bird which extends Animal has constructors
Bird(), Bird(int weight), Bird(int weight, int livespan)
113
Recap: Class Hierarchy
In Java, a class can extend a single other class
(If none is stated then it implicitly extends an Object class)
Animal
Animal
inheritance is transitive
An instance of class Parrot is also an instance of Bird,
an instance of Animal, …, and an instance of class
Object
Base Class Object
In Java, all classes use inheritance.
If no parent class is specified explicitly, the base class Object is
implicitly inherited.
All classes defined in Java, is a child of Object class, which provides
minimal functionality guaranteed to e common to all objects.
Methods defined in Object class are;
1. equals(Object obj): Determine whether the argument object is the
same as the receiver.
2. getClass(): Returns the class of the receiver, an object of type Class.
3. hashCode(): Returns a hash value for this object. Should be
overridden when the equals method is changed.
4. toString(): Converts object into a string value. This method is also
often overridden.
Base class
1) a class obtains variables and methods from another class
2) the former is called subclass, the latter super-class (Base class)
3) a sub-class provides a specialized behavior with respect to its
super-class
4) inheritance facilitates code reuse and avoids duplication of
data
Extends
Is a keyword used to inherit a class from another class
Allows to extend from only one class
class Two extends One
class One
{ int a=5; {
} int b=10;
}
Subclass, Subtype and Substitutability
A subtype is a class that satisfies the principle of
substitutability.
A subclass is something constructed using inheritance,
whether or not it satisfies the principle of substitutability.
The two concepts are independent. Not all subclasses are
subtypes, and (at least in some languages) you can
construct subtypes that are not subclasses.
Substitutability is fundamental to many of the powerful
software development techniques in OOP.
The idea is that, declared a variable in one type may hold
the value of different type.
Substitutability can occur through use of inheritance,
whether using extends, or using implements keywords.
Subclass, Subtype, and Substitutability
When new classes are constructed using inheritance, the argument
used to justify the validity of substitutability is as follows;
• Instances of the subclass must possess all data fields associated
with its parent class.
• Instances of the subclass must implement, through inheritance
at least, all functionality defined for parent class. (Defining new
methods is not important for the argument.)
• Thus, an instance of a child class can mimic the behavior of the
parent class and should be indistinguishable from an instance of
parent class if substituted in a similar situation.
Subclass, Subtype, and
Substitutability
The term subtype is used to describe the relationship between
types that explicitly recognizes the principle of substitution. A type
B is considered to be a subtype of A if an instances of B can legally
be assigned to a variable declared as of type A.
The term subclass refers to inheritance mechanism made by
extends keyword.
Not all subclasses are subtypes. Subtypes can also be formed
using interface, linking types that have no inheritance relationship.
Subclass
Methods allows to reuse a sequence of statements
+ getWeight() : int
Bird
+ fly() : void
Substitutability (Deriving Subclasses)
In Java, we use the reserved word extends to establish an
inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}
TextField
CheckBox
ScrollBar
Forms of Inheritance
(- Inheritance for Specification -)
This is another most common use of inheritance. Two different
mechanisms are provided by Java, interface and abstract, to make use of
subclassification for specification. Subtype is formed and substitutability
is explicitly upheld.
Mostly, not used for refinement of its parent class, but instead is used for
definitions of the properties provided by its parent.
class FireButtonListener implements ActionListener {
// body of class
}
class B extends A {
// class A is defined as abstract specification class
}
Specification
The next most common form of inheritance involves
specification. The parent class specifies some behavior, but
does not implement the behavior
Child class implements the behavior
Similar to Java interface or abstract class
When parent class does not implement actual behavior but
merely defines the behavior that will be implemented in child
classes
Example, Java 1.1 Event Listeners:
ActionListener, MouseListener, and so on specify behavior, but
must be subclassed.
Forms of Inheritance
(- Inheritance for Construction -)
Child class inherits most of its functionality from parent, but may
change the name or parameters of methods inherited from
parent class to form its interface.
This type of inheritance is also widely used for code reuse
purposes. It simplifies the construction of newly formed
abstraction but is not a form of subtype, and often violates
substitutability.
Example is Stack class defined in Java libraries.
Construction
The parent class is used only for its behavior, the child class
has no is-a relationship to the parent.
Child modify the arguments or names of methods
An example might be subclassing the idea of a Set from an
existing List class.
Child class is not a more specialized form of parent class;
no substitutability
Forms of Inheritance
(- Inheritance for Extension -)
Subclassification for extension occurs when a child class only
adds new behavior to the parent class and does not modify or
alter any of the inherited attributes.
Such subclasses are always subtypes, and substitutability can be
used.
Example of this type of inheritance is done in the definition of
the class Properties which is an extension of the class HashTable.
Generalization or Extension
The child class generalizes or extends the parent class by
providing more functionality
In some sense, opposite of subclassing for specialization
The child doesn't change anything inherited from the
parent, it simply adds new features
Often used when we cannot modify existing base parent
class
Example, ColoredWindow inheriting from Window
Add additional data fields
Override window display methods
Forms of Inheritance
(- Inheritance for Limitation -)
Subclassification for limitation occurs when the behavior of the
subclass is smaller or more restrictive that the behavior of its
parent class.
Like subclassification for extension, this form of inheritance
occurs most frequently when a programmer is building on a
base of existing classes.
Is not a subtype, and substitutability is not proper.
Limitation
The child class limits some of the behavior of the parent class.
Example, you have an existing List data type, and you want a
Stack
Inherit from List, but override the methods that allow access
to elements other than top so as to produce errors.
Forms of Inheritance
(- Inheritance for Combination -)
This types of inheritance is known as multiple inheritance in
Object Oriented Programming.
Although the Java does not permit a subclass to be formed be
inheritance from more than one parent class, several
approximations to the concept are possible.
Example of this type is Hole class defined as;
class Hole extends Ball implements PinBallTarget{
// body of class
}
Combimnation
Two or more classes that seem to be related, but its not clear
who should be the parent and who should be the child.
Program Size
Message-Passing Overhead
SUPER SUPER
extends extends
implement
extends
s
SUPER 1 SUPER 2
SUB
SUB
extends implement
extends
s
Book
protected int pages
+ getPages() : int
+ setPages(): void
Dictionary
+ getDefinitions() : int
+ setDefinitions(): void
+ computeRatios() : double
“super” uses
‘super’ is a keyword used to refer to hidden variables of super
class from sub class.
super.a=a;
Vehicle
2. package myPackage;
class MyClass3{ … }
Two ways:
1) The current directory is the default start point - if
packages are stored in the current directory or sub-
directories, they will be found.
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n; bal = b;
}
void show() {
if (bal<0) System.out.print("-->> ");
System.out.println(name + ": $" + bal);
} }
Example: Package
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for (int i=0; i<3; i++) current[i].show();
}
}
Example: Package
Save, compile and execute:
1) call the file AccountBalance.java
2) save the file in the directory MyPack
3) compile; AccountBalance.class should be also in
MyPack
4) set access to MyPack in CLASSPATH variable, or make
the
parent of MyPack your current directory
5) run: java MyPack.AccountBalance
import otherPackage1;otherPackage2.otherClass;
class myClass { … }
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);
}
}
Example: Packages 2
The importing code has access to the public class Balance of
the
MyPack package and its two public members:
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show();
}
}
Java Source File
AskMe includes all shared constants in the same way, using them
to display the result, depending on the value received:
The testing function relies on the fact that both ask and
answer methods.
B extends A:
interface B extends A {
void meth3();
}
Example: Interface Inheritance 2
wake up
JVM
Born start()
suspend()
resume()
Runnable
Blocked
stop() wait
stop()
notify
block on I/O
Dead I/O available
New state – After the creations of Thread instance the thread is in this
state but before the start() method invocation. At this point, the thread
is considered not alive.
Runnable (Ready-to-run) state – A thread start its life from Runnable
state. A thread first enters runnable state after the invoking of start()
method but a thread can return to this state after either running,
waiting, sleeping or coming back from blocked state also. On this state a
thread is waiting for a turn on the processor.
Running state – A thread is in running state that means the thread is
currently executing. There are several ways to enter in Runnable state
but there is only one way to enter in Running state: the scheduler select
a thread from runnable pool.
Dead state – A thread can be considered dead when its run() method
completes. If any thread comes on this state that means it cannot ever
run again.
Blocked - A thread can enter in this state because of waiting the
resources that are hold by another thread.
Creating Threads
class ThreadDemo {
public static void main(String args[]) {
//A new thread is created as an object of
// NewThread:
new NewThread();
//After calling the NewThread start method,
// control returns here.
Example: New Thread 4
//Both threads (new and main) continue concurrently.
//Here is the loop for the main thread:
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
New Thread: Extend Thread
class ExtendThread {
public static void main(String args[]) {
//After a new thread is created:
new NewThread();
//the new and main threads continue
//concurrently…
Example: New Thread 4
//This is the loop of the main thread:
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Threads: Synchronization
Multi-threading introduces asynchronous behavior to a program.
How to ensure synchronous behavior when we need it?
For instance, how to prevent two threads from simultaneously
writing and reading the same object?
Java implementation of monitors:
1) classes can define so-called synchronized methods
2) each object has its own implicit monitor that is automatically
entered when one of the object’s synchronized methods is called
3) once a thread is inside a synchronized method, no other thread
can call any other synchronized method on the same object
Thread Synchronization
Language keyword: synchronized
Takes out a monitor lock on an object
Exclusive lock for that thread
If lock is currently unavailable, thread will block
Thread Synchronization
Protects access to code, not to data
Make data members private
Synchronize accessor methods
Puts a “force field” around the locked object so no other
threads can enter
Actually, it only blocks access to other synchronizing threads
Daemon Threads
Any Java thread can be a daemon thread.
Daemon threads are service providers for other threads running in the
same process as the daemon thread.
The run() method for a daemon thread is typically an infinite loop that
waits for a service request. When the only remaining threads in a
process are daemon threads, the interpreter exits. This makes sense
because when only daemon threads remain, there is no other thread
for which a daemon thread can provide a service.
To specify that a thread is a daemon thread, call the setDaemon
method with the argument true. To determine if a thread is a daemon
thread, use the accessor method isDaemon.
Thread Groups
o Every Java thread is a member of a thread group.
o Thread groups provide a mechanism for collecting multiple threads into a single
object and manipulating those threads all at once, rather than individually.
o For example, you can start or suspend all the threads within a group with a single
method call.
o Java thread groups are implemented by the “ThreadGroup” class in the java.lang
package.
The runtime system puts a thread into a thread group during thread construction.
When you create a thread, you can either allow the runtime system to put the new
thread in some reasonable default group or you can explicitly set the new thread's
group.
The thread is a permanent member of whatever thread group it joins upon its
creation--you cannot move a thread to a new group after the thread has been
created
The ThreadGroup Class
268
The collections framework was designed to meet several goals:
The framework had to be high-performance. The
implementations for the fundamental collections (dynamic
arrays, linked lists, trees, and hashtables) are highly efficient.
The framework had to allow different types of collections to
work in a similar manner and with a high degree of
interoperability.
Extending and/or adapting a collection had to be easy.
Collections Framework
A collections framework is a unified architecture for representing
and manipulating collections.
Reduces effort to learn and to use new APIs: Many APIs naturally take collections on
input and furnish them as output. In the past, each such API had a small sub-API devoted to
manipulating its collections. There was little consistency among these ad hoc collections
sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when
using them. With the advent of standard collection interfaces, the problem went away.
Reduces effort to design new APIs: This is the flip side of the previous advantage.
Designers and implementers don't have to reinvent the wheel each time they create an API
that relies on collections; instead, they can use standard collection interfaces.
Fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable. The same goes for new algorithms that operate on objects
that implement these interfaces.
Each collection class implements an interface from a
Collections
hierarchy Framework Diagram
Each class is designed for a
specific type of storage
Ordered Lists
Lists and Sets
ArrayList
Stores a list of items in a dynamically sized array
LinkedList
Allows speedy insertion and removal of items from the list
HashSet
Uses hash tables to speed up finding, adding, and removing
elements
TreeSet
Uses a binary tree to speed up finding, adding, and removing
elements
Set — a collection that cannot contain duplicate elements. This interface models the mathematical set
abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making
up a student's schedule, or the processes running on a machine..
List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The
user of a List generally has precise control over where in the list each element is inserted and can access
elements by their integer index (position). If you've used Vector, you're familiar with the general flavor of
List.
Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection
operations, a Queue provides additional insertion, extraction, and inspection operations.
Map — an object that maps keys to values. A Map cannot
contain duplicate keys; each key can map to at most one
value. If you've used Hashtable.
2.The second tree starts with the Map interface, which maps keys and values similar to a
Hashtable.
Map's subinterface, SortedMap, maintains its key-value pairs in ascending order or in an
order specified by a Comparator.
These interfaces allow collections to be manipulated independently of the details of their
representation.
The Collection Classes
Java provides a set of standard collection classes that
implement Collection interfaces. Some of the classes provide
full implementations that can be used as-is and others are
abstract class, providing skeletal implementations that are used
as starting points for creating concrete collections.
Classes with Description
1AbstractCollection -Implements most of the Collection interface.
2AbstractList -Extends AbstractCollection and implements most of the List interface.
3AbstractSequentialList Extends AbstractList for use by a collection that uses sequential
rather than random access of its elements.
4LinkedList -Implements a linked list by extending AbstractSequentialList.
5ArrayList -Implements a dynamic array by extending AbstractList.
6AbstractSet -Extends AbstractCollection and implements most of the Set interface.
7HashSet -Extends AbstractSet for use with a hash table.
8LinkedHashSet -Extends HashSet to allow insertion-order iterations.
9TreeSet -Implements a set stored in a tree. Extends AbstractSet.
10AbstractMap -Implements most of the Map interface.
11HashMap -Extends AbstractMap to use a hash table.
12TreeMap -Extends AbstractMap to use a tree.
13WeakHashMap -Extends AbstractMap to use a hash table with weak keys.
14LinkedHashMap-Extends HashMap to allow insertion-order iterations.
15IdentityHashMap -Extends AbstractMap and uses reference equality when comparing
documents.
The Collection Interface (2)
Linked lists use references to maintain an ordered
15.2 Linked Lists
lists of ‘nodes’
The ‘head’ of the list references the first node
Each node has a value and a reference to the next node
Removal of a node
Find the element to remove
Remap neighbor’s references
Inefficient Operations
Random access Each instance variable is declared just like
other variables we have used.
LinkedList: Important Methods
Sets
A set is an unordered collection
It does not support duplicate elements
100
101
102
hashCode
The method is called hashCode
If multiple elements have the same hash code, they are stored
in a Linked list
L 8.6
Introduction
JDBC stands for Java Database Connectivity, which is a
standard Java API for database-independent connectivity
between the Java programming language and a wide
range of databases.
Import the packages . Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
Register the JDBC driver . Requires that you initialize a driver so you can open a
communications channel with the database.
To create a new database, you need not to give any database name while preparing
database URL as mentioned in the below example.
Execute a query . Requires using an object of type Statement for building and
submitting an SQL statement to the database.
After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method, which represents a physical
connection with the database as follows:
//STEP 3: Open a connection // Database credentials
static final String USER = "username";
static final String PASS = "password";
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
Execute a query:
This requires using an object of type Statement or PreparedStatement for building
and submitting an SQL statement to the database as follows:
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql; sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
Following table lists down popular JDBC driver names and
database URL.
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port
Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port
Number/databaseName
All the highlighted part in URL format is static and you need to change only remaining
part as per your database setup.
If there is an SQL UPDATE,INSERT or DELETE statement
required, then following code snippet would be required:
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "DELETE FROM Employees";
ResultSet rs = stmt.executeUpdate(sql);
Extract data from result set:
This step is required in case you are fetching data from the database.
You can use the appropriate ResultSet.getXXX() method to retrieve the
data from the result set as follows:
//STEP 5: Extract data from result set
while(rs.next())
{
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last); }
Clean up the environment:
You should explicitly close all database resources versus
relying on the JVM's garbage collection as follows:
rs.close();
stmt.close();
conn.close();
JDBC Driver
JDBC drivers implement the defined interfaces in the JDBC API for
interacting with your database server.
For example, using JDBC drivers enable you to open database
connections and to interact with it by sending SQL or database
commands then receiving results with Java.
The Java.sql package that ships with JDK contains various classes with
their behaviours defined and their actual implementaions are done in
third-party drivers.
Third party vendors implements the java.sql.Driver interface in their
database driver.
When Java first came out, this was a useful driver because
most databases only supported ODBC access but now this type
of driver is recommended only for experimental use or when
no other alternative is available.
L 3.2
Adapter classes
Java provides a special feature, called an adapter class, that
can simplify the creation of event handlers.
Members of the inner class are known only within the scope of
the inner class and may not be used by the outer class
The AWT class hierarchy
The AWT classes are contained in the java.awt package. It
is one of Java's largest packages. some of the AWT classes.
AWT Classes
1. AWTEvent:Encapsulates AWT events.
2. AWTEventMulticaster: Dispatches events to multiple
listeners.
3. BorderLayout: The border layout manager. Border
layouts use five components: North, South, East, West,
and Center.
4. Button: Creates a push button control.
5. Canvas: A blank, semantics-free window.
6. CardLayout: The card layout manager. Card layouts
emulate index cards. Only the one on top is showing.
7. Checkbox: Creates a check box control.
8. CheckboxGroup: Creates a group of check box controls.
9. CheckboxMenuItem: Creates an on/off menu item.
10. Choice: Creates a pop-up list.
11. Color: Manages colors in a portable, platform-independent fashion.
12. Component: An abstract super class for various AWT components.
13. Container: A subclass of Component that can hold other components.
14. Cursor: Encapsulates a bitmapped cursor.
15. Dialog: Creates a dialog window.
16. Dimension: Specifies the dimensions of an object. The width is stored
in width, and the height is stored in height.
17. Event: Encapsulates events.
18. EventQueue: Queues events.
19. FileDialog: Creates a window from which a file can be selected.
20. FlowLayout: The flow layout manager. Flow layout positions
components left to right, top to bottom.
21. Font: Encapsulates a type font.
22. FontMetrics: Encapsulates various information related to a font. This
information helps you display text in a window.
23. Frame: Creates a standard window that has a title bar, resize corners,
and a menu bar.
24. Graphics: Encapsulates the graphics context. This context is used by
various output methods to display output in a window.
25. GraphicsDevice: Describes a graphics device such as a screen or
printer.
26. GraphicsEnvironment: Describes the collection of available Font and
GraphicsDevice objects.
21. GridBagConstraints: Defines various constraints relating to the
GridBagLayout class.
22. GridBagLayout: The grid bag layout manager. Grid bag layout displays
components subject to the constraints specified by
GridBagConstraints.
23. GridLayout: The grid layout manager. Grid layout displays
components in a two-dimensional grid.
30. Scrollbar: Creates a scroll bar control.
31. ScrollPane: A container that provides horizontal and/or
vertical scrollbars for another component.
32. SystemColor: Contains the colors of GUI widgets such as
windows, scrollbars, text, and others.
33. TextArea: Creates a multiline edit control.
34. TextComponent: A super class for TextArea and TextField.
35. TextField: Creates a single-line edit control.
36. Toolkit: Abstract class implemented by the AWT.
37. Window: Creates a window with no frame, no menu bar, and
no title.
user interface components
Labels: Creates a label that displays a string.
A label is an object of type Label, and it contains a string, which it
displays.
Labels are passive controls that do not support any interaction with the
user.
Label defines the following constructors:
1. Label( )
2. Label(String str)
3. Label(String str, int how)
The first version creates a blank label.
The second version creates a label that contains the string specified by
str. This string is left-justified.
The third version creates a label that contains the string specified by str
using the alignment specified by how. The value of how must be one of
these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.
Set or change the text in a label is done by using the
setText( ) method.
Obtain the current label by calling getText( ).
These methods are shown here:
void setText(String str)
String getText( )
For setText( ), str specifies the new label. For getText( ),
the current label is returned.
To set the alignment of the string within the label by
calling setAlignment( ).
To obtain the current alignment, call getAlignment( ).
The methods are as follows:
void setAlignment(int how)
int getAlignment( )
Once you have added all items to a Menu object, you can
add that object to the menu bar by using this version of
add( ) defined by MenuBar:
Components Peer-Based
Platform controls component appearance
Inconsistencies in implementations
Interfacing to native platform error-prone
components
Container
JComponent
AbstractButton
JButton
JMenuItem
JCheckBoxMenuItem
JMenu
JRadioButtonMenuItem
JToggleButton
JCheckBox
JRadioButton
Components (contd…)
JComponent
JComboBox
JLabel
JList
JMenuBar
JPanel
JPopupMenu
JScrollBar
JScrollPane
Components (contd…)
JComponent
JTextComponent
JTextArea
JTextField
JPasswordField
JTextPane
JHTMLPane
Containers
Top-Level Containers
The components at the top of any Swing
containment hierarchy
General Purpose Containers
Intermediate containers that can be used under many
different circumstances.
Special Purpose Container
Intermediate containers that play specific roles in the UI.
Exploring swing- JApplet
If using Swing components in an applet, subclass
JApplet, not Applet
JApplet is a subclass of Applet
Sets up special internal component event handling,
among other things
Can have a JMenuBar
Default LayoutManager is BorderLayout
JFrame
public class FrameTest {
public static void main (String args[]) {
JFrame f = new JFrame ("JFrame Example");
Container c = f.getContentPane();
c.setLayout (new FlowLayout());
for (int i = 0; i < 5; i++) {
c.add (new JButton ("No"));
c.add (new Button ("Batter"));
}
c.add (new JLabel ("Swing"));
f.setSize (300, 200);
f.show();
}
}
JComponent
JComponent supports the following components.
JComponent
JComboBox
JLabel
JList
JMenuBar
JPanel
JPopupMenu
JScrollBar
JScrollPane
JTextComponent
JTextArea
JTextField
JPasswordField
JTextPane
JHTMLPane
Icons and Labels
In Swing, icons are encapsulated by the ImageIcon class,
which paints an icon from an image.
constructors are:
ImageIcon(String filename)
ImageIcon(URL url)
The ImageIcon class implements the Icon interface that
declares the methods
1. int getIconHeight( )
2. int getIconWidth( )
3. void paintIcon(Component comp,Graphics g,int x, int y)
Swing labels are instances of the JLabel class, which extends
JComponent.
It can display text and/or an icon.
Constructors are:
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for the label. The align
argument is either LEFT, RIGHT, or CENTER. These constants are
defined in the SwingConstants interface,
Methods are:
1. Icon getIcon( )
2. String getText( )
3. void setIcon(Icon i)
4. void setText(String s)
Here, i and s are the icon and text, respectively.
Text fields
The Swing text field is encapsulated by the
JTextComponent class, which extendsJComponent.
It provides functionality that is common to Swing text
components.
One of its subclasses is JTextField, which allows you to
edit one line of text.
Constructors are:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
Here, s is the string to be presented, and cols is the number
of columns in the text field.
Buttons
Swing buttons provide features that are not found in the Button class defined
by the AWT.
Swing buttons are subclasses of the AbstractButton class, which extends
JComponent.
AbstractButton contains many methods that allow you to control the
behavior of buttons, check boxes, and radio buttons.
Methods are:
1. void setDisabledIcon(Icon di)
2. void setPressedIcon(Icon pi)
3. void setSelectedIcon(Icon si)
4. void setRolloverIcon(Icon ri)
Here, di, pi, si, and ri are the icons to be used for these different conditions.
The text associated with a button can be read and written via the following
methods:
1. String getText( )
2. void setText(String s)
Here, s is the text to be associated with the button.
JButton
The JButton class provides the functionality of a push
button.
JButton allows an icon, a string, or both to be associated
with the push button.
Some of its constructors are :
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
Check boxes
The JCheckBox class, which provides the functionality of a check box,
is a concrete implementation of AbstractButton.
Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is
true, the check box is initially selected. Otherwise, it is not.
The state of the check box can be changed via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be checked.
Combo boxes
Swing provides a combo box (a combination of a text field and a drop-
down list) through the JComboBox class, which extends
JComponent.
A combo box normally displays one entry. However, it can also display a
drop-down list that allows a user to select a different entry. You can also
type your selection into the text field.
Two of JComboBox's constructors are :
JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box.
Items are added to the list of choices via the addItem( ) method,
whose signature is:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
Radio Buttons
Radio buttons are supported by the JRadioButton class, which is a
concrete implementation of AbstractButton.
Some of its constructors are :
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is
true, the button is initially selected. Otherwise, it is not.
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.
Tabbed Panes
A tabbed pane is a component that appears as a group of folders in a file
cabinet.
Each folder has a title. When a user selects a folder, its contents become visible.
Only one of the folders may be selected at a time.
Tabbed panes are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which extends
JComponent. We will use its default constructor. Tabs are defined via the
following method:
void addTab(String str, Component comp)
Here, str is the title for the tab, and comp is the component that should be
added to the tab. Typically, a JPanel or a subclass of it is added.
The general procedure to use a tabbed pane in an applet is outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this method
define the
title of the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.
Scroll Panes
A scroll pane is a component that presents a rectangular area in which a
component may be viewed. Horizontal and/or vertical scroll bars may be
provided if necessary.
Scroll panes are implemented in Swing by the JScrollPane class, which
extends JComponent. Some of its constructors are :
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
Here, comp is the component to be added to the scroll pane. vsb and hsb are
int constants that define when vertical and horizontal scroll bars for this scroll
pane areshown.
These constants are defined by the ScrollPaneConstants interface.
1. HORIZONTAL_SCROLLBAR_ALWAYS
2. HORIZONTAL_SCROLLBAR_AS_NEEDED
3. VERTICAL_SCROLLBAR_ALWAYS
4. VERTICAL_SCROLLBAR_AS_NEEDED
Here are the steps to follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the constructor specify
thecomponent and the policies for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet.
Trees
Data Model - TreeModel
default: DefaultTreeModel
getChild, getChildCount, getIndexOfChild, getRoot,
isLeaf
View - TreeCellRenderer
getTreeCellRendererComponent
Node - DefaultMutableTreeNode
Tables
A table 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.
Tables are implemented by the JTable class, which extends JComponent.
One of its constructors is :
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.
Here are the steps for using a table in an applet:
1. Create a JTable object.
2. Create a JScrollPane object. (The arguments to the constructor specify
the table and
the policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.