Documente Academic
Documente Profesional
Documente Cultură
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.
Classisfication
Exception Hierarchy
Exception Hierarchy
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.");
}
}
}
System.out.println("restofthecode...");
}
}
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..");
}
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
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.
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
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();
}
}
}
No:
throw
throws
1)
2)
3)
Throw is followed by an
instance.
4)
5)
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;
if(price < 0)
throw new
MyOwnExceptionClass(price);
else
System.out.println("Your age
is :"+price);
}
}
package java4s;
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
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.
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.
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.
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>
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>.
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){}
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
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.
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.
Method
public void
setLayout(LayoutManager m)
Description
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); }
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
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.
InputEventThe InputEvent class is root event class for all componentlevel input events.
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
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); }
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
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")
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();
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)
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);}