Module 4.Docx
Module 4.Docx
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.
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.*;
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.
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;
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:
2. User-defined Packages
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); } }
Java` // import 'MyClass' class from 'names' myPackage import myPackage.MyClass; public
class Geeks { public static void main(String args[]) {
}}`
Note: MyClass.java must be saved inside the myPackage directory since it is a part of the
package.
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[]) {
}`
Output
GeeksforGeeks
import java.util.*;
import java.sql.*;
//And then use Date class, then we will get a compile-time error :
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:
$BASE_DIR/com/zzz/project1/subproject2/Circle.class
Setting CLASSPATH
CLASSPATH can be set by any of the following ways:
● 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
CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
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,
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:
Basics
Exception handling:
● 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
● 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
● 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.
public static boolean isNumberBetween(int number, int lower, int upper) { if (lower > upper)
{ throw new IllegalArgumentException( "Lower bound cannot be higher than upper bound");
} // ... }
public void write(String text, String filePath) throws IOException { // potentially throws
checked IOException Files.write(Paths.get(filePath), text.getBytes()); }
● 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 (ExceptionClass1 ex) { // code handling
the exception } catch (ExceptionClass2 | ExceptionClass3 ex) { // code handling the
exception }
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.
● 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.
Chaining:
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.
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.
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).
More sneaky approach: trick the Java compiler into ignoring checked exceptions. Example
implementation (taken from Core Java SE 9 for the Impatient):
Now, any checked exceptions thrown inside the doWork method are ignored by the compiler.
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):
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.
● 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.
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,
Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.
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); }
}`
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.
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();
}`
Output:
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();
}`
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.