0% found this document useful (0 votes)
6 views18 pages

Module 4.Docx

Java packages are used to group related classes and interfaces, preventing naming conflicts and promoting organization and encapsulation. They can be built-in or user-defined, with specific import methods to access classes. Exception handling in Java involves checked and unchecked exceptions, with best practices for throwing, catching, and managing exceptions effectively.

Uploaded by

sukunansr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views18 pages

Module 4.Docx

Java packages are used to group related classes and interfaces, preventing naming conflicts and promoting organization and encapsulation. They can be built-in or user-defined, with specific import methods to access classes. Exception handling in Java involves checked and unchecked exceptions, with best practices for throwing, catching, and managing exceptions effectively.

Uploaded by

sukunansr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Packages in Java

Packages in Java are a mechanism that encapsulates a group of classes, sub-packages, and
interfaces. Packages are used for:

●​ Prevent naming conflicts by allowing classes with the same name to exist in different
packages, like college.staff.cse.Employee and college.staff.ee.Employee.
●​ They make it easier to organize, locate, and use classes, interfaces, and other
components.
●​ Packages also provide controlled access for Protected members that are accessible
within the same package and by subclasses.
●​ Also for default members (no access specifier) that are accessible only within the
same package.

By grouping related classes into packages, Java promotes data encapsulation, making code
reusable and easier to manage. Simply import the desired class from a package to use it in
your program.

Working of Java Packages

Directory Structure: Package names and directory structures are closely related. For
example, if a package name is college.staff.cse, then three directories are, college, staff, and
cse, where cse is inside staff, and staff is inside the college.

Naming Conventions: Package names are written in reverse order of domain names, e.g.,
org.geeksforgeeks.practice. In a college, the convention might be:

●​ college.tech.cse
●​ college.tech.ee
●​ college.art.history

Example:

import java.util.*;

Here, util is a sub-package created inside the java package.

Accessing Classes Inside a Package


In Java, we can import classes from a package using either of the following methods:

1. Import a specific class:

import java.util.Vector;

This imports only the Vector class from the java.util package.
2. Import all classes from a package:

import java.util.*;

This imports all classes and interfaces from the java.util package but does not include
sub-packages.

Example: Importing Class

Java` // Import the Vector class from // the java.util package import java.util.Vector; public
class Geeks {

public Geeks() { // java.util.Vector is imported, hence we are // able to access it directly in our
code. Vector v = new Vector(); // java.util.ArrayList is not imported, hence // we are referring
to it using the complete // package name. java.util.ArrayList l = new java.util.ArrayList(); }
public static void main(String[] args) { // Creating an instance of Geeks // class to invoke the
constructor new Geeks(); }

}`

Note:

●​ Using import package.*; imports all classes in a package, but not classes from its
sub-packages.
●​ When two packages have classes with the same name (e.g., java.util.Date and
my.package.Date), use the fully qualified name to avoid conflicts:

import java.util.Date;

import my.package.Date;

Types of Java Packages


●​ Built-in Packages
●​ User-defined Packages

1. Built-in Packages

These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:

●​ java.lang : Contains language support classes(e.g classes which defines primitive


data types, math operations). This package is automatically imported.
●​ java.io: Contains classes for supporting input / output operations.
●​ java.util : Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
●​ java.applet: Contains classes for creating Applets.
●​ java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc). 6)
●​ java.net: Contain classes for supporting networking operations.

2. User-defined Packages

These are the packages that are defined by the user.

1. Create the Package:

First we create a directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being the package
names.

Java// Name of the package must be same as the directory // under which this file is saved
package myPackage; public class MyClass { public void getNames(String s) {
System.out.println(s); } }

2. Use the Class in Program:

Now we will use the MyClass class in our program.

Java` // import 'MyClass' class from 'names' myPackage import myPackage.MyClass; public
class Geeks { public static void main(String args[]) {

// Initializing the String variable // with a value String s = "GeeksforGeeks"; // Creating an


instance of class MyClass in // the package. MyClass o = new MyClass(); o.getNames(s);

}}`

Note: MyClass.java must be saved inside the myPackage directory since it is a part of the
package.

Static Import In Java


Static Import in Java is about simplifying access to static members and separates it from the
broader discussion of user-defined packages.

Static import is a feature introduced in Java programming language (versions 5 and above)
that allows members (fields and methods) defined in a class as public static to be used in
Java code without specifying the class in which the field is defined.

Example:

Java` // Note static keyword after import. import static java.lang.System.*; class Geeks {
public static void main(String args[]) {

// We don't need to use 'System.out' // as imported using static. out.println("GeeksforGeeks");


}

}`
Output

GeeksforGeeks

Handling Name Conflicts


When two packages contain a class with the same name (e.g., java.util.Date and
java.sql.Date), specify the full package name to avoid conflicts.

import java.util.*;

import java.sql.*;

//And then use Date class, then we will get a compile-time error :

Date today ; //ERROR– java.util.Date or java.sql.Date?

The compiler will not be able to figure out which Date class do we want. This problem can be
solved by using a specific import statement:

import java.util.Date;

import java.sql.*;

If we need both Date classes then, we need to use a full package name every time we declare
a new object of that class. For Example:

java.util.Date deadLine = new java.util.Date();

java.sql.Date today = new java.sql.Date();

Directory Structure and CLASSPATH


Package names correspond to a directory structure. For example, a class Circle in package
com.zzz.project1.subproject2 is stored as:

$BASE_DIR/com/zzz/project1/subproject2/Circle.class

●​ Here $BASE_DIR represents the base directory of the package.


●​ The “dot” in the package name corresponds to a sub-directory of the file system.
●​ The base directory ( $BASE_DIR) could be located anywhere in the file system.
●​ Hence, the Java compiler and runtime must be informed about the location of the
$BASE_DIR so as to locate the classes.
●​ It is is accomplished by an environment variable called CLASSPATH.
●​ CLASSPATH is similar to another environment variable PATH, which is used by the
command shell to search for the executable programs.

Setting CLASSPATH
CLASSPATH can be set by any of the following ways:

●​ CLASSPATH can be set permanently in the environment the steps In Windows is

Go to Control Panel -> System -> Advanced -> Environment Variables.

●​ Select “System Variables” to apply the CLASSPATH for all users on the system.
●​ Select “User Variables” to apply it only for the currently logged-in user.
●​ Edit or Create CLASSPATH : If CLASSPATH already exists, select it and click
“Edit” or If it doesn’t exist, click “New”
●​ Enter CLASSPATH Details: In the “Variable name” field, enter: “CLASSPATH”,
In the “Variable value” field, enter the directories and JAR files separated by
semicolons.
●​ In the “Variable value” field, enter the directories and JAR files separated by
semicolons. Example:

.c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

●​ The dot ( .) represents the current working directory.


●​ To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath or -cp of the javac and java commands, for example,

> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

Illustration of user-defined packages: Creating our first package: File name –


ClassOne.java

Javapackage package_name; public class ClassOne { public void methodClassOne() {


System.out.println("Hello there its ClassOne"); } }

Creating our second package: File name – ClassTwo.java

Javapackage package_one; public class ClassTwo { public void methodClassTwo() {


System.out.println("Hello there i am ClassTwo"); } }

Making use of both the created packages: File name – Testing.java

Javaimport package_name.ClassOne; import package_one.ClassTwo; public class Testing {


public static void main(String[] args) { ClassTwo a = new ClassTwo(); ClassOne b = new
ClassOne(); a.methodClassTwo(); b.methodClassOne(); } }
Now having a look at the directory structure of both the packages and the testing class file:

Access Modifiers in the Context of Packages

1.​ Public: Members with the public modifier are accessible from anywhere, regardless
of whether the accessing class is in the same package or not .
2.​ Protected: Memebers with the protected modifier are accessible within the same
package, In subclasses
3.​ Default: Members with no modifier are accessible only within the same package
4.​ Private: Members with the private modifier are accessible only within the same class.
They cannot be accessed by classes in the same package, subclasses, or different
packages.

Important points:

●​ Every class is part of some package.


●​ If no package is specified, the classes in the file goes into a special unnamed package
(the same unnamed package for all files).
●​ All classes/interfaces in a file are part of the same package. Multiple files can specify
the same package name.
●​ If package name is specified, the file must be in a subdirectory called name (i.e., the
directory name must match the package name).
●​ We can access public classes in another (named) package using:
package-name.class-name
Exceptions in Java
The different kinds of exceptions in Java and some best practices for using them

Basics ​
Exception handling:

●​ A method can throw an exception indicating that something is wrong


●​ Exceptions automatically bubble up the call chain until they are handled (or, if they
are not handled, they end up terminating the current thread)
o​ Great benefit when comparing to error codes which must be manually passed
up the chain if needed
●​ Typically, exceptions include a stack trace, indicating where the exception occurred in
the code and what the call chain looked like at the time

Hierarchy of exception classes in Java:


Classes:

●​ Throwable:
o​ Common superclass for all Java exceptions
●​ Error:
o​ Exceptions defined by the Java language that are thrown when something
really bad happens that the code can normally not recover from by itself
o​ All unchecked (see below)
o​ Example: OutOfMemoryError, which occurs when Java is unable to allocate
space to an object because there is no more memory available and garbage
collection does not help. If you run into that one, the best you can generally do
is exit the program.
●​ Exception:
o​ All user-defined exceptions are subclasses of this one
o​ Exceptions deriving directly from this one are checked (see below) exceptions
●​ RuntimeException :
o​ User-defined exceptions that are subclasses of this one are unchecked (see
below) exceptions

Checked versus unchecked exceptions ​


Basic idea:

●​ Checked: Checked by compiler


o​ If your code can possibly throw a checked exception, the Java compiler
requires you to either catch the exception or use a throws declaration to
indicate that your code can throw the exception
●​ Unchecked: Not checked by compiler

Intention of this design:

●​ Use checked exceptions when there is a reasonable way of recovering from the failure
during the execution of the program
o​ Example: a call to open a file and write to it, which can fail if the file does not
exist. A reasonable way of recovering from this is trying a different filename.
o​ When using checked exceptions, the compiler forces you to to decide what to
do in case such an exception occurs. This prevents you from forgetting that
this kind of failure can actually happen.
●​ Use unchecked exceptions for errors that the program cannot reasonably recover from
o​ Example: exceptions indicating programming errors, like
NullPointerException

Alternative school of thought:

●​ Use checked exceptions if there is a reasonable way of recovering from the failure
during the execution of the program and the possibility for failure is unavoidable (an
example is a missing file: even if you checked for its existence before, the file can still
have disappeared in the meantime)
o​ If the possibility for failure is unavoidable, it makes sense to force the caller to
deal with the possible failure
●​ Use unchecked exceptions in all other cases.
●​ Evaluate these conditions at every level in the call chain.

Yet another different (and popular school of thought):

●​ Always use unchecked exceptions.


●​ Never use checked exceptions (unless you are maybe writing a very critical library).
●​ This is advertised in, amongst others, the Clean Code book by Robert C. Martin
●​ Reason: drawbacks of checked exceptions
o​ If you throw a checked exception from your code and the appropriate handler
sits three levels higher in the call chain, you must declare the exception on
every method in between
o​ This means that a single change to a small method somewhere deep in the
program can require the signature of several higher-level methods to change,
breaking encapsulation and coupling the handler of the exception to the code
that generates it
o​ This actually negates a large benefit of exceptions, which is that you can
decouple the code detecting a failure from the code handling the failure

Throwing and the throws declaration ​


Throwing unchecked exception:

public static boolean isNumberBetween(int number, int lower, int upper) { if (lower > upper)
{ throw new IllegalArgumentException( "Lower bound cannot be higher than upper bound");
} // ... }

If code can throw a checked exception, a throws clause is mandatory!

public void write(String text, String filePath) throws IOException { // potentially throws
checked IOException Files.write(Paths.get(filePath), text.getBytes()); }

Throws and inheritance:

●​ If you override a method, you cannot throw more checked exceptions than the original
throws clause specifies. Otherwise, you would break the contract of the method.
●​ If a method does not have a throws clause, a method overriding it cannot throw any
checked exceptions
●​ Note that you can perfectly override a method declaring checked exceptions with a
method not throwing any exceptions at all

Catching exceptions ​
Simple try-catch block:

try { // code potentially throwing exception } catch (TheExceptionClass ex) { // code


handling the exception }
Can also have multiple catch statements, catching exceptions of different exception classes.
They are evaluated top to bottom, so put more specific exception classes first. It is also
possible to have a handler that can handle several exception classes.

try { // code potentially throwing exception } catch (ExceptionClass1 ex) { // code handling
the exception } catch (ExceptionClass2 | ExceptionClass3 ex) { // code handling the
exception }

Cleaning up using try-with-resources ​


Java offer a try-with-resources statement. In this form of try statement, you can specify
resources that should be closed automatically. The fact that a resource can be closed
automatically is indicated by the fact that it implements the AutoCloseable interface.

public void write(ArrayList<String> lines) throws FileNotFoundException { try(PrintWriter


out = new PrintWriter("output.txt")) { for (String line: lines) {
this.possiblyGenerateException(line); out.println(line); } } }

When the code exits the try block, either because we finished processing the lines or an
exception was thrown inside, the PrintWriter will be closed automatically. It is also possible
to provide multiple resources to a try-with-resources statement. In that case, the order in
which they are closed is the reverse of the order in which they were provided.

A try-with-resources statement can also have catch clauses catching any exceptions occurring
in the statement.

Note: it is possible that closing an AutoCloseable throws an exception itself!

●​ If closing happened after normal execution of the try block, that exception is passed to
the caller
●​ If closing happened because of an exception happening inside the try block, the
exception from the try block is passed to the caller and any exceptions generated by
subsequently closing the resources will be attached as suppressed exceptions on that
exception
o​ When catching the exception that happened in the try block (the primary
exception), you can access those suppressed exceptions by invoking the
getSuppressed() method on the caught exception.

public class ThrowsOnClose implements AutoCloseable { @Override public void close() {


throw new IllegalStateException("Closing"); } }

try (ThrowsOnClose throwsOnClose = new ThrowsOnClose()) { throw new


IllegalArgumentException("Inside try"); } catch (Exception e) {
System.out.println(e.getMessage()); // Inside try for (Throwable suppressed:
e.getSuppressed()) { System.out.println(suppressed.getMessage()); // Closing } }

Cleaning up using finally ​


Alternative to the try-with-resources statement: the finally clause.
●​ After the try block and potential catch blocks, you add a finally block which will run
after the rest of the try-catch statement has finished
●​ Especially useful if you need to clean up something that is not an AutoCloseable.
●​ Note: avoid throwing exceptions in the finally block!
o​ If the code in the try block throws an exception and then the finally block
throws an exception, the caller of the method will only see the exception from
the finally block. The suppression mechanism we saw above only works with
try-with-resources statements.

Rethrowing and chaining ​


Rethrowing:

●​ Catch the exception


●​ Do something useful with it (for example, logging it)
●​ Just throw the exception object that you caught

Chaining:

●​ Catch the exception


●​ Throw a new exception instead
●​ Original exception is typically included as the cause for the new exception

Chaining example:

try { // set foreign key to parent in database } catch (SQLException ex) { throw new
ParentNotFoundException(ex); // sets ex as cause }

When the caller catches the ParentNotFoundException, it can find the original exception
using the getCause() method.

In this case, ParentNotFoundException has a constructor which allows passing the cause (this
is considered good practice). If an exception class does not allow that, the cause for the
exception can be set through the initCause() method.

Dealing with NullPointerException ​


NullPointerException is an unchecked exception indicating a programming error (we called a
method on a null reference). The best way of dealing with NullPointerException is to avoid
it.

You can make failure with a NullPointerException less likely by using the following set of
rules for your code:

●​ Don’t return null from methods. Wherever possible, return a special case object (e.g.
an empty list, which you can easily obtain from Collections.emptyList(), or an
instance of a dedicated class that was intended for these cases).
●​ Avoid passing null as a method parameter.
You can use null-safety annotations to let the compiler enforce these kinds of rules. For
example, you could use the following null-safety annotations from the Spring framework
org.springframework.lang package:

●​ @NonNull can be used to explicitly mark a field, method parameter or return value as
non-nullable
●​ @NonNullApi can be used at package level to mark all method parameters and return
values in the package as non-nullable by default
●​ @NonNullFields can be used at package level to mark all fields in the package as
non-nullable by default
●​ @Nullable can be used to explicitly mark a field, method parameter or return value as
nullable (useful for overriding @NonNullApi and @NonNullFields where needed)

The Objects class has some convenient methods for preventing problems with null pointers.
These can be used for checking arguments or preventing passing null.

●​ Objects.requireNonNull() throws a NullPointerException if the argument is null and


returns the argument itself otherwise. This does not prevent the NullPointerException
from being thrown. However, the benefit here is that we throw it where the source of
the problem lies ( null being passed where it is not allowed) instead of at some later
point in the code where we try to invoke a method on a null reference.
●​ Objects.requireNonNullElse() returns either the first parameter or, if the first
parameter is null, it returns the second parameter. It is quite similar to the
COALESCE function in SQL.

public static void test(String name, String nickname) { name =


Objects.requireNonNull(name); nickname = Objects.requireNonNullElse(nickname, "nick");
}

Something else that can help is the Optional type. Wrapping the returned value in an Optional
type makes it clear to the caller of your method that there may be no actual value returned. It
also allows the caller to deal with missing values in a nice way. See also Optional type (Java).

Turning checked exceptions into unchecked exceptions ​


In some cases, you may find yourself getting a checked exception which you want to pass up
the method chain as an unchecked exception (for example because you are overriding a
method without a throws declaration allowing the checked exception).

Simplest way to do this: chaining (see above)

●​ Catch checked exception


●​ Throw new unchecked exception with checked exception as the cause

More sneaky approach: trick the Java compiler into ignoring checked exceptions. Example
implementation (taken from Core Java SE 9 for the Impatient):

public class Exceptions { @SuppressWarnings("unchecked") private static <T extends


Throwable> void throwAs(Throwable e) throws T { throw (T) e; // erased to (Throwable) e }
public static <V> V doWork(Callable<V> c) { try { return c.call(); } catch (Throwable ex) {
Exceptions.<RuntimeException>throwAs(ex); return null; } } }

Now, any checked exceptions thrown inside the doWork method are ignored by the compiler.

public static void test() { // error: unhandled FileNotFoundException new


PrintWriter("output.txt"); // ok Exceptions.doWork(() -> new PrintWriter("output.txt")); }

Although this is a pretty cool trick, it is not generally applicable in practice. Not only would it
be confusing to catch an IOException from a method that doesn’t declare it, but the compiler
does not even allow you to do it.

public static void invokeTest() { try { test(); } catch (IOException ex) { // error: unreachable
catch block } } public static void test() { Exceptions.doWork(() -> new
PrintWriter("output.txt")); }

Some cases where this trick may make sense (although not necessarily good practice):

●​ Dealing with “impossible” exceptions


o​ Some methods in the standard library have a throws clause declaring checked
exceptions, although there are some sets of arguments which are guaranteed to
never throw an exception
o​ If you know that you are passing such a set of arguments, you could use this
trick to stop the compiler from bothering you about this impossible exception.
●​ Creating a Runnable that can throw a checked exception in its run() method (which
does not declare any checked exceptions)
o​ You can define custom error handling behavior for the thread (for both
checked and unchecked exceptions) in the thread’s uncaught exception handler

Example of the Runnable case:

public class TestRunnable implements Runnable { @Override public void run() {


Exceptions.doWork(() -> new PrintWriter("unwritableFile")); } }

Thread thread = new Thread(new TestRunnable());


thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public
void uncaughtException(Thread t, Throwable e) { if (e instanceof IOException) {
System.out.println("Caught IOException"); } } }); thread.start(); // Caught IOException

An event is a change in the state of an object triggered by some action such as Clicking a
button, Moving the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java, the
java.awt.event package provides various event classes to handle these actions.

Classification of Events
Events in Java can be broadly classified into two categories based on how they are generated:

1.​ Foreground Events: Foreground events are the events that require user interaction to
generate. Examples of these events include Button clicks, Scrolling the scrollbar,
Moving the cursor, etc.
2.​ Background Events: Events that don’t require interactions of users to generate are
known as background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.

Event Handling Mechanism


Event handling is a mechanism that allows programs to control events and define what should
happen when an event occurs. Java uses the Delegation Event Model to handle events. This
model consists of two main components:

●​ Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
●​ Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.

Registering the Source With Listener

To handle events, the source must be registered with a listener. Java provides specific
methods for registering listeners based on the type of event.

Syntax:

addTypeListener()

For example,

●​ addKeyListener() for KeyEvent


●​ addActionListener() for ActionEvent

Event Classes and Listener Interfaces


Java provides a variety of event classes and corresponding listener interfaces. Below table
demonstrates the most commonly used event classes and their associated listener interfaces:

Event Class Listener Interface Description ActionEvent ActionListener An event that


indicates that a component-defined action occurred like a button click or selecting an item
from the menu-item list. AdjustmentEvent AdjustmentListener The adjustment event is
emitted by an Adjustable object like Scrollbar. ComponentEvent ComponentListener An
event that indicates that a component moved, the size changed or changed its visibility.
ContainerEvent ContainerListener When a component is added to a container (or) removed
from it, then this event is generated by a container object. FocusEvent FocusListener These
are focus-related events, which include focus, focusin, focusout, and blur. ItemEvent
ItemListener An event that indicates whether an item was selected or not. KeyEvent
KeyListener An event that occurs due to a sequence of keypresses on the keyboard.
MouseEvent MouseListener & MouseMotionListener The events that occur due to the user
interaction with the mouse (Pointing Device). MouseWheelEvent MouseWheelListener An
event that specifies that the mouse wheel was rotated in a component. TextEvent TextListener
An event that occurs when an object’s text changes. WindowEvent WindowListener An event
which indicates whether a window has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.

Methods in Listener Interfaces


Each listener interface contains specific methods that must be implemented to handle events.
Below table demonstrates the key methods for each interface:

Listener Interface Methods ActionListener actionPerformed() AdjustmentListener


adjustmentValueChanged() ComponentListener componentResized() componentShown()
componentMoved() componentHidden() ContainerListener componentAdded()
componentRemoved() FocusListener focusGained() focusLost() ItemListener
itemStateChanged() KeyListener keyTyped() keyPressed() keyReleased() MouseListener
mousePressed() mouseClicked() mouseEntered() mouseExited() mouseReleased()
MouseMotionListener mouseMoved() mouseDragged() MouseWheelListener
mouseWheelMoved() TextListener textChanged() WindowListener windowActivated()
windowDeactivated() windowOpened() windowClosed() windowClosing()
windowIconified() windowDeiconified()

Flow of Event Handling


The event handling process in Java follows these steps:

1.​ User Interaction with a component is required to generate an event.


2.​ The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3.​ The newly created object is passed to the methods of the registered listener.
4.​ The method executes and returns the result.

Approaches For Event Handling


Java provides three main approaches to implement event handling

1. Event Handling Within the Class

Java` // Java program to demonstrate the // event handling within the class import java.awt.;
import java.awt.event.; class GFGTop extends Frame implements ActionListener { TextField
textField; GFGTop() { // Component Creation textField = new TextField(); // setBounds
method is used to provide // position and size of the component textField.setBounds(60, 50,
180, 25); Button button = new Button("click Here"); button.setBounds(100, 120, 80, 30); //
Registering component with listener // this refers to current instance
button.addActionListener(this); // add Components add(textField); add(button); // set
visibility setVisible(true); }

// implementing method of actionListener public void actionPerformed(ActionEvent e) { //


Setting text to field textField.setText("GFG!"); } public static void main(String[] args) { new
GFGTop(); }

}`

Output:

Explanation:

●​ Firstly extend the class with the applet and implement the respective listener.
●​ Create Text-Field and Button components.
●​ Registered the button component with respective event. i.e. ActionEvent by
addActionListener().
●​ In the end, implement the abstract method.

2. Event Handling by Another Class

Java` // Java program to demonstrate the // event handling by the other class import java.awt.;
import java.awt.event.; class GFG1 extends Frame { TextField textField; GFG2() { //
Component Creation textField = new TextField();

// setBounds method is used to provide // position and size of component


textField.setBounds(60, 50, 180, 25); Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30); Other other = new Other(this); // Registering component
with listener // Passing other class as reference button.addActionListener(other); // add
Components add(textField); add(button); // set visibility setVisible(true); } public static void
main(String[] args) { new GFG2(); }

}`

Separate class implementing ActionListener to handle events:

Java/// import necessary packages import java.awt.event.*; // implements the listener


interface class Other implements ActionListener { GFG2 gfgObj; Other(GFG1 gfgObj) {
this.gfgObj = gfgObj; } public void actionPerformed(ActionEvent e) { // setting text from
different class gfgObj.textField.setText("Using Different Classes"); } }

Output:

3. Event Handling By Anonymous Classes

Java` // Java program to demonstrate the // event handling by the anonymous class import
java.awt.; import java.awt.event.; class GFG3 extends Frame { TextField textField; GFG3() {
// Component Creation textField = new TextField();

// setBounds method is used to provide // position and size of component


textField.setBounds(60, 50, 180, 25); Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30); // Registering component with listener anonymously
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent
e) { // Setting text to field textField.setText("Anonymous"); } }); // add Components
add(textField); add(button); //make size viewable setSize(300,300); // set visibility
setVisible(true); } public static void main(String[] args) { new GFG3(); }

}`
Output:

Note: To run event handling code, use an IDE or install the JDK. Online compilers may
throw errors due to the unavailability of certain packages.

You might also like