Sun Microsystem Green Oak Java: Susceptible To Bugs That Can Crash System .In Particular, C++ Uses Direct
Sun Microsystem Green Oak Java: Susceptible To Bugs That Can Crash System .In Particular, C++ Uses Direct
• Object-oriented
Java defines data as object with method that supports the object–
oriented. Java is purely object–oriented. Any codes you write
,you have write in Class.
• Distributed
Java programs can access data across the web as easily as they
access data from a local system. Contd…
• Interpreted and Compiled
Java is both interpreted and compiled. A java
applet/Application is written and compiled into what
is called bytecode. This byte code is binary and
platform independent. When this applet has to be
executed it is fetched to the local system where it is
interpreted by the browser.
• Java is secure
A program traveling across the Internet onto your
machine is unseen by you and could possibly be
carrying a virus along with it. This is a possibility in
java program . But due to strong type checking done by
java on the users local machine, any changes to the
program are tagged as an error the program will not
executed.
• Multithreaded
Ability of an applet to perform multiple tasks at the
same time. For e.g.; suppose you are playing a
game one thread displaying score, one graphics. In
single threaded applet only one task can be
performed at a given point of time.
• Dynamic
A java program can consist of many modules that
are written by many programmers. These modules
may undergo many changes. Java makes
interconnection between modules at run time ,
which easily avoids the problem caused by the
changes of the code used by your program java
thus dynamic.
Process by which java sources code files are compiled and
interpreted.
Application/Applet
Bytecode is a standardized, machine
independent low level language. The
bytecode files are loaded,interpreted at
the client machine by a special program
called Java Virtual Machine [JVM] .
Basic Java Application
//This is first program of Java
public class MyFirstProg
{
public static void main(String args[])
{
System.out.println(“This is first
program”);
}
}
Assignment: Comparison:
=,+=,-=,*=,/=,%= ==,>,>=,<,<=,!=
Conditional
Iteration
if .. else Construct
This is used to check the condition.Its Syntax is:
if(condition)
Do Some action
This returns true if the checked condition is true otherwise false
class Hello
{
public static void main(String args[])
{
int iVar1=20, iVar2=10;
if (iVar1>iVar2)
System.out.println(“iVar1 is greater than iVar2”);
}
}
switch..case Construct
• Is used to successively test the value of an expression against a list of integer or
character constants.Only integer or character can be passed.
class Hello
{
public static void main(String args[])
{
int I=0;
switch(I)
{
case 0:
System.out.println(“Value is Zero”);
case 1:
System.out.println(“Value is One”);
case 2:
System.out.println(“Value is two”);
default:
System.out.println(“None of the condition is true”);
}
}
}
Iteration Construct
Loop Constructs:
• Are used to repeat a section of the
program a certain number of times
• Are categorized as:
– while
– do..while
– for
while Loop
• Repeats the body of the loop as long as the loop
condition is true
class Hello
{
public static void main(String args[])
{
int iNum=1;
while ( iNum<=100)
{
System.out.println(iNum);
iNum= iNum +1;
}
}
}
do..while Loop
• Executes the body of the loop at least once
• Tests the expression at the end of the loop
• Takes the form:
do
{
.
.
.
} while(Condition test);
for Loop
Is used for fixed iterations.Syntax is :
for(initialization,condition,step value)
class Hello
{
public static void main(String args[])
{
int iVar;
for(iVar=1; iVar<=10; i++)
{
System.out.println(iVar * iVar);
}
}
}
for Loop (contd.)
The statement:
for(iVar=0; iVar<=10; iVar++)
consists of three parts:
iVar=0 is the initialization expression,
iVar<=10 is the test expression and
iVar++ is the increment expression
break Statement
• Is used to terminate a case in a switch
construct
• Is also used to terminate a loop
construct
continue Statement
• Is used to skip all subsequent
instructions in a loop and take the
control back to the beginning of loop
Array
Are a collection of elements of the same
type and referenced by a common name
Elements of an array are referred to by an
array name and a subscript
Array subscript starts from zero
All elements in an Array must of the same
data type
Mainly used for grouping related
information
Declaration
There are two ways to declare:
• Place a pair of bracket after the
variable type .
• Place brackets after the identifier
name.
int MyIntArray[];
Or
int []MyIntArray;
Allocation of Space and Data Placement
0 1 2 3 4 5 6 7 8 9
Initializing Array
• Array can be initialize as:
Num[5]=10;
Num[10]=11;
int Num[]={10,20,30,40,50};
Getting the Size of an Array
To get the size of an array:
arrayname.length
class ArrayDemo
{
public static void main(String args[])
{
int num[];
num=new int[5];
System.out.println("Size is :"+num.length);
}
}
Double Dimensional Array
• Single dimensional made up of
either row or column.
• Is made up of rows and columns.
• Each element can be accessed by
row and column subscripts.
Two-dimensional Character Array
Declaration
char arrayname[x][y];
where:
x: is number of rows
y: is number of columns
Initializing Two-dimensional Arrays
char Weekdays[7][10] = {
“Sunday”,
“Monday”,
“Tuesday”,
“Wednesday”,
“Thursday”,
“Friday”,
“Saturday”
};
Object-Oriented Language
A language which supports the following
features:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
It combines both data and the functions into a
single unit called an object
• Offers data encapsulation
• Is used to create Abstract Data Types
Characteristics of Object-oriented
Language
• Realistic in Nature
• Reusability of code
• Resilience to Change
Class
A class is a Blue Print/Prototype that defines the variables and the methods common to all
Objects of certain kind.
In the real world, you often have many objects of the same kind. For example: Your Bicycle
is really just one of the many Bicycles in the world .If we talk in language of Object
Oriented terminology, we say that your bicycle object is an instance of the class of Objects
known as BICYCLES. All objects have some state (Current gear, current cadence, two
wheels) and behavior (changing gears, braking) in common.
When producing bicycles, manufacturers take advantage of the fact that bicycle from the
same blueprint -it would be very inefficient to produce a new blueprint for every individual
bicycle manufactured.
Software "blueprints" for objects is called CLASSES. For e.g.; you could create the bicycle
class that would declare several variables to contain the current gear, the current gear
cadence etc. It would also declare and provide implementations for the methods that allows
the rider to change gears ,brake and change the pedaling cadence.
The values for variables are provided by each instance of the class .So after you’ve created
the bicycle class, you must instantiate it(Create instance of it) before you can use it .when
you create an instance of class , the variable declared by class are allocated space in the
memory.
BENEFIT:
Reusability of Code.
Syntax
• It is collection of member variables and functions.It is
created using the keyword class . A class declaration
defines a new type. This new type is then used to
declare objects of that class . Thus a class is a logical
abstraction , but an object has physical existence .An
object is an instance of a class.
[access specifier][modifier]class <class-
name>
{
statements
}
Example
class MyClass
{
int RegNo; VARIABLES
String Name;
}
• Class defines a type of data.Here it is “MyClass”
• Note:Class declaration only creates template; it
does not create an actual object
Defining the Object
An object is an instance(example) of a class
Syntax:
<ClassName> <objectname>;
<objectname>=new <ClassName>;
MyClass my;
my=new MyClass();
synchronized No Yes No No
native No Yes No No
transient No No Yes No
volatile No No Yes No
Use:
FlowLayout flow=
new FlowLayout (FlowLayout.RIGHT, 10 , 10);
getContentPane().setLayout(flow);//To set the Layout
• BorderLayout:
– This enables us to position
component using the directions
North,South, West , East & Center.It
is default layout for JFrame and
JApplet. A maximum of five
components can be displayed in the
container.The constructors are:
– BorderLayout()
– BorderLayout(int hgap,int vgap);
• GridLayout:
– It divides the screen into equal-sized
rows and columns producing a
spreadsheet arrangement. The
constructors are:
– GridLayout(int rows,int cols)
– GridLayout(int rows,int cols,int
hgap,int vgap)
Card Layout
– It is used to create a stack of layouts with the
layouts arranged one behind the other.It shows
only one card at a time.The Constructor is:
– CardLayout()
– The methods are:
– first(Container container)
– next(Container container)
– previous(Container container)
– last(Container container)
– show(Container container,String CardName)
Box Layout
It is used to create a stack of layouts with the
layouts arranged in a row vertically or
horizontally in a container.The Constructor is :
BoxLayout(Panel pan,axis)
Where axis may be :
BoxLayout.X_AXIS
BoxLayout.Y_AXIS
Box Layout (Contd.)
Box Layout with two panels arranged in a row
horizontally
• GridBagLayout:
– This is most complex and highly flexible layout manager.The
basis is a grid.Unlike GridLayout components in the
GridBagLayout manager are not constrained to a single ,
regular cell.
– The way the applet specifies the size and position
characteristics of its components is specifying constraints for
each component.To specify constraint, set the variables in a
GridBagConstraints objects and specify the GridBagLayout
with setConstraints() method ,to its associate the constraints
with the component.
– GridBagLayout clas has single constructor which does not take
any argument.
– Position of each component in a layout is controlled by a
GridBagLayout object and is determined by the currently set
GridBagConstraints object.This also does not take any
argument.
– It’s an extension of the GridLayout
Manager, but differs in following
ways:-
– Component can take up more than
one cell in the grid.
– The proportion between rows and
columns do not have to be equal .
– Component inside grid cells can be
arranged in different ways
– It has following data members:
• gridx,gridy:
– They are cell coordinates of the cell that contains the
components . GridBagConstraints.RELATIVE which
is default , is used to specify the component should be
placed just to right of (gridx) or just below (for gridy)
the component added to the container before this
component.
• gridwidth,gridheight:
– They are number of cells the component
spans(stretch) .gridwidth for columns , gridheight for
rows.Default value is 1 .
• weightx,weighty:
– They are used to set up the proportions of rows and
columns . They determine whether the components
stretch horizontally/vertically to fill up the display
area.
• fill:
– If the component is smaller than its cell(s),this
variable determine whether to resize the component
to fit into the available area.It has following values:
• GridBagConstraints.NONE(don’t resize)
• GridBagConstraints.HORIZONTAL(make use of width)
• GridBagConstraints.VERTICAL(make use of height)
• GridBagConstraints.BOTH(make use of all the space)
• anchor:
– If the component is smaller than its cell(s),this
variable determine what corner or edge of the cell
area to attach the component to.Valid arguments are:
• GridBagConstraints.CENTER , NORTH , EAST , SOUTH,
WEST, NORTHWEST , NORTHEAST , SOUTHEAST,
SOUTHWEST
• Events:
– If you are asleep early in the morning and your
alarm clock goes off, That is an Event.An event
an unexpected external happening.
– An event represents a user’s interaction with
the program . When a user performs an action
such as mouse click, the system creates an
event and passes it to the program event
handling methods.The event handling method
than respond with the relevant behavior for
that event .For eg: when user clicks “submit”
button , the data associated with the dialog is
sent to the appropriate Server.
• Components of Event:-
– Event Object:An event is an object that
describes a state change in a source. It can be
generated as a consequences of person
interacting with the elements in a GUI .Some
of activities that cause event to be generated
are pressing a button , entering a character via
keyboard, selecting an item in a list and
clicking the mouse .
– Event may may be generated when a timer
expires , a counter exceeds a value , a
software/hardware failure occurs, or an
operation is completed .
– Event SourceA source is an object that generates an event.
This occurs when the internal state of that object changes in
some way.Sources may generate more than one type of
event .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.
– Syntax is :
– public void addtypeListener(typelistener el)
– type is the name of the event
– el is a reference too the event listener
– For eg:
– To register keyboard event listener-addKeyListener()
– To register mouse motion listener-addMouseMotionListener()
– To register button event listener-addActionListener()
– When an event occurs, all registered listeners are notified
and receive a copy of the event object.This is multicasting
the event.In all cases , notifications are sent only to
listener that register to receive them.
Event Listener(Handler)Listener is an object that is
notified when an event occurs.It has two major
requirements:
– It must have been registered with one/more sources to
receive notification about specific type of events.
– It must implement methods to receive and process these
notifications.
– The methods receive and process events are defined in a
set of interface found in java.awt.event.
• Root Classes:
– Root of event class hierarchy is
EventObject.Superclass for all events.It
has only one
constructor:EventObject(Object src)
– Where src is object that generates this event
• Event Delegation:
– The process of assigning an object to
handle a component event is called
delegation.Java 1.1 onwards supports
event delegation model.
Event Classes
• Interface:
– They are abstract classes that are left
completely unimplemented.The benefits
are same as abstract classes.Interface
provide a means to define protocols for a
class without worrying about the
implementation details.At a time we can
extend only one class , but we implement
more than one interface,so we can
implement concept of multiple inheritance.
– Limitation with interface is that we have to
override all the methods in the interface.
• Steps:
–Implement the appropriate
interface in the listener so that it
will receive the type of event
desired.
–Implement code to register the
listener as a recipient for the
event notifications.
import java.awt.*;import java.awt.event.*;
import java.applet.Applet;
public class Delegate extends Applet
{TextField text1; Button b1;
public void init()
{ text1=new TextField(20);
add(text1);
button =new Button("OK");
add(b1);
ButtonListener blisten=new ButtonListener();
b1.addActionListener(blisten); }
class ButtonListener implements ActionListener
{ public void actionPerformed(ActionEvent event)
{ String msg="Hello from Java!!!";
if(event.getSource()==b1)
{ text1.setText(msg); }
}
}
}
import java.applet.Applet;import java.awt.*;
import java.awt.event.*;
public class EvetYour extends Applet implements ActionListener
{ TextField text1;Button b1;
public void init()
{ text1=new TextField(20);
add(text1);
b1 =new Button("OK");
add(b1);
b1.addActionListener(this);}
public void actionPerformed(ActionEvent event)
{ String msg="Hello from Java!!!";
Object obj=event.getSource();
if(obj==b1)
{ text1.setText(msg);} }}
Exception
• An Exception is an abnormal condition that
disrupts normal flow of program .There are many
cases when abnormal conditions happen during
program execution ,such as:
– The file you try to open may not exist.
– The class file you want to load is missing or in wrong
format.
– The other end of network connection may be non-
existent.
– An operand is not in the legal range prescribed for
operation/methods.
If these abnormal condition is not prevented or at least
handled properly ,either the program will be aborted
abruptly or incorrect results or status will be carried
on ,causing more and more abnormal conditions
Exception Hierarchy
Throwable
Error Exception
Dead
• Every thread after creation and before destruction, will
always be in one of the four states:
• Newly Created: A thread enters the newly created state
immediately after creation. In this state, the local data
members are allocated and initialized. After the start()
method is called, the thread will be put into the runnable
state.
– Thread newThread=new Thread(this)
– //this- current instance
• Runnable:
Runnable In this state, the execution context exists and
the thread can be scheduled to run at any time. This
state is divided into 2 sub states: the running and
queued. When it is in running state, it is assigned CPU
cycles and is actually running. When thread is in the
queued state, it is waiting in the queue and competing
for its turn to spend CPU cycles.
• Blocked(Not Runnable): The blocked state is entered when
one of the following event occurs:
– The thread itself or another thread calls the suspend()
method
– The thread call an object’s wait() method
– The thread itself calls the sleep() method
– The thread is waiting for some I/O operation to complete
A thread in a blocked state will not be scheduled for
running. It will go back to the runnable state when the
following events occurs:
– If suspended, another thread calls its resume() method.
– If by wait() method, the object’s notify() or notifyAll()
method called
– If put to sleep(), the sleeping time elapsed.
– If I/O, the specified I/O operation completes.
• Dead Thread:
– The dead state is entered when a thread finishes
its execution or is stopped by another thread
calling its stop() method.
• How to create Thread:
– Java has both a class and interface that can be
used to create threaded applet or applications.
Java support for thread is found in the java.lang
package in the Thread class and the one interface
Runnable. There are two ways:
– By implementing a Runnnable interface
– By extending Thread class
• Synchronization:When two or more threads need
access to a shared resource , they need some way to
ensure the resource will be used by only one thread
at time .The time by which it is achieved is called
Synchronization
• Key to synchronization is the concept of
monitor(also called semaphore).A monitor is an
object that is used as a mutually exclusive lock, or
mutex.Only one thread can own a monitor at a
given time . When a thread acquires a lock , it is
said to have entered the monitor. All other threads
attempting to enter the locked monitor will be
suspended until the first thread exists the
monitor.These other threads are said to be waiting
for the monitor.A thread that owns a monitor can
reenter the same monitor if it so desires.
• User can synchronize their code in
two ways:
–By using synchronized method
–By using synchronized statement
• DeadLock:
– This situation occurs when two threads have a
circular dependency on a pair of synchronized
objects.For e.g. Suppose one thread enters the
monitor on object X and other thread enters the
monitor on object Y.If the thread in X tries to
call any synchronized method on Y , it will block
as expected.However if the thread in Y , in turn
tries to call any synchronized method on X the
thread waits forever , because to access X , it
would have to release its own lock on Y so that
the first thread could complete.
STREAMS: A Stream is a continuous flow of
data from source to a destination , it could be from
memory to hard disk , from network to local
system or from one area of memory to another.If
stream is used as source of information , it is called
an Input Stream.If
Stream stream is used as a destination
for information it is called an Output Stream.
Stream
Java defines two types of streams:Byte and
Character. Byte streams provides a convenient
means of handling input and output of bytes.They
are used when reading and writing binary data.
Character Streams provide a convenient means for
handling input and output of characters.
• Byte Stream Classes: It is defined by
using two classes hierarchies . At the top
are two abstract classes :InputStream and
OutputStream .They define several
methods that the other stream classes
implement .Two of the most important are
read() and write() which are used to read
and write bytes of data.
• Character Stream Classes: It is also
defined by using two class hierarchies.At
the top are two abstract classes Reader and
Writer.
• Methods of InputStream:
– int available() :No. of bytes available
– void close() :Closes the input stream
– int read() :To read bytes
– int read(byte buff[]):Read up to buffer-
length bytes into buffer
– int read(byte buff[],int start,int end):
Attempts to read up to end into
buffer starting at start
• Methods of OutputStream:
– void write(int n) :Write specified byte
to an output stream
– void write(byte []b):Write an array of
bytes
– void write(byte []b,int start,int end):
Attempts to write up to end into buffer
starting at start
– void flush() :Forces to writes whenever
the data accumulates in the output stream
– void close() :Closes output stream.
• FileInputStream:
– This is used to read bytes from file.The
available Constructors are:
– FileInputStream(String filepath);
– FileInputStream(File fileobj);
FileInputStream fi=new FileInputStream(“file1.txt”);
File f=new File(“file1.txt”);
FileInputStream fi=new FileInputStream(f);
• FileOutputStream:
– This is used to write bytes to a file.The
available Constructors are:
– FileOutputStream(String filepath);
– FileOutputStream(File fileobj);
– FileOutputStream(String fil,boolean app);
FileOutputStream fo=new FileOutputStream(“file1.txt”);
FileOutputStream fo=new FileOutputStream(“file1.txt”,true);
• Character Streams: Like input and output
stream here , Reader and Writer are abstract
classes.
• File Reader: It is used to read contents of a file. It
has two constructors.
– FileReader (String filepath)
– FileReader (File fileobj)
• FileWriter: It creates a writer that is can used to
write to a file.Constructors are:
– FileWriter (String filepath)
– FileWriter (String path, boolean append)
– FileWriter (File obj)
• RandomAccessFile:It
RandomAccessFile: is used to read
from or written to random locations
within file.It implements the interfaces
DataInput and DataOutput.It also
supports positioning requests- that is
we can position the file pointer within
the file.It has two constructors:
• RandomAccessFile(File obj,String access)
• RandomAccessFile(String filename,String access)
– Where access is either r or rw
• Methods are:
– seek(long value):To set current position of
file pointer within file.Next read write will
occur at the new file pointer
– getFilePointer():Returns current location.
– length():Length of file in terms of byte.
Networking
Client/Server Model:
Server:
One who Serves on request of client
Client:
One who request for service to the
Server.
The communication between Server and
client is termed as Networking
• Protocols:
– When computers communicate , they need to follow certain
rules like human .Data is sent from one machine to another
machine in the form of packets . Rules govern packaging of
data into in the form of packets, speed of transmission and
recreation of data to its original form .These rules are called
network protocol .Network protocols are set of rules and
conventions followed by systems that communicate over a
network.Examples of Protocols are:
– TCP/IP
– UDP(User Datagram Protocol)
– ICMP(Internet Control Message Protocol)
– AppletTalk
– IGMP(Internet Group Multicast Protocol)
– NetBEUI
• In JAVA there are two tools for communication
– Datagram that uses UDP
– Sockets that uses TCP/IP
• A Datagram packet is an array of bytes sent from
one program to another.They are unreliable as there
is no guarantee that the data packet that user is
sending will reach its destination.It just transmit
data with IP address and Port as the destination of
the packet.They are used only when the data to be
transmitted is very less and the distance between
sender and receiver is not very large.There is chance
of packet getting lost if the network traffic is very
high , or receiving program is handling multiple
request simultaneously from other programs.It can
send only a 65,536 bytes packet.
• Sockets on the other hand , use TCP for
communication .The advantage of Socket
model is that the server is not affected by
the source of client requests.It services all
requests, as long as the client follow the
TCP/IP protocol .Any Computer that
support TCP/IP can talk to any other
computer that supports it through the
socket model.
• Datagrams are faster than Sockets because
there is no overhead of establishing a
connection.Sockets however first establish
connection and then transmit.
• Internet Addressing Method:
– On the Internet every machine has an internal
address ,which is a number that uniquely identifies
each computer on the Net.An IP Address has 32-bits
and its is referred to as a sequence of four numbers
between 0-255 separated by dots(192.168.0.3).These
nos. are assigned hierarchically so that every machine
can be remembered easily.Since there are many
computers interconnected on the Internet , it is
difficult to remember the numeric address .To
overcome this problem , an alternative addressing
method is derived which is known as Domain Naming
Service(DNS).DNS is textual addressing method.The
general form is host.subdomain.domain (
www.sun.com).
– A port number is numeric address through which
service requests are processed.
• Socket:
A socket is a handle to communication link with
another application over the network .They are often
used in client/server application .A centralized service
waits for various remote machines to request specific
resources, handling each request as it arrives.In order
for clients to know how to communicate with server,
standard application protocols are assigned well-
known ports.
java.net Package:
It includes several classes and interfaces , which
provide support for networking.
• Steps:
1. Open a socket.
2. Open an input stream and output stream to the
socket.
3. Read from and write to the stream according to the
server's protocol.
4. Close the streams.
5. Close the socket.
• Creating Socket Client:
– Create Socket Class Object:
• Socket clisocket=new Socket(“127.0.0.1”,1001);
• Constructor takes two arguments IP Address/DNS name
and port no.
– Reading from and Writing to Socket:
• Two class are required for this purpose:
• PrintStream(For writing to Socket)
• BufferedReader(For reading from Socket)
• PrintStream out=new
PrintStream(clisocket.getOutputStream());
• BufferedReader in=new BufferedReader(new
InputStreamReader(clisocket.getInputStream());
– Closing Connection:
• out.close()
• in.close();
• Creating the Server:
• Create object of ServerSocket Class
– ServerSocket server=new ServerSocket(1001);
– ServerSocket server=bew ServerSocket(1001,2);
• accept() method:
– The accept() method waits for a client connection by
listening to the port to which it is bound.When client
attempts to connect to the server,the method accepts
the connection and returns a client socket.The socket
is later used for communication between the server
and its client.
Collections
• A collection is an object that contains a group of
objects within it. The contained objects are called
the elements of the collection
• The Java programming language supports collection
classes like Vector, Bits, Stack,
Hashtable, and LinkedList. A collection has
references to objects of the type Object
• The collection API typically consists of interfaces
that are used to maintain objects. These are the
Collection, Set, and List interfaces
The Vector Class
• The Vector class allows us to create dynamic
arrays that can contain multiple objects
• It provides methods for adding, removing, and
inserting elements
• Constructors are:
– Vector vector = new Vector();//By default initial
Capacity is of 10 elements
– Vector vector = new Vector(5);//Initial Capacity is of 5
elements grow by initial capacity
– Vector vector = new Vector(5,2);//Initial Capacity is of 5
elements grow by 2
• Adding Objects to Vectors:
– addElement(Object n):
• It adds the new object, n, as the last element in the vector
– insertElementAt(Object n, int index):
• It inserts a new object, n,at the position specified by the
index
– setElementAt(Object n, int index):
• It replaces the element at index with the object, n
• Removing Objects from vectors:
– removeElementAt(int index)
Accessing the Elements of a Vector:
– capacity() method:
• To see the capacity of Vector
– elementAt(int index)method :
• To access the elements of a vector.
– firstElement() method:
• To see the first element of vector
– lastElement() method:
• To see the last element of vector
– size()method:
• To find out the number of objects
present in a vector
The Stack Class
• The Stack class is a subclass of the Vector class.
• push() method:
– To add item in a Stack.
• pop() method:
– Remove the item from Stack.Last element will removed
first.
• search() method :
– To search for an object in a stack .
• empty() method :
– Returns true if a stack is empty.
Inter-thread Communication
– The communication between threads is called inter-
thread communication
– Inter-thread communication is achieved using four
methods – wait(), notify(), notifyAll(),
and yield()
– They can only be called from a synchronized
method
– A synchronized method is used when access has
to be coordinated for an object
– We can invoke only one synchronized method
for an object at any given point of time. This
prevents conflicts between the synchronized
methods in multiple threads
• The wait() Method:
– The wait()method tells the current thread to give up the
monitor and sleep until another thread calls the notify()
method
– Syntax:
• public final void wait() throws InterruptedException;