Sunteți pe pagina 1din 66

JAVA

Exception
An exception is an event that occurs during the
execution of a program that disrupts the normal
flow of instructions.
At compilation time syntax and semantics
checking is done and code is not executed on
machine so exceptions can only be detected
at run time.
JREtries to find someone that can handle the
raised exception.
When an exception occurs within a method, the
method creates an exception object and hands it
off
to
the
runtime
system.
This
is
calledthrowing
the
exception.
The
exception object contains a lot of debugging

Exception handling
After a method throws an exception, the runtime
system receives the exception object, it tries to
find the handler for the exception. Exception
Handler is the block of code that can process the
exception object.
If appropriate exception handler is found,
exception object is passed to the handler to
process it. The handler is said to becatching
the exception.
If there are no appropriate exception handler
found
then
program
terminates
printing
information about the exception.

When an exception occurs program


processing gets terminated and doesnt
continue further. In such cases we get a system
generated error message. It is an object which is

Classisfication

The sun microsystem says there are three types of exceptions:


Checked Exception: The classes that extend Throwable class except
RuntimeException and Error are known as checked exceptions
e.g.IOException,
SQLException,
ClassNotFoundException,
IllegalAccessException,
NoSuchFieldException
EOFExceptionetc. etc. Checked exceptions are checked at
compile-time. These exceptions cannot simply be ignored at the time
of compilation, the Programmer should take care of (handle) these
exceptions. We should catch this exception and provide useful message
to user and log it properly for debugging purpose. Checked Exceptions
are exceptional scenarios that we can anticipate in a program and try
to recover from it. If these exceptions are not handled/declared in the
program, it will give compilation error.
Unchecked Exception: The classes that extend RuntimeException
are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, logic
errors or improper use of an API etc. Unchecked exceptions are
not checked at compile-time rather they are checked at runtime.
Runtime Exceptions are cause by bad programming. But its the
duty of the programmer to handle these exceptions and provide a safe
exit. These exceptions need not be included in any methods throws list
because compiler does not check to see if a method handles or throws
these exceptions.
Error: Error are irrecoverable. Errorsindicate serious problems and

Exception Hierarchy

Exception Hierarchy

Useful Exception Methods


Some of the useful methods of Throwable class are;

public String getMessage() This method returns the message String of


Throwable and the message can be provided while creating the exception
through its constructor.
public String getLocalizedMessage() This method is provided so that
subclasses can override it to provide locale specific message to the calling
program. Throwable class implementation of this method simply
usegetMessage()method to return the exception message.
public synchronized Throwable getCause() This method returns the
cause of the exception or null id the cause is unknown.
public String toString() This method returns the information about
Throwable in String format, the returned String contains the name of
Throwable class and localized message.
public void printStackTrace() This method prints the stack trace
information to the standard error stream, this method is overloaded and we
can pass PrintStream or PrintWriter as argument to write the stack trace
information to the file or stream.

Exception Handling in Java


Java Exception handling is a framework that is used to handle
runtime errors only, compile time errors are not handled by
exception handling framework.
An exception is first thrown from the top of the stack and if it is not
caught, it drops down the call stack to the previous method, If not
caught there, the exception again drops down to the previous method,
and so on until they are caught or until they reach the very bottom of
the call stack. This is called exception propagation. By default
Unchecked Exceptions are forwarded in calling chain, Checked
Exceptions are not forwarded in calling chain (propagated)
In java exceptions are handled by following mechanisms
Try-catch/try-finally/try-multiple catch
Throws
Throw
Finally
User defined exceptions

Java try-catch block


Java try block is used to enclose the code that might throw an
exception. The code which is prone to exceptions is placed in the try block,
when an exception occurs, that exception is handled by catch block
associated with it. Every try block should be immediately followed either by
a catch block or finally block.
A catch statement involves declaring the type of exception you are
trying to catch. If an exception occurs in protected code, the catch block
(or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method
parameter.
If you do not handle the exception in a try catch block, compiling
will fail. Handling all the exceptions using the try and catch block
could be cumbersome and will hinder the coders throughput.
A simple way to capture any exception is to use an object of Exception class
as other classes inherit Exception class
try{
//codethatmaythrowexception
}catch(ExceptionclassNameref){}
or
try{
//codethatmaythrowexception
}finally{}

Internal working of java try-catch


block

Example

class Division {
public static void main(String[] args) {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
try {
// try block
result = a / b;
System.out.println("Result = " + result);
}
catch (ArithmeticException e) { // catch block
System.out.println("Exception caught: Division by zero.");
}
}
}

Multiple catch Blocks


If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
At a time only one Exception is occured and at a time only one catch block is
executed.
All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
publicclassTestMultipleCatchBlock{
publicstaticvoidmain(Stringargs[]){
try{
inta[]=newint[5];
a[5]=30/0;
}
catch(ArithmeticExceptione){System.out.println("task1iscompleted");}
catch(ArrayIndexOutOfBoundsExceptione){System.out.println("task2completed");}
catch(Exceptione){System.out.println("commontaskcompleted");}

System.out.println("restofthecode...");
}
}

Nested try blocks


The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.
classExcep6{
publicstaticvoidmain(Stringargs[]){
try{
try{
System.out.println("goingtodivide");
intb=39/0;
}catch(ArithmeticExceptione){System.out.println(e);}

try{
inta[]=newint[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsExceptione){System.out.println(e);}

System.out.println("otherstatement);
}catch(Exceptione){System.out.println("handeled");}

System.out.println("normalflow..");
}

Try with resource


management
JDK 7 introduces a new version of try statement known astry-with-resources
statement. This feature add another way to exception handling with resources
management, it is also referred to asautomatic resource management.
Thetry-with-resources statementensures that each resource is closed at the
end of the statement, you do not have to explicitly close the resources.
try(resource-specification){
//usetheresource
}
catch(){...}

import java.io.*;
class Test {
public static void main(String[] args) {
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{ String str;
while((str=br.readLine())!=null) {
System.out.println(str);
}
}
catch(IOException ie) { System.out.println("exception"); } } }

finally

A finally block of code always executes whether or not exception


has occurred. Using a finally block, lets you run any cleanup type
statements that you want to execute, no matter what happens in the
protected code. Java finally block must be followed by try or catch block. It
is usedto execute important codesuch as closing connection, stream etc.
If you don't handle exception, before terminating the program, JVM
executes finally block(if any).
For each try block there can be zero or more catch blocks, but only one
finally block.
The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort)
publicclassTestFinallyBlock2{
publicstaticvoidmain(Stringargs[]){
try{
intdata=25/0;
System.out.println(data);
}
catch(ArithmeticExceptione){System.out.println(e);}
finally{System.out.println("finallyblockisalwaysexecuted");}
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero

throws

Any method capable of causing exceptions must list all the exceptions possible
during its execution, so that anyone calling that method gets a prior knowledge about
which exceptions to handle. A method can do so by using thethrowskeyword.
It gives an information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that normal
flow can be maintained.
The'throws'clause in java programming language is to specify that the method raises
particular type of exception while being executed. The'throws'clause takes arguments
as a list of the objects of type'Throwables'class.
If you are calling a method that declares an exception, you must either caught
or declare the exception. Ie In java if a code written within a method throws an
exception, there can be two cases. Either the code is being enclosed by try block and
exception handling is implemented in the same method, or the method can throws the
exception to the calling method simply. This is what throws does in exception handling,
it throws the exception to immediate calling method in the hierarchy.
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
A. In case you declare the exception, if exception does not occur, the code will be executed fine.
B. In case you declare the exception if exception occures, an exception will be thrown at runtime because throws
does not handle the exception.

Anybody calling a method with a throws clause is needed to be enclosed within


the try catch blocks
type method_name(parameter_list)throwsexception_list{//definitionofmethod}

Example 1
CASE 1 caught the exception
importjava.io.*;
classM{
voidmethod()throwsIOException{
thrownewIOException("deviceerror");
}
}
publicclassTestthrows2{
publicstaticvoidmain(Stringargs[]){
try{
Mm=newM();
m.method();
}catch(Exceptione)
{System.out.println("exceptionhandled");}

System.out.println("normalflow...");
}
}
Output:exception handled
normal flow..

CASE 2 :A
If exception doesnt occur
importjava.io.*;
classM{
voidmethod()throwsIOException{
System.out.println("deviceoperationperf
ormed");
}
}
classTestthrows3{
publicstaticvoidmain(Stringargs[])th
rowsIOException{//declareexception
Mm=newM();
m.method();

System.out.println("normalflow...");
}
}
Output:device operation performed
normal flow...

EXAMPLE 2
CASE 2:B Program if exception occurs
importjava.io.*;
classM{
voidmethod()throwsIOException{
thrownewIOException("deviceerror");
}
}
classTestthrows4{
publicstaticvoidmain(Stringargs[])throwsIOException{//declareexception
Mm=newM();
m.method();

System.out.println("normalflow...");
}
}
Output:Runtime Exception

throw
The Java throw keyword is used to explicitly throw an exception. Only object of
Throwable class or its sub classes can be thrown. Program execution stops on
encounteringthrowstatement, and the closest catch statement is checked
for matching type of exception.
We can throw either checked or uncheked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception(user defined).
Throw keyword should be defined in either try catch block or the method should
be defined using throws keyword.(if its not explicit)
Thethrowkeyword is used to throw an exception from within a method. When
athrowstatement is encountered and executed, execution of the current method is
stopped and returned to the caller.
Whereas thethrowskeyword is used to declare that a method may throw one or
some exceptions. The caller has to catch the exceptions (catching is optional if the
exceptions are of type unchecked exceptions).
When using thethrowkeyword to throw a checked exception from within a
method, the method must either:
Declares thethrowsclause followed by the exceptions thrown by thethrowstatements,
or:
Catches the exceptions thrown by thethrowstatements.ie method should be inside a trycatch block
If thethrowstatements throw unchecked exceptions, the method is not required to declare
those unchecked exceptions in itsthrowsclause.

Syntax:Throw ThrowableInstance

Syntax and Example


void aMethod()throws
Exception1, Exception2 {
// statements...
if (an exception occurs) {
throw new Exception1();
}
// statements...
if (another exception
occurs) {
throw new Exception2();
}
}

publicclassTestThrow1{
staticvoidvalidate(intage){
if(age<18)
thrownewArithmeticException
("notvalid");
else
System.out.println("welcometo
vote");
}
publicstaticvoidmain(Stringar
gs[]){
validate(13);
System.out.println("restofthec
ode...");
}
}

Example
Method call of a method using throw should be
in try block as it is throwing an exception.
to throw your own exception explicitly
using throw keyword
package beginnersbook.com;
class MyOwnException extends Exception {
public MyOwnException(String msg)
{ super(msg);
}
}
class EmployeeTest {
static void employeeAge(int age) throws
MyOwnException{
if(age < 0) throw new MyOwnException("Age
can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) { e.printStackTrace();
}
}
}

to throw an already defined


exception using throw keyword
package beginnersbook.com;
class Exception2{
static int sum(int num1, int num2){
if (num1 == 0) throw new
ArithmeticException("First parameter is
not valid");
else
System.out.println("Both parameters are
correct!!");
return num1+num2;
}
public static void main(String args[]){
int res=sum(0,12);
System.out.println(res);
System.out.println("Continue Next
statements");
}
}

Difference between throws and


throw

No:

throw

throws

1)

Java throw keyword is used Java throws keyword is used to


to explicitly throw an
declare an exception.
exception.

2)

Checked exception cannot


be propagated using throw
only.

Checked exception can be


propagated with throws.

3)

Throw is followed by an
instance.

Throws is followed by class.

4)

Throw is used within the


method.

Throws is used with the method


signature.

5)

You cannot throw multiple


exceptions.

You can declare multiple exceptions


e.g.
public void method()throws

User-defined exceptions/Custom Exceptions


You can also create your own exception sub class simply
by extending javaExceptionclass. You can define a
constructor for your Exception sub class (not compulsory)
and you can override thetoString()function to display
your customized message on catch.
classInvalidAgeExceptionextendsException{
InvalidAgeException(Strings){
super(s);
}
}
classTestCustomException1{

staticvoidvalidate(intage)throwsInvalidAgeException{
if(age<18)
thrownewInvalidAgeException("notvalid");
else
System.out.println("welcometovote");
}

publicstaticvoidmain(Stringargs[]){
try{
validate(13);
}catch(Exceptionm){System.out.println("Exceptionoccured:"+m);}

System.out.println("restofthecode...");

Example
package java4s;

public class Client {


public static void main(String[]
args)throws Exception
{
int price = -120;

if(price < 0)
throw new
MyOwnExceptionClass(price);
else
System.out.println("Your age
is :"+price);
}
}

package java4s;

public class MyOwnExceptionClass


extends Exception {

private int price;

public MyOwnExceptionClass(int price)


{
this.price = price;
}

public String toString(){


return "Price should not be in
negative, you are entered" +price;
}

Example
class MyException extends Exception{
String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
}
class CustomException{
public static void main(String args[]){
try{
throw new MyException("Custom"); // I'm throwing user defined custom exception above
}
catch(MyException exp){
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}}}
Output:
Hi this is my catch block Output String = Custom

ExceptionHandling with MethodOverriding in Java

There are many rules if we talk about methodoverriding


with exception handling. The Rules are as follows:
If the superclass method does not declare an
exception
If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked
exception but it can declare unchecked exception.

If the superclass method declares an exception


If the superclass method declares an exception, subclass
overridden method can declare same, subclass exception or
no exception but cannot declare parent exception.

Advantage of Exceptions
Separating Error-Handling Code from
"Regular" Code:Exceptions provide the means to
separate the details of what to do when something
out of the ordinary happens from the main logic of a
program.
Propagating Errors Up the Call Stack: A second
advantage of exceptions is the ability to propagate
error reporting up the call stack of methods.
Grouping and Differentiating Error Types:
Because all exceptions thrown within a program are
objects, the grouping or categorizing of exceptions
is a natural outcome of the class hierarchy.

Exception handling best


practices
Use Specific Exceptions Base classes of Exception hierarchy doesnt provide any useful
information,always throw and catch specific exception classes so that caller will know the root cause
of exception easily and process them. This makes debugging easy and helps client application to
handle exceptions appropriately.
Throw Early or Fail-Fast We should try to throw exceptions as early as possible.
Catch Late Since java enforces to either handle the checked exception or to declare it in method
signature, sometimes developers tend to catch the exception and log the error.
Closing Resources Since exceptions halt the processing of program, we should close all the
resources in finally block or use Java 7 try-with-resources enhancement to let java runtime close it for
you.
Logging Exceptions We should always log exception messages and while throwing exception
provide clear message so that caller will know easily why the exception occurred.
Single catch block for multiple exceptions Most of the times we log exception details and provide
message to the user, in this case we should use java 7 feature for handling multiple exceptions in a
single catch block. This approach will reduce our code size and it will look cleaner too.
Using Custom Exceptions Its always better to define exception handling strategy at the design
time and rather than throwing and catching multiple exceptions, we can create a custom exception with
error code and caller program can handle these error codes.
Use Exceptions Judiciously Exceptions are costly and sometimes its not required to throw
exception at all and we can return a boolean variable to the caller program to indicate whether an
operation was successful or not. This is helpful where the operation is optional and you dont want your
program to get stuck because it fails. For example, while updating the stock quotes in database from a
third party webservice, we may want to avoid throwing exception if the connection fails.

Applet
An applet is a Java program that runs in a Web browser and works at
client side. Applet is a special type of program that is embedded in the
webpage to generate the dynamic content.
Java Plug-in software is responsible to manage the life cycle of an applet.
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not
define main().
When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of
the Web browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be
followed.
Other classes that the applet needs can be downloaded in a single Java
Archive (JAR) file.

Applet
Every applet is an extension of thejava.applet.Applet class. The base applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context. These include methods that do the following:
Get applet parameters
Get the network location of the HTML file that contains the applet
Get the network location of the applet class directory
Print a status message in the browser
Fetch an image
Fetch an audio clip
Play an audio clip
Resize the applet

Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may:
request information about the author, version and copyright of the applet
request a description of the parameters the applet recognizes
initialize the applet
destroy the applet
start the applet's execution
stop the applet's execution

The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.

Abstract Windows Toolkit Class Hierarchy

Hierarchy of Applet Class

These import statements bring the classes into the scope of our applet class:
java.applet.Applet., java.awt.Graphics. The java.applet package contains a class Applet
which uses various interfaces such as AppletContext, AppletStub and AudioCIip. The
applet class is an extension of Panel class belonging to java.awt package.
The Abstract Windowing Toolkit (AWT): Java AWT(Abstract Windowing Toolkit)
isan API to develop GUI or window-based application in java. Java AWT
components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components uses the resources
of system.
Component: Acomponentis an object with a graphical representation that can
interact with the user. Component is an abstract class. Eg: buttons, checkboxes, list,
textfield and scrollbars.
Containers: A Container is a Component used to hold and organize components
together for display purposes. Components added to a Container are added to the end
of the list unless an index position is specified. There is no limit to the number of
components a Container may hold. Container is an abstract class, but they also contain
code for event handling and many 'niceties' such as controlling the cursor image and
the application's icon. Eg: Frame, Window, Dialog, Panel
Window: The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.
Panel: The Panel is the container that doesn't contain title bar and menu bars. It can
have other components like button, textfield etc.
Frame: A frame is a top-level window with a title and a border. The Frame is the
container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.A frame may also have scroll bars, a menu bar, etc.

Lifecycle of Java Applet


1. Applet is initialized. public void init():is used to initialized the
Applet. It is invoked only once.
2. Applet is started. public void start():is invoked after the init()
method or browser is maximized. It is used to start the Applet.
3. Applet is painted. public void paint(Graphics g):is used to
paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.
4. Applet is stopped. public void stop():is used to stop the Applet.
It is invoked when Applet is stop or browser is minimized.
5. Applet is destroyed. public void destroy():is used to destroy
the Applet. It is invoked only once.
The java.applet.Applet class provide 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods(paint
method) for an applet.

Advantages and disadvantages of


Applets

Advantages of applets
It works at client side so less response
time.
Secured
It can be executed by browsers running
under many platforms, including Linux,
Windows, Mac Os etc.

Disadvantages of Applet
Plugin is required at client browser to
execute applet.

Running an applet
There are two ways to run an applet
By html file.
To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now open the html
file using any java enabled web browser. class must be public because its
object is created by Java Plugin software that resides on the browser.
<html>
<body>
<appletcode="Filename.class"width="300"height="300">
</applet>
</body>
</html>

By appletViewer tool (for testing purpose).


To execute the applet by appletviewer tool, create an applet that contains
applet tag in comment and compile it. After that run it by: appletviewer
Filename.java. If Html tag is used run it by: appletviewer
Filename.html.
/*
<appletcode="Filename.class"width="300"height="300">
</applet>
*/

Running an applet
Non-Java-enabled browsers do not process <applet> and </applet>.
Therefore, anything that appears between the tags, not related to the
applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location
of the document. To specify otherwise, use the codebase attribute of
the <applet> tag as shown:
<applet codebase="http://amrood.com/applets"
code="HelloWorldApplet.class" width="320" height="120">
If an applet resides in a package other than the default, the holding
package must be specified in the code attribute using the period
character (.) to separate package/class components. For example:
<applet code="mypackage.subpackage.TestApplet.class"
width="320" height="120">
If an applet takes parameters, values may be passed for the
parameters by adding <param> tags between <applet> and
</applet>.

Commonly used methods of Graphics class:


public abstract void drawString(String str, int x, int y):is used to draw the specified
string.
public void drawRect(int x, int y, int width, int height):draws a rectangle with the
specified width and height.
public abstract void fillRect(int x, int y, int width, int height):is used to fill rectangle
with the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height):is used to draw oval
with the specified width and height.
public abstract void fillOval(int x, int y, int width, int height):is used to fill oval with the
default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2):is used to draw line between
the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer):is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle):is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle):is used to fill a circular or elliptical arc.
public abstract void setColor(Color c):is used to set the graphics current color to the
specified color.
g.setColor (Color.blue);
Color lightOrange = new Color(230, 220, 0);
setBackground(lightOrange);
public abstract void setFont(Font font):is used to set the graphics current font to the
specified font.
Font f = new Font("Helvetica", Font.BOLD,20);
g.setFont(f);

To display an image
The java.awt.Graphics class provide a method drawImage() to
display the image.
public abstract boolean drawImage(Image img, int x, int
y, ImageObserver observer):is used draw the specified
image.
The java.applet.Applet class provides getImage() method that
returns the object of Image. Syntax:
publicImagegetImage(URLu,Stringimage){}
java.applet.AppletContext class provides the facility of
communication between applets. We provide the name of
applet through the HTML file. It provides getApplet() method
that returns the object of Applet.
Syntax:publicAppletgetApplet(Stringname){}

Screen Coordinates are used for


Positioning Graphics
A point on the screen is a picture element (pixel).The
pixel is positioned at the intersection of its horizontal and
vertical coordinates.
The horizontal coordinate (horiz) starts as zero at the
left.Increasing the value of horiz moves the pixel further to the
right.
The vertical coordinate (vert) starts as zero at the top.Each
increase in the value of vert moves the pixel further to the
bottom.

The width and height of a graphic object is measured in


pixels.
Width (w). As w increases, the object is wider.
Height (h).As h increases, the object is taller.

Example

importjava.applet.Applet;
importjava.awt.Graphics;
import java.awt.Color;
publicclassBasicAppletExampleextend
sApplet{

publicvoidpaint(Graphicsg){
Color c[] =
{Color.blue,Color.cyan,Color.darkGray,Co
lor.gray,Color.green};
for(int i = 0; i<c.length; i++){
g.setColor(c[i]);
g.drawString("This is my First
Applet",10, 10 + (i*10));}
}
}

/*
<applet code =
"BasicAppletExample" width = 200
height = 200>
</applet>
*/

importjava.applet.Applet;
importjava.awt.Graphics;
import java.awt.Color;
publicclassBasicAppletExampleextends
Applet{

publicvoidpaint(Graphicsg){
//write text using drawString
method of Graphics class
g.drawString("This is my First
Applet", 10, 10 + (i*10));}
}
}

/*
<HTML>
<HEAD> </HEAD>
<BODY>
<applet code = "BasicAppletExample"
width = 200 height = 200>
</applet>
</BODY>
</HTML> */
To Compile: : javac

Swing
Swing, which is an extension library to the AWT, includes new
and improved components that enhance the look and
functionality of GUIs.
It is a part of Java Foundation Classes (JFC) that isused to
create window-based applications.
Swing can be used to build Standalone swing gui Apps as well
as Servlets and Applets.
It employs a model-view-control architecture.
Swing is more portable and more flexible than AWT. Java Swing
provides platform-independent and lightweight components.
In Swing, classes that represent GUI components have names
beginning with the letter J. Some examples are JButton, JLabel,
and JSlider. Altogether there are more than 250 new classes
and 75 interfaces in Swing twice as many as in AWT.

Swing Features

Pluggable Look & Feel


Rich controls
Highly Customizable
Lightweight components
Uses MVC Architecture
100% Java implementation of components
Three parts
Component set (subclasses of JComponent)
Support classes
Interfaces

Swing Model-view-Control
Architecture
Model represents the data, View as a visual representation of
the data and Controller takes input and translates it to changes
in data .
A Model represents component's data. The model part of the
MV design is implemented by a model object and a change
listener object.
View represents visual representation of the component's data.
The view part of the MV design is implemented with a
component object and the UI object.
Controller takes the input from the user on the view and
reflects the changes in Component's data.
Swing component have Model as a seperate element and View
and Controller part are clubbed in User Interface elements.
Using this way, Swing has pluggable look-and-feel architecture.

Java Swing class hierarchy

The classJComponent, descended directly from Container, is the


root class for most of Swings user interface components.

UI Components of SWING Class

JPanelis Swings version of the AWT class Panel and uses the same default
layout, FlowLayout. JPanel is descended directly from JComponent. Panels
are useful for grouping components and placing them to appropriate
locations in a frame.
JFrameis Swings version of Frame and is descended directly from that
class. Frame is a window that can have title, border, menu, buttons, text
fields and several other components. A Swing application must have a
frame to have the components added to it.The components added to the
frame are referred to as its contents; these are managed by the
contentPane. To add a component to a JFrame, we must use its
contentPane instead.
JLabel, descended from JComponent, is used to create text labels. A label
is unselectable text and images. If you want to display a string or an image
on a frame, you can do so by using labels.
JTextFieldallows editing of a single line of text. Used for capturing user
inputs, these are the text boxes where user enters the data.New features
include the ability to justify the text left, right, or center, and to set the
texts font.
JPasswordField(a direct subclass of JTextField) you can suppress the
display of input. Similar to text fields but the entered data gets hidden and
displayed as dots on GUI. Each character entered can be replaced by an
echo
character.

UI Components of SWING Class


JTextAreaallows editing of multiple lines of text. JTextArea can be used in conjunction with
class JScrollPane to achieve scrolling. The underlyingJScrollPanecan be forced to always or
never
have
either
the
vertical
or
horizontal
scrollbar;
JButton is a component the user clicks to trigger a specific action.
JRadioButtonis similar to JCheckbox, except for the default icon for each class. A set of
radio
buttons
can
be
associated
as
a
group
in
which
only
one button at a time can be selected.
JCheckBoxis not a member of a checkbox group. A checkbox can be selected and
deselected, and it also displays its current state.
JComboBoxis like a drop down box. You can click a drop-down arrow and select an option
from
a
list.
For
example,
when
the
component
has
focus,
pressing a key that corresponds to the first character in some entrys name selects that
entry. A vertical scrollbar is used for longer lists.
JList;provides a scrollable set of items from which one or more may be selected. JList can
be
populated
from
an
Array
or
Vector.
JList
does
not
support scrolling directly, instead, the list must be associated with a scrollpane. The view
port
used
by
the
scroll
pane
can
also
have
a
user-defined
border. JList actions are handled using ListSelectionListener.
JInternalFrameis confined to a visible area of a container it is placed in. It can be
iconified , maximized and layered.
JWindowis Swings version of Window and is descended directly from that class. Like
Window, it uses BorderLayout by default.
JDialogis Swings version of Dialog and is descended directly from that class. Like Dialog, it
uses
BorderLayout
by
default.
Like
JFrame
and
JWindow,
JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and
glass
panes.
All
dialogs
are
modal,
which
means
the
current
thread is blocked until user interaction with it has been completed. JDialog class is intended

UI Components of SWING Class


JToolbarcontains a number of components whose type is usually some kind of
button which can also include separators to group related components
within the toolbar.
FlowLayoutwhen used arranges swing components from left to right until
theres no more space available. Then it begins a new row below it and moves
from left to right again. Each component in a FlowLayout gets as much space as
it needs and no more.
JTabbedPanecontains a tab that can have a tool tip and a mnemonic, and it can
display both text and an image.
BorderLayoutplaces swing components in the North, South, East, West and
center of a container. You can add horizontal and vertical gaps between
the areas.
GridLayoutis a layout manager that lays out a containers components in a
rectangular grid. The container is divided into equal-sized rectangles,
and one component is placed in each rectangle.
GridBagLayoutis a layout manager that lays out a containers components in a
grid of cells with each component occupying one or more cells,
called its display area. The display area aligns components vertically and
horizontally, without requiring that the components be of the same size.
JMenubarcan contain several JMenus. Each of the JMenus can contain a series
of JMenuItem s that you can select. Swing provides support for
pull-down and popup menus.
Scrollable JPopupMenuis a scrollable popup menu that can be used whenever

Commonly used Methods of


Component class
SI
N
O

Method

public void add(Component c) add a component on another


component.

public void setSize(int


width,int height)

sets size of the component.

public void
setLayout(LayoutManager m)

sets the layout manager for the


component.

public void setVisible(boolean


b)

sets the visibility of the


component. It is by default false.

Description

There are two ways to create a frame:


By creating the object of Frame class (association)
By extending Frame class (inheritance)

Example
import javax.swing.JButton; I
mport javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class SwingFirstExample {
public static void main(String[] args)
{
JFrame frame = new JFrame("My First
Swing Example");
frame.setSize(350,200);
frame.setDefaultCloseOperation(JFram
e.EXIT_ON_CLOSE);
JPanel panel = new JPanel();

frame.add(panel);
placeComponents(panel);
frame.setVisible(true); }

private static void placeComponents(JPanel


panel) {
panel.setLayout(null);

JLabel userLabel = new JLabel("User");
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);
JTextField userText = new JTextField(20);

userText.setBounds(100,20,165,25);
panel.add(userText);
JLabel passwordLabel = new
JLabel("Password");

passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);

JPasswordField passwordText = new
JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
JButton loginButton = new
JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton); } }

Event Handling
Change in the state of an object is known as event i.e. event describes the
change in state of source. Events are generated as result of user interaction with
the graphical user interface components. For example, clicking on a button.
Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
Java Uses the Delegation Event Model to handle the events.
The Delegation Event Model has the following key participants namely:
Source- The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes for
source object.
TheEvent object(Event) encapsulates the state changes in the event source.
Listener- It is also known as event handler. Listener is responsible for generating
response to an event. From java implementation point of view the listener is also an
object. Listener waits until it receives an event. Once the event is received , the listener
process the event an then returns.

The benefit of this approach is that the user interface logic is completely
separated from the logic that generates the event.
In this model ,Listener needs to be registered with the source object so that the
listener can receive the event notification. This is an efficient way of handling
the event because the event notifications are sent only to those listener that
want to receive them.

Event Handling

Some subclasses of Event are ActionEvents and WindowEvents.


Buttons detects only one type of event - called ActionEvents. In
contrast, there are seven kinds of WindowEvents.
To understand events, you need to consider two types of interfaces, and
their relationship:
Event Detectors: The former is set up to detect the occurence of certain
types of event, and it sends notices to the listeners. Examples of Event
Detectors are windows or buttons.
Event Listeners. It is the listeners that take the appropriate action.

For buttons, the ctionListener" is appropriate. But in order for the


event objects to know which listener object to send the events to, we
need to do three things:
Implement the listener interface using ANY reasonable class. In our example,
the class will be an extension of JPanel. To implement the ActionListener, you
need to supply the methodactionPerformed(ActionEvent)(the only method
of this interface).
Create a listener object:
Listener lis = new MyPanel();
register this object with the event detector.
button.addActionListener(lis); // button is the event detector; The general form
for registering listener objects is:
<eventDetector>.add<EventType>Listener(<listenerObject>);

Event Classes
SiN Control & Description
o
1

AWTEventIt is the root event class for all SWING events. This class and
its subclasses supercede the original java.awt.Event class.

ActionEventThe ActionEvent is generated when button is clicked or


the item of a list is double clicked.

InputEventThe InputEvent class is root event class for all componentlevel input events.

KeyEventOn entering the character the Key event is generated.

MouseEventThis event indicates a mouse action occurred in a


component.

WindowEventThe object of this class represents the change in state of


a window.

AdjustmentEventThe object of this class represents the adjustment


event emitted by Adjustable objects.

ComponentEventThe object of this class represents the change in


state of a window.

Event Listener Interfaces


The Event listener represent the interfaces responsible to handle
events. In order to design a listener class we have to develop
some listener interfaces. These Listener interfaces forecast
some public abstract callback methods which must be
implemented by the listener class.
Every method of an event listener method has a single
argument as an object which is subclass of EventObject class.
For example, mouse event listener methods will accept instance
of MouseEvent, where MouseEvent derives from EventObject.
Event Listener Inerface is a marker interface which every
listener interface has to extend. This class is defined in java.util
package. If you do not implement the any if the predefined
interfaces then your class can not act as a listener class for a
source object.

SWING Event Listener Interfaces


Si
No

Control & Description

ActionListenerThis interface is used for receiving the action


events.

ComponentListenerThis interface is used for receiving the


component events.

ItemListenerThis interface is used for receiving the item


events.

KeyListenerThis interface is used for receiving the key events.

MouseListenerThis interface is used for receiving the mouse


events.

WindowListenerThis interface is used for receiving the window


events.

AdjustmentListenerThis interface is used for receiving the


adjusmtent events.

ContainerListenerThis interface is used for receiving the

Adapter Classes
Adapters are abstract classes for receiving various events. The
methods in these classes are empty. These classes exists as
convenience for creating listener objects.
Following is the list of commonly used adapters while listening GUI
events in SWING.
Sr. Adapter & Description
No.
1

FocusAdapterAn abstract adapter class for receiving focus


events.

KeyAdapterAn abstract adapter class for receiving key events.

MouseAdapterAn abstract adapter class for receiving mouse


events.

MouseMotionAdapterAn abstract adapter class for receiving


mouse motion events.

WindowAdapterAn abstract adapter class for receiving window


events.

package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;

Example

public SwingControlDemo(){
prepareGUI(); }
public static void main(String[] args){
SwingControlDemo swingControlDemo = new
SwingControlDemo();
swingControlDemo.showEventDemo(); }
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0); } });
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true); }

private void showEventDemo(){


headerLabel.setText("Control in action: Button");
JButton okButton = new JButton("OK");
JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new
ButtonClickListener());
cancelButton.addActionListener(new
ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true); }
private class ButtonClickListener implements
ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "OK" ))
{ statusLabel.setText("Ok Button clicked."); }
else if( command.equals( "Submit" ) )
{ statusLabel.setText("Submit Button clicked."); }

NetBeans IDE
the NetBeans IDE is a free, opensource, cross-platform integrated
development environment with builtin support for the Java programming
language. It offers many advantages
over coding with a text editor

JAVA JDBC Connectivity


Java JDBC is a java API to connect and execute query with the database.
JDBC API uses jdbc drivers to connect with the database.
Before JDBC, ODBC API was the database API to connect and execute
query with the database. But, ODBC API uses ODBC driver which is
written in C language (i.e. platform dependent and unsecured). That is
why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).

JDBC Driver is a software component that enables java application to


interact with the database.

JAVA JDBC Connectivity


There are 4 types of JDBC drivers:
1.
2.
3.
4.

JDBC-ODBC bridge driver


Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)

There are 6 steps to connect any java application with the database in java using JDBC.
They are as follows:
1. Import the packages:Requires that you include the packages containing the JDBC classes needed
for database programming.These 3 import statements should be present.
.import java.sql.Connection;
.import java.sql.DriverManager;
.import java.sql.SQLException;
2. Register the driver class: The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class. Eg: Class.forName("com.mysql.jdbc.Driver");
3. Creating connection: To connect to a database you need a Connection object. The Connection object
uses aDriverManager. The DriverManager passes in your database username, your password, and
the location of the database. The getConnection() method of DriverManager class is used to establish
connection with the database. Eg: Connectioncon=DriverManager.
("jdbc:mysql://localhost:3306/dbname",usrnm",pwd")

JAVA JDBC Connectivity


3.

Creating statement: The createStatement() method of Connection interface is


used to create statement. The object of statement is responsible to execute
queries with the database. The JDBCStatement,
CallableStatement,andPreparedStatementinterfaces define the methods and
properties that enable you to send SQL or PL/SQL commands and receive data
from your database.They also define methods that help bridge data type
differences between Java and SQL data types used in a database.
Eg: Statementstmt=con.createStatement();
4. Executing queries: The executeQuery() method of Statement interface is used
to execute queries to the database. This method returns the object of ResultSet
that can be used to get all the records of a table.Eg:
ResultSetrs=stmt.executeQuery("select*fromemp");

while(rs.next()){
System.out.println(rs.getInt(1)+""+rs.getString(2));
}
5. Closing connection: By closing connection object statement and ResultSet will
be closed automatically. The close() method of Connection interface is used to
close the connection. Eg: con.close();

JAVA JDBC Connectivity


for the mysql database:
Driver class:The driver class for the mysql database iscom.mysql.jdbc.Driver.
Connection URL:The connection URL for the mysql database
isjdbc:mysql://localhost:3306/sonoowhere jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and sonoo is the database name. We may use any database, in such
case, you need to replace the sonoo with your database name.
Username:The default username for the mysql database isroot.
Password:Password is given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
for the oracle database:
Driver class:The driver class for the oracle database
isoracle.jdbc.driver.OracleDriver.
Connection URL:The connection URL for the oracle10G database
isjdbc:oracle:thin:@localhost:1521:xewhere jdbc is the API, oracle is the database, thin
is the driver, localhost is the server name on which oracle is running, we may also use IP
address, 1521 is the port number and XE is the Oracle service name. You may get all these
informations from the tnsnames.ora file.
Username:The default username for the oracle database issystem.
Password:Password is given by the user at the time of installing the oracle database.

JAVA JDBC Connectivity


The DriverManager class acts as an interface between user and
drivers. It keeps track of the drivers that are available and handles
establishing a connection between a database and the appropriate
driver. The DriverManager class maintains a list of Driver classes that
have registered themselves by calling the method
DriverManager.registerDriver().
Commonly used methods of DriverManager class:
1) public static void registerDriver(Driver driver):is used to register
the given driver with DriverManager.2) public static void
deregisterDriver(Driver driver):is used to deregister the given driver
(drop the driver from the list) with DriverManager.3) public static
Connection getConnection(String url):is used to establish the
connection with the specified url.4) public static Connection
getConnection(String url,String userName,String password):is used to
establish the connection with the specified url, username and
password.

JAVA JDBC Connectivity


A Connection is the session between java application and database. The
Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection can be used to get the
object of Statement and DatabaseMetaData. The Connection interface
provide many methods for transaction management like
commit(),rollback() etc.
Statement interface:TheStatement interfaceprovides methods to
execute queries with the database. The statement interface is a factory
of ResultSet i.e. it provides factory method to get the object of ResultSet.
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql):is used to execute SELECT
query. It returns the object of ResultSet
2) public int executeUpdate(String sql):is used to execute specified query, it
may be create, drop, insert, update, delete etc
3) public boolean execute(String sql):is used to execute queries that may
return multiple results.
4) public int[] executeBatch():is used to execute batch of commands.

PreparedStatement interface
The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
Let's see the example of parameterized query:
Stringsql="insertintoempvalues(?,?,?)";
As you can see, we are passing parameter (?) for the
values. Its value will be set by calling the setter
methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the
application will be faster if you use PreparedStatement
interface because query is compiled only once.

Methods of PreparedStatement
interface
Method

Description

public void setInt(int paramIndex, sets the integer value to the given
int value)
parameter index.
public void setString(int
paramIndex, String value)

sets the String value to the given


parameter index.

public void setFloat(int


paramIndex, float value)

sets the float value to the given


parameter index.

public void setDouble(int


paramIndex, double value)

sets the double value to the given


parameter index.

public int executeUpdate()

executes the query. It is used for


create, drop, insert, update,
delete etc.

public ResultSet executeQuery()

executes the select query. It


returns an instance of ResultSet.

Example

importjava.sql.*;
classMysqlCon{
publicstaticvoidmain(Stringargs[]){
try{
Class.forName("com.mysql.jdbc.Driver");

Connectioncon=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");

//heresonooisdatabasename,rootisusernameandpassword

Statementstmt=con.createStatement();

ResultSetrs=stmt.executeQuery("select*fromemp");

while(rs.next())
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));

con.close();

}catch(Exceptione){System.out.println(e);}

S-ar putea să vă placă și