0% found this document useful (0 votes)
49 views

2 PDF

The document discusses Java packages, interfaces, and how to work with them. It explains what packages and interfaces are, how to define and use them, how to organize classes into packages and subpackages, and how to access packages and classes from other packages. It also covers how to compile and run package programs and load class files.

Uploaded by

jeeturathia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

2 PDF

The document discusses Java packages, interfaces, and how to work with them. It explains what packages and interfaces are, how to define and use them, how to organize classes into packages and subpackages, and how to access packages and classes from other packages. It also covers how to compile and run package programs and load class files.

Uploaded by

jeeturathia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

1 |M.

sc sem I OOPs USING JAVA

UNIT-II Paekage, Applet, Swing and JDBC

(1) Packages
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.
2 |M.sc sem I OOPs USING JAVA

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within
the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents
the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.
3 |M.sc sem I OOPs USING JAVA

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to the current
package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
4 |M.sc sem I OOPs USING JAVA

5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now there is no
need to import. But you need to use fully qualified name every time when you are accessing the class or
interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages contain
Date class.

Example of package by import fully qualified name


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding the classes
and interfaces of the subpackages. Hence, you need to import the subpackage as well.
5 |M.sc sem I OOPs USING JAVA

Note: Sequence of the program must be package then import then class.

Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package
further.

Let's take an example, Sun Microsystem has definded a package named java that contains many classes
like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and
Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and
so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean or


org.sssit.dao.

Example of Subpackage

1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For example:
6 |M.sc sem I OOPs USING JAVA

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

To Compile:

e:\sources> javac -d c:\classes Simple.java

To Run:

To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java that tells where to look
for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple


7 |M.sc sem I OOPs USING JAVA
Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the public class
name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one public class, but keep
the package name same. For example:

1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}

(2) interfaces
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
8 |M.sc sem I OOPs USING JAVA

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all the methods
in an interface are declared with the empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods declared in the interface.

Syntax:

1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Java 8 Interface Improvement


Since Java 8, interface can have default and static methods which is discussed later.
9 |M.sc sem I OOPs USING JAVA

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds
public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another interface,
but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided in the A6
class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
10 |M.sc sem I OOPs USING JAVA

6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Test it Now

Output:

Hello

Java Interface Example: Drawable


In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle
and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is
provided by different implementation providers. Moreover, it is used by someone else. The implementation
part is hidden by the user who uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
16. d.draw();
17. }}

(3) ENCAPSULATION
11 |M.sc sem I OOPs USING JAVA

Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the class private. Now
we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java


By providing only a setter or getter method, you can make the class read-only or write-only. In other
words, you can skip the getter or setter methods.

It provides you the control over the data. Suppose you want to set the value of id which should be greater
than 100 only, you can write the logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the data through
the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to
create an encapsulated class in Java.

Simple Example of Encapsulation in Java


Let's see the simple example of encapsulation that has only one field with its setter and getter methods.

File: Student.java

1. //A Java class which is a fully encapsulated class.


2. //It has a private data member and getter and setter methods.
3. package com.javatpoint;
4. public class Student{
5. //private data member
6. private String name;
7. //getter method for name
8. public String getName(){
9. return name;
10. }
11. //setter method for name
12. public void setName(String name){
13. this.name=name
12 |M.sc sem I OOPs USING JAVA

14. }
15. }

File: Test.java

1. //A Java class to test the encapsulated class.


2. package com.javatpoint;
3. class Test{
4. public static void main(String[] args){
5. //creating instance of the encapsulated class
6. Student s=new Student();
7. //setting value in the name member
8. s.setName("vijay");
9. //getting value of the name member
10. System.out.println(s.getName());
11. }
12. }
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test

Output:

vijay

Read-Only class

1. //A Java class which has only getter methods.


2. public class Student{
3. //private data member
4. private String college="AKG";
5. //getter method for college
6. public String getCollege(){
7. return college;
8. }
9. }

Now, you can't change the value of the college data member which is "AKG".

1. s.setCollege("KITE");//will render compile time error

Write-Only class

1. //A Java class which has only setter methods.


2. public class Student{
13 |M.sc sem I OOPs USING JAVA

3. //private data member


4. private String college;
5. //getter method for college
6. public void setCollege(String college){
7. this.college=college;
8. }
9. }

Now, you can't get the value of the college, you can only change the value of college data member.

1. System.out.println(s.getCollege());//Compile Time Error, because there is no such method


2. System.out.println(s.college);//Compile Time Error, because the college data member is private.
3. //So, it can't be accessed from outside the class

Another Example of Encapsulation in Java


Let's see another example of encapsulation that has only four fields with its setter and getter methods.

File: Account.java

1. //A Account class which is a fully encapsulated class.


2. //It has a private data member and getter and setter methods.
3. class Account {
4. //private data members
5. private long acc_no;
6. private String name,email;
7. private float amount;
8. //public getter and setter methods
9. public long getAcc_no() {
10. return acc_no;
11. }
12. public void setAcc_no(long acc_no) {
13. this.acc_no = acc_no;
14. }
15. public String getName() {
16. return name;
17. }
18. public void setName(String name) {
19. this.name = name;
20. }
21. public String getEmail() {
22. return email;
14 |M.sc sem I OOPs USING JAVA

23. }
24. public void setEmail(String email) {
25. this.email = email;
26. }
27. public float getAmount() {
28. return amount;
29. }
30. public void setAmount(float amount) {
31. this.amount = amount;
32. }
33.
34. }

File: TestAccount.java

1. //A Java class to test the encapsulated class Account.


2. public class TestEncapsulation {
3. public static void main(String[] args) {
4. //creating instance of Account class
5. Account acc=new Account();
6. //setting values through setter methods
7. acc.setAcc_no(7560504000L);
8. acc.setName("Sonoo Jaiswal");
9. acc.setEmail("[email protected]");
10. acc.setAmount(500000f);
11. //getting values through getter methods
12. System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.getAmount());
13. }
14. }

(4) Abstract classes


Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract
and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java
15 |M.sc sem I OOPs USING JAVA

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method


16 |M.sc sem I OOPs USING JAVA

In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Test it Now
running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle
classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of
the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the factory method
later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
17 |M.sc sem I OOPs USING JAVA

12. class TestAbstraction1{


13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
15. s.draw();
16. }
17. }
Test it Now
drawing circle

Another example of Abstract class in java


File: TestBank.java

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
14. b=new SBI();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
16. b=new PNB();
17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
18. }}
Test it Now
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract class having constructor, data member and methods


An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.

File: TestAbstraction2.java
18 |M.sc sem I OOPs USING JAVA

1. //Example of an abstract class that has abstract and non-abstract methods


2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7. //Creating a Child class which inherits Abstract class
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. //Creating a Test class which calls abstract and non-abstract methods
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. }
18. }
Test it Now
bike is created
running safely..
gear changed

Rule: If there is an abstract method in a class, that class must be abstract.


1. class Bike12{
2. abstract void run();
3. }
Test it Now
compile time error
Rule: If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.

Another real scenario of abstract class


The abstract class can also be used to provide some implementation of the interface. In such case, the end
user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
19 |M.sc sem I OOPs USING JAVA

5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}

(5) Graphic User interface


GUI: Graphical USer Interface
GUI stands for Graphical User Interface. It refers to an interface that allows one to interact with electronic
devices like computers and tablets through graphic elements. It uses icons, menus and other graphical
representations to display information, as opposed to text-based commands. The graphic elements enable
users to give commands to the computer and select functions by using mouse or other input devices.

The programs which run under a GUI has a specific set of graphic elements so that after learning a specific
interface, a user can use these programs without learning new commands.

Xerox 8010 Information system was the first GUI-centric computer operating model. It was developed at
Xerox PARC by Alan Kay, Douglas Engelbart and their associates.

As of 2014, the most popular GUIs are Microsoft Windows and Mac OS X. And, if we talk about mobile
devices, the Apple's IOS and Google's Android Interface are the widely used GUIs.

Basic Components of a GUI


o Pointer: It is a symbol that appears on the display screen. It can be moved to select commands and objects.
20 |M.sc sem I OOPs USING JAVA

o Pointing device: It allows you move the pointer and select objects on the screen, e.g. mouse or trackball.
o Icons: It refers to small images on the display screen that represent commands, files, windows etc. Using
pointer and pointing device, you can execute these commands.
o Desktop: It is the display screen that contains the icons.

GUI KEY Benefits

o It allows you to place more information within a program.


o The graphics allow users to use complex programs with greater ease.
o It saves time as you do not need to edit configurations manually.
o You can easily memorize the tasks (point-and-click).
o Helps create user-friendly software with a point-and-click interface.

(6) Event Handling


EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple example of
event handling in applet that prints a message by click on the button.

Example of EventHandling in applet:

1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
21 |M.sc sem I OOPs USING JAVA

18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked only once.

myapplet.html

1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

(7) Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The
java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener
22 |M.sc sem I OOPs USING JAVA

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For
example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:
23 |M.sc sem I OOPs USING JAVA

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example
that sets the position of the component it may be button, textfield etc.

2) Java event handling by outer class


24 |M.sc sem I OOPs USING JAVA

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(tf);
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
23. }
1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }

3) Java event handling by anonymous class

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
25 |M.sc sem I OOPs USING JAVA

5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }

(8) Java Applet


Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It
runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.


26 |M.sc sem I OOPs USING JAVA

Do You Know
o Who is responsible to manage the life cycle of an applet ?
o How to perform animation in applet ?
o How to paint like paint brush in applet ?
o How to display digital clock in applet ?
o How to display analog clock in applet ?
o How to communicate two applets ?

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass
of Component.

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
27 |M.sc sem I OOPs USING JAVA

4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1. 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.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.

How to run an Applet?


There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


28 |M.sc sem I OOPs USING JAVA

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 click the html file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software that resides on the
browser.

myapplet.html

1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:


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 First.java. Now Html file is not required but it is for testing
purpose only.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
29 |M.sc sem I OOPs USING JAVA

12. <applet code="First.class" width="300" height="300">


13. </applet>
14. */

(9) writing applets Using Swing


Java Swing Tutorial
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation and
controller acts as an interface between model and view.

What is JFC
30 |M.sc sem I OOPs USING JAVA

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.

Do You Know

o How to create runnable jar file in java?


o How to display image on a button in swing?
o How to change the component color by choosing a color from ColorChooser ?
o How to display the digital watch in swing tutorial ?
o How to create a notepad in swing?
o How to create puzzle game and pic puzzle game in swing ?
o How to create tic tac toe game in swing ?

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


31 |M.sc sem I OOPs USING JAVA

The methods of Component class are widely used in java swing that are given below.

Method Description

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.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame object
inside the main() method.

File: FirstSwingExample.java

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
32 |M.sc sem I OOPs USING JAVA

14. }
15. }

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java

1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position
of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java

1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
33 |M.sc sem I OOPs USING JAVA

3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
download this example
What we will learn in Swing Tutorial
o JButton class
o JRadioButton class
o JTextArea class
o JComboBox class
o JTable class
o JColorChooser class
o JProgressBar class
o JSlider class
o Digital Watch
o Graphics in swing
o Displaying image
o Edit menu code for Notepad
o OpenDialog Box
o Notepad
o Puzzle Game
o Pic Puzzle Game
o Tic Tac Toe Game
o BorderLayout
o GridLayout
o FlowLayout
o CardLayout
34 |M.sc sem I OOPs USING JAVA

(10) Error Handling


On execution of a program, errors also run along with the program. If these errors will not be handled properly,
then the program may not run smoothly.

Error handling let us handle these errors by taking appropriate action and run program smoothly. Various types of
errors can be handled by error handling.

You need to catch the error and run your program smoothly by rectifying the error. Perl provides a number of ways
to do so which are illustrated below.

Perl Script without Die function


The die() function gives you a proper error message. It immediately terminates the script on encountering an error.
If you won't use die() function in your script, your script will keep on running.

1. use strict;
2. use warnings;
3. open(my $fh, '>', 'sssit/javatpoint/file1.txt');
4. print $fh "Example to show Error Handling\n";
5. close $fh;
6. print "done\n";

Output:

Print() on closed filehandle $fh at script.pl


done

Look at the above output, the script keeps on running on encountering error printing 'done'.

Perl Open or Die


The open() function will only open your file as usual. The die() function throws an exception and just exit the
script.

In 'open or die' function, on left side we have open() function. On right side we have die() function.

If open() function returns true, then script goes on next line and die() function doesn't execute.

If open() function returns false, then script goes on die() function which throws an exception and exit the script.

Here, in this example we have given the wrong path of the file due to which die() function will execute and exit the
script.

1. use strict;
2. use warnings;
35 |M.sc sem I OOPs USING JAVA

3. open(my $fh, '>', 'sssit/javatpoint/file1.txt') or die;


4. print $fh "Example to show Error Handling\n";
5. close $fh;
6. print "done\n";

Output:

Died at script.pl

In the output, as we use die() function script exit on encountering error. Hence, 'done' is not printed.

Perl Adding Explanation in Die


If you want to add some explanation about the error, you can add it in die() function. If your script dies, this
explanation will print as the error message.

1. use strict;
2. use warnings;
3. open(my $fh, '>', 'sssit/javatpoint/report.txt')
4. or die "Could not open file due to 'sssit/javatpoint/report.txt'";
5. close $fh;
6. print "done\n";

Output:

Could not open file due to 'sssit/javatpoint/report.txt'at script.pl

Look at the above output, we got an explanation about the error in our script.

Perl Error Reporting using $!


The $! Variable is a built in variable in Perl language. By adding explanation in die() function, we know the error
message but we still don't know the reason behind it. To know the exact reason of error use $! variable. It will print
the message told by operating system about the file.

1. use strict;
2. use warnings;
3. my $filename = 'sssit/javatpoint/file1.txt';
4. open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
5. close $fh;
6. print "done\n";

Output:
36 |M.sc sem I OOPs USING JAVA
Could not open file 'sssit/javatpoint/file1.txt' No such file or directory

Perl warn Function


A warn function gives a warning message but does not exit the script. The script will keep on running. Hence, it is
useful when you only want to print the warning message and proceed for the rest of the program.

1. use strict;
2. use warnings;
3. my $filename = 'sssit/javatpoint/file1.txt';
4. open(my $fh, '>', $filename) or warn "Can't open file";
5. print "done\n";

Output:

Can't open file at hw.pl at line 4.


done

Look at the above output, we have printed 'done' to show that execution continues even after printing warning
message.

Perl Error Reporting using confess Function


The modern approach for error handling is to use Carp standard library. The confess() function is used within Carp
library. We have passed $! as its argument.

1. use strict;
2. use warnings;
3. use Carp;
4. my $filename = 'sssit/javatpoint/file1.txt';
5. open(my $fh, '>', $filename) or confess($!);
6. print "done\n";

Output:

No such file or directory.


done

Perl eval Function


An eval() function is a built-in function in Perl which is used to detect normal fatal error. The eval() function is
supplied with a code block instead of passing into string.

If there are syntax errors, eval block will fail. But if a runtime error occurs, the script carries on running.

In the following program,there is no syntax error.

use strict; use warnings; my $result = eval { my $x = 10; my $y = 0; my $result2 = $x/$y; print "$result2"; }; print "Script is still
running!\n"; unless($result) { print $@; }

Output:
37 |M.sc sem I OOPs USING JAVA
Script is still running!
Illegal division by zero

Look at the above output, script keeps on running as their is no syntax error.

Difference between die() and confess()


The die() function is used when script short comprising of ten lines. The die() function can also be used without $!.

The confess() function is used inside carp package. For a larger script, it is better to use confess function.

(11) Java Exceptions

Exception Handling in Java


Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and
unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.
Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
38 |M.sc sem I OOPs USING JAVA

6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the
code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is why we use exception handling
in Java.

Do You Know?

o What is the difference between checked and unchecked exceptions?


o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error. The hierarchy of Java Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked
exception. However, according to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
39 |M.sc sem I OOPs USING JAVA

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions
are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError


etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It means we
can't use try block alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
in the method. It doesn't throw an exception. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the
exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
40 |M.sc sem I OOPs USING JAVA

7. //rest code of the program


8. System.out.println("rest of the code...");
9. }
10. }
Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will cause
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
41 |M.sc sem I OOPs USING JAVA

(12) JDBC Driver


JDBC Driver is a software component that enables java application to interact with the database. There are 4 types
of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts
JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.

In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers
provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:

o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC function calls.
42 |M.sc sem I OOPs USING JAVA

o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely in java.

Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.
43 |M.sc sem I OOPs USING JAVA

Advantage:

o No client side library is required because of application server that can perform many tasks like auditing, load
balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be
done in the middle tier.

4) Thin diver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as
thin driver. It is fully written in Java language.
44 |M.sc sem I OOPs USING JAVA

Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

(13) Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) 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.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException


Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in
the classpath, and then JDBC driver manager can detect and load the driver automatically.

Example to register the OracleDriver class


45 |M.sc sem I OOPs USING JAVA

Here, Java program is loading oracle driver to esteblish database connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of statement is
responsible to execute queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

Example to create the statement object

1. Statement stmt=con.createStatement();

4) Execute the query


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.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


46 |M.sc sem I OOPs USING JAVA

1. ResultSet rs=stmt.executeQuery("select * from emp");


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

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException

Example to close connection

1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
(14)

You might also like