SlideShare a Scribd company logo
1 of 42
Download to read offline
SRI VASAVI COLLEGE,ERODE
(Self -Finance Wing)
Department of Computer Science
I-M.Sc (CS)
Advanced Java Programming
Unit-1
Presented by
P.KALAISELVI
Assistant Professor
Department of Computer Science
 What is Java?
◦ Java is a high level programming language and also
known as platform because of its JRE (java runtime
environment).
 Brief History of Java.
◦ Java language project initially started in June 1991 by
James Gosling, Mike Sheridan, and Patrick Naughton.
An oak tree stood outside Gosling’s office at that time
and java named as oak initially. It later renamed as
Green and was later renamed as java from java coffee.
 Base concept of java language project.
◦ Write once, run anywhere (WORA) – that means java
program can run anywhere and on any platform. When
java code is compiled it is converted into byte code.
Now only this byte code is needed to run using JVM, no
need of source code and recompilation.
 Java released versions:
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
11. Java SE 9 (21th Sept, 2017)
12. Java SE 10 (20th March, 2018)
13. Java SE 11 (25th Nov, 2018)
14. Java SE 12 (19th March, 2019)
 Java features:
1. Simple, easy and familiar:
◦ Java is easy to learn and familiar because java syntax is
just like c++.
◦ It is simple because:
◦ a) it does not use header files.
◦ b) eliminated the use of pointer and operator
overloading.
2. Platform Independent:
◦ Write once, run anywhere (WORA).
3.Object-Oriented:
◦ Java is Object oriented throughout language- that mean
no coding outside of
◦ class definitions, including main().
4. Robust:
◦ Robust means inbuilt capabilities to handle
errors/exceptions.
◦ Java is robust because of following:
1. Built-in Exception handling.
2. Strong type checking i.e. all data must be declared an
explicit type.
3. Local variables must be initialized.
4. Automatic garbage collection.
5. First checks the reliability of the code before Execution
etc.
5. Secure:
◦ Java is secure because it provides:
◦ 1. access restrictions with the help of access modifiers
(public, private etc).
◦ 2. byte codes verification – checks classes after loading.
◦ Class loader – confines objects to unique namespaces.
◦ Security manager – determines what resources a class
can access such as reading and writing to the local disk.
6. Distributed:
◦ Java provides the network facility. i.e. programs can be
access remotely from any machine on the network rather
than writing program on the local machine. HTTP and
FTP protocols are developed in java.
7. Compiled and interpreted:
◦ Java code is translated into byte code after compilation
and the byte code is interpreted by JVM (Java Virtual
Machine). This two steps process allows for extensive
code checking and also increase security.
9. Architecture-Neutral:
◦ Java code is translated into byte code after compilation
which is independent of any computer architecture, it
needs only JVM (Java Virtual Machine) to execute.
10. High performance:
◦ JVM can execute byte codes (highly optimized) very fast
with the help of Just in time (JIT) compilation technique.
11. Re-usability of code:
◦ Java provides the code reusability With the Help of
Inheritance.
12. Multithreading:
◦ Java provides multitasking facility with the help of
lightweight processes called threads.
13. Dynamic:
◦ Java have the capability of linking dynamic new classes,
methods and objects.
 Exception:
◦ Exception refers to an exceptional event. Exception is an
event that disrupts the normal flow of the program, during
program execution
 Exception object:
◦ When an error occurs within a method, the method creates an
object and hands it to the runtime system. This object is
known as exception object. It contains the information of the
error.
 Throwing an exception:
◦ It is a process of handing an exception object to the runtime
system.
 Catch the exception:
◦ It is a process of finding something which can handle
exception object.
 Exception handler:
◦ It is a block of code that can handle the exception is known
as exception handler.
 Exceptional handling:
◦ Exception handling is a mechanism to handle runtime
errors, so that normal flow of the program can be
maintained.
 Exception Hierarchy:
◦ Throwable is the super class.
 Advantages/Benefits of exceptional handling:
◦ Using exceptional handling we can separate the error
handling code from normal code.
◦ Using exceptional handling we can differentiate the
error types.
◦ Normal flow of program can be maintained.
 Types of Exception:
◦ Checked exception.
◦ Unchecked exception.
◦ Error.
 Checked exceptions:
◦ Checked exceptions are those exceptional conditions
that are checked by compiler at the compile time. A
checked exception forces you to either use try-catch or
throws. All exceptions except Error, RuntimeException,
and their subclasses are checked exceptions.
◦ e.g. – IOException, SQLException etc.
 Unchecked exceptions:
◦ Unchecked exceptions are those exceptional conditions
that are not checked by compiler at the compile time.
Unchecked exceptions are checked at runtime. An
unchecked exception not forces you to either use try-
catch or throws. RuntimeException and their subclasses
are unchecked exceptions. This Exception can be
avoided by programmer.
◦ e.g. – NullPointerException, ArithmeticException etc.
 Error:
◦ Errors are those exceptional conditions that are not
checked by compiler at the compile time. Errors are
checked at runtime. An error not forces you to either
use try-catch or throws. Error and their subclasses are
represents errors. Error can’t be avoided by
programmer, it is irrecoverable.
◦ e.g. – OutOfMemoryError etc.
 How to write an exception handler?
◦ To write a simple exception handler, first enclose the
code that might throw an exception within try block.
When an exception occurs in try block, it will be
handled by an appropriate exception handler.
Exception handler can associate with try block by using
catch block or finally block after it.
Note: catch and finally block both can be attached with
single try block. Hierarchy should be try-catch-finally.
◦ To understand more, let us see the keywords used in
exception handling.
 try
 catch
 finally
 throw
 throws
Try And Catch Blocks In Java
 try block :
◦ try block is used to enclose the code that might throw
an exception. It must be followed by either catch or
finally or both blocks.
 Syntax of try block with catch block:
try{
//block of statements
}catch(Exception handler class){
}
 Syntax of try block with finally block:
try{
//block of statements
} finally {
}
 Syntax of try block with catch and finally block:
try{
//block of statements
}catch(Exception handler class){
}finally{
}
 catch block:
◦ Catch block is used for exception handler. It is used
after try block.
◦ Syntax :
try{
//block of statements
}catch(Exception handler class){
}
class ArithmaticTest
{
public void division(int num1, int num2)
{
try
{
System.out.println(num1/num2);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Remaining code after exception handling.");
}
}
public class ExceptionHandlingExample2
{
public static void main(String args[])
{ArithmaticTest obj = new ArithmaticTest();
obj.division(20, 0);
}
}
 Output:
◦ java.lang.ArithmeticException: / by zero Remaining code after exception handling.
 Multiple catch blocks:
◦ If more than one exception can occur in one try block,
than we can use multiple catch blocks to provide
appropriate handler to different exception objects.
◦ Note: in case of multiple catch blocks, blocks must be
placed from specific handler to general handler.
 Syntax of try block with multiple catch blocks:
try{
//block of statements
}catch(Exception handler class subclass ){
} catch(Exception handler super class){
}
 MultipleCatchExample.java
class ArithmaticTest
{
int array[]={10,20,30,40};
int num1 = 50; int num2 = 10;
public void multipleCatchTest()
{
Try
{
System.out.println(num1/num2);
System.out.println("4th element of given array = " + array[3]);
System.out.println("5th element of given array = " + array[4]);
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
catch(ArithmeticException e)
{ System.out.println(e);}
catch(Exception e)
{System.out.println(e);}
System.out.println("Remaining code after exception handling.");
} }
public class MultipleCatchExample
{
public static void main(String args[])
{
ArithmaticTest obj = new ArithmaticTest(); obj.multipleCatchTest();
}
}
Output:
5 4th element of given array = 40
java.lang.ArrayIndexOutOfBoundsException: 4
Remaining code after exception handling.
 Throwable Class Methods In Java
1. getMessage(): returns the message string about the
exception.
◦ Syntax: public String getMessage()
2. getCause(): returns the cause of the exception. It
will return null is cause is unknown or non-existent.
◦ Syntax : public Throwable getCause()
3. toString(): returns a short description of the
exception.
◦ Discription of the exception = class name + “: “ + message.
◦ Syntax: public String toString()
4. printStackTrace(): prints the short description of the
exception(using toString()) + a stack trace for this
exception on the error output stream(System.err).
◦ Syntax: public void printStackTrace(PrintStream s)
 Multithreading:
◦ Multithreading is a type of multitasking based upon
threads i.e. context switching is done in-between
threads. In case of multithreading, multiple independent
tasks are executed simultaneously. These independent
tasks are the part of same application. Multithreading is
the type of multitasking which is handled at program
level.
 Thread:
◦ A thread is a lightweight process. Thread uses process’s
execution environment i.e. memory area. Context switch
time is less in case of threads because switch is done
within the same process’s memory area.
◦ A thread represents a flow of execution. Every thread has
a job associated with it.
◦ Note: A thread can’t be exist without process, it exist
within the process.
 Thread life cycle:
◦ New.
◦ Runnable.
◦ Running.
◦ Blocked(Non-Runnable).
◦ Dead.
1. New: A new thread is created but not working. A thread
after creation and before invocation of start() method
will be in new state.
2. Runnable: A thread after invocation of start()
method will be in runnable state. A thread in
runnable state will be available for thread
scheduler.
3. Running: A thread in execution after thread
scheduler select it, it will be in running state.
4. Blocked: A thread which is alive but not in
runnable or running state will be in blocked
state. A thread can be in blocked state because
of suspend(), sleep(), wait() methods or implicitly
by JVM to perform I/O operations.
5. Dead: A thread after exiting from run() method
will be in dead state. We can use stop() method
to forcefully killed a thread.
 Way of creating thread:
◦ By implementing Runnable interface.
◦ By extending Thread class.
 Important points:
◦ We discussed earlier that every thread has a job associated
with it. This job is what we are performing in run method.
◦ By default every program have one main thread. It may have
number of daemon threads. GC is a daemon thread. It is the
responsibility of main thread to start the child threads.
1. By implementing Runnable interface:
◦ To create a thread using Runnable interface, create a class
which implements Runnable interface. Runnable interface
have only one method run().
◦ Syntax:
 public void run()
 run() method will contain the code for created thread.
Now create a thread class object explicitly because our class is
not extending thread class and hence its object can’t be treated
as thread object. Pass class object that impleme
class Test implements Runnable
{
public void run()
{
System.out.println("thread started.");
}
}
public class CreateThreadExample2
{
public static void main(String args[])
{
Test obj = new Test();
thrd = new Thread(obj); thrd.start();
}
}
 Output: thread started.
2. By extending Thread class:
◦ Thread class provides methods to perform operations on
threads.
◦ Thread class is in Java.lang package.
◦ Syntax:
◦ public class Thread extends Object implements Runnable
 Commonly used constructors of Thread class:
1. Thread().
2. Thread(Runnable target).
target – the class object whose run method is
invoked when this thread is started. If null, this
thread’s run method is invoked.
3. Thread(String name).
name – the name of the new thread.
4. Thread(Runnable target, String name).
target – the class object whose run method is
invoked when this thread is started. If null, this
thread’s run method is invoked.
name – the name of the new thread.
class Test extends Thread{ public void run()
{
System.out.println("thread started.");
}
}
public class CreateThreadExample1
{
public static void main(String args[])
{
Test thrd1 = new Test();
thrd1.start(); } }
 Output:
 thread started.
 Methods Of Thread Class
1. public void start()
◦ starts thread to begin execution, JVM calls run method
of this thread.
◦ IllegalThreadStateException – if the thread was already
started.
2. public void run()
◦ run method is used to perform operations by thread.
3. public final void setName(String name)
◦ Changes the name of the thread.
◦ name – new name for this thread.
4. public final String getName()
◦ Returns this thread’s name.
5. public final void setPriority(int newPriority)
◦ Changes the priority of the thread.
◦ IllegalArgumentException – If the priority is not in the
range MIN_PRIORITY to MAX_PRIORITY.
6. public final int getPriority()
◦ Returns thread’s priority.
7. public final void join()
◦ The current thread invokes this method on a second
thread, causing the current thread to block until the
second thread terminates.
8. public final void join(long millisec)
◦ The current thread invokes this method on a second
thread, causing the current thread to block until the
second thread terminates or the specified number of
milliseconds passes.
9. public final void setDaemon(boolean on)
◦ Marks this thread as daemon thread if on is true.
10. public final boolean isDaemon()
◦ Returns true if thread is daemon.
11. public final boolean isAlive()
◦ returns true if thread is alive.
12. public long getId()
◦ Returns the ID of the thread(A long number generated at the
time of thread creation).
13. public void interrupt()
◦ Interrupts this thread and causing it to continue execution if
it was blocked.
14. public boolean isInterrupted()
◦ Returns true if thread is interrupted else return false.
15. public static void dumpStack()
◦ Prints a stack trace of the current thread.
16. public static void sleep(long millis)
◦ Causes the currently executing thread to sleep for the
specified number of milliseconds.
17. public static void yield()
 Causes the currently executing thread object to
temporarily pause and allow other threads to
execute.
18. public static Thread currentThread()
◦ Returns a reference to the currently running thread.
 Java Networking is a concept of connecting two
or more computing devices together so that we
can share resources.
 Java socket programming provides facility to
share data between different computing devices.
 Advantage of Java Networking
◦ Sharing resources
◦ Centralize software management
 The java.net package supports two protocols,
◦ TCP: Transmission Control Protocol provides reliable
communication between the sender and receiver. TCP is
used along with the Internet Protocol referred as TCP/IP.
◦ UDP: User Datagram Protocol provides a connection-
less protocol service by allowing packet of data to be
transferred along two or more nodes
 Java Networking Terminology
◦ The widely used Java networking terminologies are given below:
◦ IP Address
◦ Protocol
◦ Port Number
◦ MAC Address
◦ Connection-oriented and connection-less protocol
◦ Socket
1) IP Address
◦ IP address is a unique number assigned to a node of a network
e.g. 192.168.0.1 . It is composed of octets that range from 0 to
255.
◦ It is a logical address that can be changed.
2) Protocol
◦ A protocol is a set of rules basically that is followed for
communication. For example:
 TCP
 FTP
 Telnet
 SMTP
 POP etc.
3) Port Number
◦ The port number is used to uniquely identify different
applications. It acts as a communication endpoint between
applications.
◦ The port number is associated with the IP address for
communication between two applications.
4) MAC Address
◦ MAC (Media Access Control) address is a unique identifier of
NIC (Network Interface Controller). A network node can have
multiple NIC but each with unique MAC address.
◦ For example, an ethernet card may have a MAC address of
00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
◦ In connection-oriented protocol, acknowledgement is sent by
the receiver. So it is reliable but slow. The example of
connection-oriented protocol is TCP.
◦ But, in connection-less protocol, acknowledgement is not sent
by the receiver. So it is not reliable but fast. The example of
connection-less protocol is UDP.
6) Socket
◦ A socket is an endpoint between two way communications.
◦ Visit next page for Java socket programming.
 java.net package
◦ The java.net package can be divided into two sections:
◦ A Low-Level API: It deals with the abstractions of addresses i.e.
networking identifiers, Sockets i.e. bidirectional data
communication mechanism and Interfaces i.e. network
interfaces.
◦ A High Level API: It deals with the abstraction of URIs i.e.
Universal Resource Identifier, URLs i.e. Universal Resource
Locator, and Connections i.e. connections to the resource
pointed by URLs.
◦ The java.net package provides many classes to deal with
networking applications in Java. A list of these classes is given
below:
◦ Authenticator
◦ CacheRequest
◦ CacheResponse
◦ ContentHandler
◦ CookieHandler
◦ CookieManager
◦ DatagramPacket
◦ DatagramSocket
◦ DatagramSocketImpl
◦ InterfaceAddress
 MulticastSocket
 InetSocketAddress
 InetAddress
 Inet4Address
 Inet6Address
 IDN
 HttpURLConnection
 HttpCookie
 NetPermission
 NetworkInterface
 PasswordAuthentication
 Proxy
 ProxySelector
 ResponseCache
 SecureCacheResponse
 ServerSocket
 Socket
 SocketAddress
 SocketImpl
 SocketPermission
 StandardSocketOptions
 URI
 URL
 URLClassLoader
 URLConnection
 URLDecoder
 URLEncoder
 URLStreamHandler
 List of interfaces
available in java.net
package:
•ContentHandlerFactory
•CookiePolicy
•CookieStore
•DatagramSocketImplFac
tory
•FileNameMap
•SocketOption<T>
•SocketOptions
•SocketImplFactory
•URLStreamHandlerFacto
ry
•ProtocolFamily
 Multimedia basics in Java
◦ In broad sense, multimedia is the processing of audio,
video, image/graphics, and text in such a way that one
can create them, linked them, interact with them and all
these things in a real time fashion. Processing of all
these, although requires extra hardware support, and
presently, number of professional tools are readily
available in the market, but Java is unique because of its
incomparable feature of portability.
 Audio basics
◦ To play an audio data, it requires a specific format that
the working platform can support. Java can play back
audio data over a wide range of platforms. According to
Java convention, all audio data should come from a URL (
Universal Resource Locator ) in a .au audio file. In order
to use existing sounds in formats such as .wav or .aiff,
one need to convert these to .au using a sound program
that supports audio conversion.
 If one try to use .wav then Java is unable to support it and
throws an InvalidAudioFormatException, which will not play
the audio. The .au file refers to an 8-bit, 8Khz encoded audio
file. This format doesn't represent the state of the art in audio
fidelity, but is adequate for most sound clips.
 There are two ways to play a sound file from an
applet. The first way to play a, but uses a base URL
and file name to locate the audio file.
 sound is through the play() method and the other
through the AudioClip of the Applet class object.
◦ Using play() method :This method comes in two versions,
both of which take a URL for a sound file, load the file into
the memory, and then play the sound for one time.
◦ The play() method is as follows :
public void play (URL url ) - plays an audio clip if the audio
clip referred to by the URL is found. public void
play (URL url, String name) - same as the previous method
import java.applet.*;
import java.awt.*;
public class AudioPlayTest extends Applet
{
public void init ( )
{
setLayout (new FlowLayout (FlowLayout. CENTER )); Button
playButton = new Button ("Play" );
add (playButton );
}
public boolean action (Event e, object button)
{
if ("Play".equals (button))
{
play (getDocumentBase ( ), "audiobell.au" );
return true;
}
}
}
 This applet simply plays the audio file bell.au which is located in the
audio sub directory of the directory of the HTML file that loaded the
applet. The audio file is cached in memory before playing it.
 Note : URL actually a source of an object in Internet site. A typical URL
which is actually having various component may look like as below :
 Here, we have specified an audio file "music.au" which is available in
the sub directory "audio" at the server node "sun".
 There are two methods defined in Applet class, getDocumentBase()
and getCodeBase() which are very useful to load data from the
directory that had the HTML file that started the applet(document
base), and the directory that the class file was loaded from (code base
). These two methods return a URL object.
 Using Audio clip object :The disadvantage of using the play() method
is that the first time you call it with a given audio file, it will have to
down load the file if it hasn't been used before. This can happen
responsiveness in cases like the previous example, where we want to
play the sound in response to a user action, and the user ends up
waiting for the sound to load in response to hitting a button. Also,
the play() method is present only in the applet, which means that to
use it from a component, or from within a thread, we need to have a
reference to the applet. Last, the play() method plays a sound only
once and must be called again if one wants to play the sound next.
 The AudioClip object solves many of these limitations. To obtain an
AudioClip object, one has to call the Applet's getAudioClip() method,
which is defined as follows :
◦ public AudioClip getAudioClip (URL url ) - returns an AudioClip object. This
method will not return until the AudioClip has been loaded from the specified
URL, so one should consider placing it in a separate thread if the file is
expected to take a while to down load. public AudioClip getAudioClip (URL url,
String name ) - same as the previous method, but finds the audio file using the
base URL and file name.
◦ The AudioClip object specifies three methods which are stated below : public
abstract void loop( ) - plays the clip in a continuous loop.
◦ public abstract void play( ) - starts playing the clip from its beginning. public
abstract void stop( ) - stops the clip if it is currently playing. Here, audio played
by the AudioClip() is asynchronous play that can be possible with the above
three methods. Following is the Illustration 9.2 of an applet that plays a sound
as long as the applet is on - screen or until the 'Stop' button is clicked :
 // Play audio through Audio clip //
import java.applet.*;
import java.awt.*;
public class AudioClipTest extends Applet
{
AudioClip flute ;
AudioClip piano ;
public void init ( )
{
setLayout (new FlowLayout
(FlowLayout.CENTER ));
Button testButton = new Button ( "Start" );
add(testButton);
testButton = new Button( "Continue");
add(testButton);
testButton = new Button ( "Stop");
add(testButton);
flute = getAudioClip( getDocumentBase( ),
"flute.au");
piano = getAudioClip( getDocumentBase( ),
"piano.au");
}
public void start( )
{
piano.loop( ); }
public void stop( )
{piano.stop( ); }
public boolean action(
Event e, Object
button)
{
if( "Start".equals(button)
) flute.play( );
if(
"Continue".quals(butt
on) ) piano.loop( );
if (
"Stop".equals(button)
) piano.stop( );
return true;
}
}
 Image basics
◦ Java is popular because it has the promise of creating
rich graphical experiences. Java has a number of
classes designed to deal with images and image
manipulation. Java follows both JPEG (Joint
Photographic Expert Group) and GIF (Graphics
Interchange Format ) as the formats for image data. In
general , JPEG images are better suited to natural color
images such as photo graphs, and GIF images are best
for graphical logos, rules, and button images.
◦ There are five types of objects that one will need to
deal with or at least understand when dealing with
Images. These are :
 Image
 ImageObserver
 ImageProducer
 ImageConsumer
 ImageFilter
 These are basics, all of them defined in java.awt package,
and many more also related to image manipulation.
 Image class: With this class one can load an image object
that obtains its pixel data from a specific URL. The most
common way to do this is through the use of the
getImage() method of the java.applet.Applet class, which
has the following two forms :
◦ public Image getImage (URL url ) - returns an Image object
given a URL.
◦ public Image getImage (URL url, String name )- returns an
Image object given a base URL and file name.
◦ // Draw an Image //
import java.applet.*;
import java.awt.*;
public class ImageTest extends Applet
{
Image mona;
public void init ( )
{ mona = getImage (getDocumentBase ( ), "monalisa.gif ");
}
public void point (Graphics g ) { g.drawImage (mona, 0, 0, this); }
}
 In the above mentioned applet, first init() method loads the image
object from the specified URL and file name. The paint() method uses
drawImage() method ( it is defined in Component class); it has the
form as below :
◦ public abstract boolean drawImage ( Image imageName, int x, int y,
ImageObserver imgObs );
 imageName is the image reference that has to be drawn, the x, y
coordinates to paint at, and imgObs is the ImageObserver that can
monitors an image while it loads, we will learn more about it during
the subsequent discussion. In the above example Illustration, this
represents the default ImageObserver. When this applet runs, it starts
loading "monalisa.gif " in the init() method. On screen you can see the
image as it loads from the Network ( or local machine), because the
default ImageObserver interface calls paint() method every time more
image data arrives from the source.
 ImageObserver class :ImageObserver is an abstract interface used to
get notification as an image is being generated. As we have seen in
the last example, the drawImage() method takes both an Image object
and an ImageObserver object. In the case of an ImageObserver object,
because ImageObserver is an interface, we need to pass a reference to
an instance of a class that implements the ImageObserver interface.
Classes that implements the ImageObserver interface are required to
have an imageUpdate() method as follows :
◦ public abstract boolean imageUpdate (Image img, int status , int x, int y, int
width, int height);

More Related Content

Similar to Adv java unit 1 M.Sc CS.pdf

Similar to Adv java unit 1 M.Sc CS.pdf (20)

UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 

More from KALAISELVI P

ADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdfADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdfKALAISELVI P
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfKALAISELVI P
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc csKALAISELVI P
 
Pks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcsPks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcsKALAISELVI P
 
Pks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcsPks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcsKALAISELVI P
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)KALAISELVI P
 
Pks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcsPks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcsKALAISELVI P
 
Pks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcsPks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcsKALAISELVI P
 

More from KALAISELVI P (9)

ADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdfADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdf
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
Pks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcsPks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcs
 
Pks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcsPks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcs
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)
 
Pks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcsPks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcs
 
Pks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcsPks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcs
 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

Adv java unit 1 M.Sc CS.pdf

  • 1. SRI VASAVI COLLEGE,ERODE (Self -Finance Wing) Department of Computer Science I-M.Sc (CS) Advanced Java Programming Unit-1 Presented by P.KALAISELVI Assistant Professor Department of Computer Science
  • 2.  What is Java? ◦ Java is a high level programming language and also known as platform because of its JRE (java runtime environment).  Brief History of Java. ◦ Java language project initially started in June 1991 by James Gosling, Mike Sheridan, and Patrick Naughton. An oak tree stood outside Gosling’s office at that time and java named as oak initially. It later renamed as Green and was later renamed as java from java coffee.  Base concept of java language project. ◦ Write once, run anywhere (WORA) – that means java program can run anywhere and on any platform. When java code is compiled it is converted into byte code. Now only this byte code is needed to run using JVM, no need of source code and recompilation.
  • 3.  Java released versions: 1. JDK Alpha and Beta (1995) 2. JDK 1.0 (23rd Jan, 1996) 3. JDK 1.1 (19th Feb, 1997) 4. J2SE 1.2 (8th Dec, 1998) 5. J2SE 1.3 (8th May, 2000) 6. J2SE 1.4 (6th Feb, 2002) 7. J2SE 5.0 (30th Sep, 2004) 8. Java SE 6 (11th Dec, 2006) 9. Java SE 7 (28th July, 2011) 10. Java SE 8 (18th March, 2014) 11. Java SE 9 (21th Sept, 2017) 12. Java SE 10 (20th March, 2018) 13. Java SE 11 (25th Nov, 2018) 14. Java SE 12 (19th March, 2019)
  • 4.  Java features: 1. Simple, easy and familiar: ◦ Java is easy to learn and familiar because java syntax is just like c++. ◦ It is simple because: ◦ a) it does not use header files. ◦ b) eliminated the use of pointer and operator overloading. 2. Platform Independent: ◦ Write once, run anywhere (WORA).
  • 5. 3.Object-Oriented: ◦ Java is Object oriented throughout language- that mean no coding outside of ◦ class definitions, including main(). 4. Robust: ◦ Robust means inbuilt capabilities to handle errors/exceptions. ◦ Java is robust because of following: 1. Built-in Exception handling. 2. Strong type checking i.e. all data must be declared an explicit type. 3. Local variables must be initialized. 4. Automatic garbage collection. 5. First checks the reliability of the code before Execution etc.
  • 6. 5. Secure: ◦ Java is secure because it provides: ◦ 1. access restrictions with the help of access modifiers (public, private etc). ◦ 2. byte codes verification – checks classes after loading. ◦ Class loader – confines objects to unique namespaces. ◦ Security manager – determines what resources a class can access such as reading and writing to the local disk. 6. Distributed: ◦ Java provides the network facility. i.e. programs can be access remotely from any machine on the network rather than writing program on the local machine. HTTP and FTP protocols are developed in java. 7. Compiled and interpreted: ◦ Java code is translated into byte code after compilation and the byte code is interpreted by JVM (Java Virtual Machine). This two steps process allows for extensive code checking and also increase security.
  • 7. 9. Architecture-Neutral: ◦ Java code is translated into byte code after compilation which is independent of any computer architecture, it needs only JVM (Java Virtual Machine) to execute. 10. High performance: ◦ JVM can execute byte codes (highly optimized) very fast with the help of Just in time (JIT) compilation technique. 11. Re-usability of code: ◦ Java provides the code reusability With the Help of Inheritance. 12. Multithreading: ◦ Java provides multitasking facility with the help of lightweight processes called threads. 13. Dynamic: ◦ Java have the capability of linking dynamic new classes, methods and objects.
  • 8.  Exception: ◦ Exception refers to an exceptional event. Exception is an event that disrupts the normal flow of the program, during program execution  Exception object: ◦ When an error occurs within a method, the method creates an object and hands it to the runtime system. This object is known as exception object. It contains the information of the error.  Throwing an exception: ◦ It is a process of handing an exception object to the runtime system.  Catch the exception: ◦ It is a process of finding something which can handle exception object.  Exception handler: ◦ It is a block of code that can handle the exception is known as exception handler.
  • 9.  Exceptional handling: ◦ Exception handling is a mechanism to handle runtime errors, so that normal flow of the program can be maintained.  Exception Hierarchy: ◦ Throwable is the super class.
  • 10.  Advantages/Benefits of exceptional handling: ◦ Using exceptional handling we can separate the error handling code from normal code. ◦ Using exceptional handling we can differentiate the error types. ◦ Normal flow of program can be maintained.  Types of Exception: ◦ Checked exception. ◦ Unchecked exception. ◦ Error.  Checked exceptions: ◦ Checked exceptions are those exceptional conditions that are checked by compiler at the compile time. A checked exception forces you to either use try-catch or throws. All exceptions except Error, RuntimeException, and their subclasses are checked exceptions. ◦ e.g. – IOException, SQLException etc.
  • 11.  Unchecked exceptions: ◦ Unchecked exceptions are those exceptional conditions that are not checked by compiler at the compile time. Unchecked exceptions are checked at runtime. An unchecked exception not forces you to either use try- catch or throws. RuntimeException and their subclasses are unchecked exceptions. This Exception can be avoided by programmer. ◦ e.g. – NullPointerException, ArithmeticException etc.  Error: ◦ Errors are those exceptional conditions that are not checked by compiler at the compile time. Errors are checked at runtime. An error not forces you to either use try-catch or throws. Error and their subclasses are represents errors. Error can’t be avoided by programmer, it is irrecoverable. ◦ e.g. – OutOfMemoryError etc.
  • 12.  How to write an exception handler? ◦ To write a simple exception handler, first enclose the code that might throw an exception within try block. When an exception occurs in try block, it will be handled by an appropriate exception handler. Exception handler can associate with try block by using catch block or finally block after it. Note: catch and finally block both can be attached with single try block. Hierarchy should be try-catch-finally. ◦ To understand more, let us see the keywords used in exception handling.  try  catch  finally  throw  throws
  • 13. Try And Catch Blocks In Java  try block : ◦ try block is used to enclose the code that might throw an exception. It must be followed by either catch or finally or both blocks.  Syntax of try block with catch block: try{ //block of statements }catch(Exception handler class){ }  Syntax of try block with finally block: try{ //block of statements } finally { }
  • 14.  Syntax of try block with catch and finally block: try{ //block of statements }catch(Exception handler class){ }finally{ }  catch block: ◦ Catch block is used for exception handler. It is used after try block. ◦ Syntax : try{ //block of statements }catch(Exception handler class){ }
  • 15. class ArithmaticTest { public void division(int num1, int num2) { try { System.out.println(num1/num2); } catch(ArithmeticException e) { System.out.println(e); } System.out.println("Remaining code after exception handling."); } } public class ExceptionHandlingExample2 { public static void main(String args[]) {ArithmaticTest obj = new ArithmaticTest(); obj.division(20, 0); } }  Output: ◦ java.lang.ArithmeticException: / by zero Remaining code after exception handling.
  • 16.  Multiple catch blocks: ◦ If more than one exception can occur in one try block, than we can use multiple catch blocks to provide appropriate handler to different exception objects. ◦ Note: in case of multiple catch blocks, blocks must be placed from specific handler to general handler.  Syntax of try block with multiple catch blocks: try{ //block of statements }catch(Exception handler class subclass ){ } catch(Exception handler super class){ }
  • 17.  MultipleCatchExample.java class ArithmaticTest { int array[]={10,20,30,40}; int num1 = 50; int num2 = 10; public void multipleCatchTest() { Try { System.out.println(num1/num2); System.out.println("4th element of given array = " + array[3]); System.out.println("5th element of given array = " + array[4]); } catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);} catch(ArithmeticException e) { System.out.println(e);} catch(Exception e) {System.out.println(e);} System.out.println("Remaining code after exception handling."); } } public class MultipleCatchExample { public static void main(String args[]) { ArithmaticTest obj = new ArithmaticTest(); obj.multipleCatchTest(); } } Output: 5 4th element of given array = 40 java.lang.ArrayIndexOutOfBoundsException: 4 Remaining code after exception handling.
  • 18.  Throwable Class Methods In Java 1. getMessage(): returns the message string about the exception. ◦ Syntax: public String getMessage() 2. getCause(): returns the cause of the exception. It will return null is cause is unknown or non-existent. ◦ Syntax : public Throwable getCause() 3. toString(): returns a short description of the exception. ◦ Discription of the exception = class name + “: “ + message. ◦ Syntax: public String toString() 4. printStackTrace(): prints the short description of the exception(using toString()) + a stack trace for this exception on the error output stream(System.err). ◦ Syntax: public void printStackTrace(PrintStream s)
  • 19.  Multithreading: ◦ Multithreading is a type of multitasking based upon threads i.e. context switching is done in-between threads. In case of multithreading, multiple independent tasks are executed simultaneously. These independent tasks are the part of same application. Multithreading is the type of multitasking which is handled at program level.  Thread: ◦ A thread is a lightweight process. Thread uses process’s execution environment i.e. memory area. Context switch time is less in case of threads because switch is done within the same process’s memory area. ◦ A thread represents a flow of execution. Every thread has a job associated with it. ◦ Note: A thread can’t be exist without process, it exist within the process.
  • 20.  Thread life cycle: ◦ New. ◦ Runnable. ◦ Running. ◦ Blocked(Non-Runnable). ◦ Dead. 1. New: A new thread is created but not working. A thread after creation and before invocation of start() method will be in new state.
  • 21. 2. Runnable: A thread after invocation of start() method will be in runnable state. A thread in runnable state will be available for thread scheduler. 3. Running: A thread in execution after thread scheduler select it, it will be in running state. 4. Blocked: A thread which is alive but not in runnable or running state will be in blocked state. A thread can be in blocked state because of suspend(), sleep(), wait() methods or implicitly by JVM to perform I/O operations. 5. Dead: A thread after exiting from run() method will be in dead state. We can use stop() method to forcefully killed a thread.
  • 22.  Way of creating thread: ◦ By implementing Runnable interface. ◦ By extending Thread class.  Important points: ◦ We discussed earlier that every thread has a job associated with it. This job is what we are performing in run method. ◦ By default every program have one main thread. It may have number of daemon threads. GC is a daemon thread. It is the responsibility of main thread to start the child threads. 1. By implementing Runnable interface: ◦ To create a thread using Runnable interface, create a class which implements Runnable interface. Runnable interface have only one method run(). ◦ Syntax:  public void run()  run() method will contain the code for created thread. Now create a thread class object explicitly because our class is not extending thread class and hence its object can’t be treated as thread object. Pass class object that impleme
  • 23. class Test implements Runnable { public void run() { System.out.println("thread started."); } } public class CreateThreadExample2 { public static void main(String args[]) { Test obj = new Test(); thrd = new Thread(obj); thrd.start(); } }  Output: thread started.
  • 24. 2. By extending Thread class: ◦ Thread class provides methods to perform operations on threads. ◦ Thread class is in Java.lang package. ◦ Syntax: ◦ public class Thread extends Object implements Runnable  Commonly used constructors of Thread class: 1. Thread(). 2. Thread(Runnable target). target – the class object whose run method is invoked when this thread is started. If null, this thread’s run method is invoked. 3. Thread(String name). name – the name of the new thread. 4. Thread(Runnable target, String name). target – the class object whose run method is invoked when this thread is started. If null, this thread’s run method is invoked. name – the name of the new thread.
  • 25. class Test extends Thread{ public void run() { System.out.println("thread started."); } } public class CreateThreadExample1 { public static void main(String args[]) { Test thrd1 = new Test(); thrd1.start(); } }  Output:  thread started.
  • 26.  Methods Of Thread Class 1. public void start() ◦ starts thread to begin execution, JVM calls run method of this thread. ◦ IllegalThreadStateException – if the thread was already started. 2. public void run() ◦ run method is used to perform operations by thread. 3. public final void setName(String name) ◦ Changes the name of the thread. ◦ name – new name for this thread. 4. public final String getName() ◦ Returns this thread’s name. 5. public final void setPriority(int newPriority) ◦ Changes the priority of the thread. ◦ IllegalArgumentException – If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY.
  • 27. 6. public final int getPriority() ◦ Returns thread’s priority. 7. public final void join() ◦ The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates. 8. public final void join(long millisec) ◦ The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. 9. public final void setDaemon(boolean on) ◦ Marks this thread as daemon thread if on is true. 10. public final boolean isDaemon() ◦ Returns true if thread is daemon. 11. public final boolean isAlive() ◦ returns true if thread is alive.
  • 28. 12. public long getId() ◦ Returns the ID of the thread(A long number generated at the time of thread creation). 13. public void interrupt() ◦ Interrupts this thread and causing it to continue execution if it was blocked. 14. public boolean isInterrupted() ◦ Returns true if thread is interrupted else return false. 15. public static void dumpStack() ◦ Prints a stack trace of the current thread. 16. public static void sleep(long millis) ◦ Causes the currently executing thread to sleep for the specified number of milliseconds. 17. public static void yield()  Causes the currently executing thread object to temporarily pause and allow other threads to execute. 18. public static Thread currentThread() ◦ Returns a reference to the currently running thread.
  • 29.  Java Networking is a concept of connecting two or more computing devices together so that we can share resources.  Java socket programming provides facility to share data between different computing devices.  Advantage of Java Networking ◦ Sharing resources ◦ Centralize software management  The java.net package supports two protocols, ◦ TCP: Transmission Control Protocol provides reliable communication between the sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP. ◦ UDP: User Datagram Protocol provides a connection- less protocol service by allowing packet of data to be transferred along two or more nodes
  • 30.  Java Networking Terminology ◦ The widely used Java networking terminologies are given below: ◦ IP Address ◦ Protocol ◦ Port Number ◦ MAC Address ◦ Connection-oriented and connection-less protocol ◦ Socket 1) IP Address ◦ IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255. ◦ It is a logical address that can be changed. 2) Protocol ◦ A protocol is a set of rules basically that is followed for communication. For example:  TCP  FTP  Telnet  SMTP  POP etc.
  • 31. 3) Port Number ◦ The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications. ◦ The port number is associated with the IP address for communication between two applications. 4) MAC Address ◦ MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC address. ◦ For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e. 5) Connection-oriented and connection-less protocol ◦ In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP. ◦ But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP. 6) Socket ◦ A socket is an endpoint between two way communications. ◦ Visit next page for Java socket programming.
  • 32.  java.net package ◦ The java.net package can be divided into two sections: ◦ A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network interfaces. ◦ A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs. ◦ The java.net package provides many classes to deal with networking applications in Java. A list of these classes is given below: ◦ Authenticator ◦ CacheRequest ◦ CacheResponse ◦ ContentHandler ◦ CookieHandler ◦ CookieManager ◦ DatagramPacket ◦ DatagramSocket ◦ DatagramSocketImpl ◦ InterfaceAddress
  • 33.  MulticastSocket  InetSocketAddress  InetAddress  Inet4Address  Inet6Address  IDN  HttpURLConnection  HttpCookie  NetPermission  NetworkInterface  PasswordAuthentication  Proxy  ProxySelector  ResponseCache  SecureCacheResponse  ServerSocket  Socket  SocketAddress  SocketImpl  SocketPermission  StandardSocketOptions  URI  URL  URLClassLoader  URLConnection  URLDecoder  URLEncoder  URLStreamHandler  List of interfaces available in java.net package: •ContentHandlerFactory •CookiePolicy •CookieStore •DatagramSocketImplFac tory •FileNameMap •SocketOption<T> •SocketOptions •SocketImplFactory •URLStreamHandlerFacto ry •ProtocolFamily
  • 34.  Multimedia basics in Java ◦ In broad sense, multimedia is the processing of audio, video, image/graphics, and text in such a way that one can create them, linked them, interact with them and all these things in a real time fashion. Processing of all these, although requires extra hardware support, and presently, number of professional tools are readily available in the market, but Java is unique because of its incomparable feature of portability.  Audio basics ◦ To play an audio data, it requires a specific format that the working platform can support. Java can play back audio data over a wide range of platforms. According to Java convention, all audio data should come from a URL ( Universal Resource Locator ) in a .au audio file. In order to use existing sounds in formats such as .wav or .aiff, one need to convert these to .au using a sound program that supports audio conversion.
  • 35.  If one try to use .wav then Java is unable to support it and throws an InvalidAudioFormatException, which will not play the audio. The .au file refers to an 8-bit, 8Khz encoded audio file. This format doesn't represent the state of the art in audio fidelity, but is adequate for most sound clips.  There are two ways to play a sound file from an applet. The first way to play a, but uses a base URL and file name to locate the audio file.  sound is through the play() method and the other through the AudioClip of the Applet class object. ◦ Using play() method :This method comes in two versions, both of which take a URL for a sound file, load the file into the memory, and then play the sound for one time. ◦ The play() method is as follows : public void play (URL url ) - plays an audio clip if the audio clip referred to by the URL is found. public void play (URL url, String name) - same as the previous method
  • 36. import java.applet.*; import java.awt.*; public class AudioPlayTest extends Applet { public void init ( ) { setLayout (new FlowLayout (FlowLayout. CENTER )); Button playButton = new Button ("Play" ); add (playButton ); } public boolean action (Event e, object button) { if ("Play".equals (button)) { play (getDocumentBase ( ), "audiobell.au" ); return true; } } }
  • 37.  This applet simply plays the audio file bell.au which is located in the audio sub directory of the directory of the HTML file that loaded the applet. The audio file is cached in memory before playing it.  Note : URL actually a source of an object in Internet site. A typical URL which is actually having various component may look like as below :  Here, we have specified an audio file "music.au" which is available in the sub directory "audio" at the server node "sun".  There are two methods defined in Applet class, getDocumentBase() and getCodeBase() which are very useful to load data from the directory that had the HTML file that started the applet(document base), and the directory that the class file was loaded from (code base ). These two methods return a URL object.
  • 38.  Using Audio clip object :The disadvantage of using the play() method is that the first time you call it with a given audio file, it will have to down load the file if it hasn't been used before. This can happen responsiveness in cases like the previous example, where we want to play the sound in response to a user action, and the user ends up waiting for the sound to load in response to hitting a button. Also, the play() method is present only in the applet, which means that to use it from a component, or from within a thread, we need to have a reference to the applet. Last, the play() method plays a sound only once and must be called again if one wants to play the sound next.  The AudioClip object solves many of these limitations. To obtain an AudioClip object, one has to call the Applet's getAudioClip() method, which is defined as follows : ◦ public AudioClip getAudioClip (URL url ) - returns an AudioClip object. This method will not return until the AudioClip has been loaded from the specified URL, so one should consider placing it in a separate thread if the file is expected to take a while to down load. public AudioClip getAudioClip (URL url, String name ) - same as the previous method, but finds the audio file using the base URL and file name. ◦ The AudioClip object specifies three methods which are stated below : public abstract void loop( ) - plays the clip in a continuous loop. ◦ public abstract void play( ) - starts playing the clip from its beginning. public abstract void stop( ) - stops the clip if it is currently playing. Here, audio played by the AudioClip() is asynchronous play that can be possible with the above three methods. Following is the Illustration 9.2 of an applet that plays a sound as long as the applet is on - screen or until the 'Stop' button is clicked :
  • 39.  // Play audio through Audio clip // import java.applet.*; import java.awt.*; public class AudioClipTest extends Applet { AudioClip flute ; AudioClip piano ; public void init ( ) { setLayout (new FlowLayout (FlowLayout.CENTER )); Button testButton = new Button ( "Start" ); add(testButton); testButton = new Button( "Continue"); add(testButton); testButton = new Button ( "Stop"); add(testButton); flute = getAudioClip( getDocumentBase( ), "flute.au"); piano = getAudioClip( getDocumentBase( ), "piano.au"); } public void start( ) { piano.loop( ); } public void stop( ) {piano.stop( ); } public boolean action( Event e, Object button) { if( "Start".equals(button) ) flute.play( ); if( "Continue".quals(butt on) ) piano.loop( ); if ( "Stop".equals(button) ) piano.stop( ); return true; } }
  • 40.  Image basics ◦ Java is popular because it has the promise of creating rich graphical experiences. Java has a number of classes designed to deal with images and image manipulation. Java follows both JPEG (Joint Photographic Expert Group) and GIF (Graphics Interchange Format ) as the formats for image data. In general , JPEG images are better suited to natural color images such as photo graphs, and GIF images are best for graphical logos, rules, and button images. ◦ There are five types of objects that one will need to deal with or at least understand when dealing with Images. These are :  Image  ImageObserver  ImageProducer  ImageConsumer  ImageFilter
  • 41.  These are basics, all of them defined in java.awt package, and many more also related to image manipulation.  Image class: With this class one can load an image object that obtains its pixel data from a specific URL. The most common way to do this is through the use of the getImage() method of the java.applet.Applet class, which has the following two forms : ◦ public Image getImage (URL url ) - returns an Image object given a URL. ◦ public Image getImage (URL url, String name )- returns an Image object given a base URL and file name. ◦ // Draw an Image // import java.applet.*; import java.awt.*; public class ImageTest extends Applet { Image mona; public void init ( ) { mona = getImage (getDocumentBase ( ), "monalisa.gif "); } public void point (Graphics g ) { g.drawImage (mona, 0, 0, this); } }
  • 42.  In the above mentioned applet, first init() method loads the image object from the specified URL and file name. The paint() method uses drawImage() method ( it is defined in Component class); it has the form as below : ◦ public abstract boolean drawImage ( Image imageName, int x, int y, ImageObserver imgObs );  imageName is the image reference that has to be drawn, the x, y coordinates to paint at, and imgObs is the ImageObserver that can monitors an image while it loads, we will learn more about it during the subsequent discussion. In the above example Illustration, this represents the default ImageObserver. When this applet runs, it starts loading "monalisa.gif " in the init() method. On screen you can see the image as it loads from the Network ( or local machine), because the default ImageObserver interface calls paint() method every time more image data arrives from the source.  ImageObserver class :ImageObserver is an abstract interface used to get notification as an image is being generated. As we have seen in the last example, the drawImage() method takes both an Image object and an ImageObserver object. In the case of an ImageObserver object, because ImageObserver is an interface, we need to pass a reference to an instance of a class that implements the ImageObserver interface. Classes that implements the ImageObserver interface are required to have an imageUpdate() method as follows : ◦ public abstract boolean imageUpdate (Image img, int status , int x, int y, int width, int height);