Module 4 Topic Wise 2024-25 End
Module 4 Topic Wise 2024-25 End
PREPARED BY
ARPITHA K M
• Packages:
Packages
Packages and Member Access
Importing Packages.
Package
A set of classes and interfaces grouped together are known as Packages in
JAVA.
To create a package is quite easy: simply include a package command as the
first statement in a Java source file.
Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default
package, which has no name
While the default package is fine for short, sample programs, it is
inadequate for real applications.
Commonly Used Java Packages
• java.lang: Automatically imported; contains core classes like String,
Math, Object.
• java.util: Utility classes like Collections, ArrayList.
• java.io: Input/output classes like File, InputStream.
• java.net: Networking classes like Socket, URL.
• java.sql: Database access classes like Connection, ResultSet.
• Types of Packages
1. Built-in Packages:
Provided by Java's API.
Examples:
java.util: Utility classes (e.g., ArrayList, HashMap).
java.io: Input/Output classes (e.g., File, BufferedReader).
java.net: Networking classes (e.g., Socket, URL).
2.USER-defined Packages:
Created by developers to organize their own classes.
Example:
package mypackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass!");
}
}
Packages and member access
• In Java, packages and member access modifiers work together to control how classes
and their members (fields, methods, constructors) are accessed.
• Packages organize code, while access modifiers determine visibility. Understanding
their interplay is crucial for encapsulation and modularity.
• Packages act as containers for classes and other subordinate packages.
• Classes act as containers for data and code.
1. Default Access (Package-private)
Members with no access modifier are accessible only within the same package.
They are not visible to subclasses or other classes outside the package.
Example:
package pack1;
class A {
void defaultMethod() {
System.out.println("Default method in pack1");
}
}
package pack2;
import pack1.A; // Error: A is not accessible
class B {
public static void main(String[] args) {
A obj = new A(); // Error
obj.defaultMethod(); // Error
}
}
2. Public Access
Public members are accessible from any class, in any package.
Example:
package pack1;
public class A {
public void publicMethod() {
System.out.println("Public method in pack1");
}
}
package pack2;
import pack1.A;
class B {
public static void main(String[] args) {
A obj = new A(); // Accessible
obj.publicMethod(); // Accessible
}
}
3. Protected Access
Protected members are accessible:
Within the same package.
In subclasses (even in different packages).
Example:
package pack1;
public class A {
protected void protectedMethod() {
System.out.println("Protected method in pack1");
}
}
package pack2;
import pack1.A;
class B extends A {
public static void main(String[] args) {
B obj = new B(); // Subclass in a different package
obj.protectedMethod(); // Accessible due to inheritance
}
}
4. Private Access
Private members are accessible only within the same class.
They are not accessible outside their defining class, even within the same package.
Example:
package pack1;
public class A {
private void privateMethod() {
System.out.println("Private method in pack1");
}
public void accessPrivateMethod() {
privateMethod(); // Accessible within the same class
}
}
package pack2;
import pack1.A;
class B {
public static void main(String[] args) {
A obj = new A();
// obj.privateMethod(); // Error: Not accessible
obj.accessPrivateMethod(); // Indirect access allowed
}
}
Modifier Same Package Different Package
Syntax:
import packageName.ClassName;
Example:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
System.out.println(list);
}
}
2. Importing the Entire Package
You can import all the classes and interfaces in a package using a wildcard *.
Syntax:
import packageName.*;
Example:
import java.util.*;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
HashMap<Integer, String> map = new HashMap<>();
list.add("Hello");
map.put(1, "World");
System.out.println(list + " " + map);
}
}
Exception Handling Fundamentals in
Java
• Exception handling in Java is a mechanism to handle runtime errors,
ensuring smooth execution of the program even in the presence of
errors.
• This mechanism prevents abrupt termination of the program by
providing ways to handle or recover from exceptions.
• Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
What is Exception in Java?
• In Java, an exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.
• These exceptions can occur for various reasons, such as invalid user
input, file not found, or division by zero. When an exception occurs, it
is typically represented by an object of a subclass of the
java.lang.Exception class.
Types of Java Exceptions
• In Java, exceptions are categorized into two main types: checked
exceptions and unchecked exceptions.
• Additionally, there is a third category known as errors.
• Let's delve into each of these types:
1)BUILT IN EXCEPTIONS
Checked Exception
Unchecked Exception
Error
2) USER DEFINED EXCEPTION/Coustom exception
Types of exception handling
1. Checked Exceptions
• Checked exceptions are the exceptions that are checked at compile-time.
• This means that the compiler verifies that the code handles these exceptions either by
catching them or declaring them in the method signature using the throws keyword.
• Examples of checked exceptions include:
IOException: An exception is thrown when an input/output operation fails, such as
when reading from or writing to a file.
SQLException: It is thrown when an error occurs while accessing a database.
ParseException: Indicates a problem while parsing a string into another data type,
such as parsing a date.
ClassNotFoundException: It is thrown when an application tries to load a class
through its string name using methods like Class.forName(), but the class with the
specified name cannot be found in the classpath.
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
// Attempting to open a file
FileReader reader = new FileReader("example.txt");
System.out.println("File opened successfully.");
reader.close();
} catch (IOException e) {
// Handling the checked exception
System.out.println("An error occurred: " + e.getMessage());
}
}
}
• 2. Unchecked Exceptions (Runtime Exceptions)
• Unchecked exceptions, also known as runtime exceptions, are not checked at
compile-time.
• These exceptions usually occur due to programming errors, such as logic
errors or incorrect assumptions in the code.
• They do not need to be declared in the method signature using the throws
keyword, making it optional to handle them.
• Examples of unchecked exceptions include:
NullPointerException: It is thrown when trying to access or call a method on
an object reference that is null.
ArrayIndexOutOfBoundsException: It occurs when we try to access an array
element with an invalid index.
ArithmeticException: It is thrown when an arithmetic operation fails, such as
division by zero.
public class UncheckedExceptionExample {
public static void main(String[] args) {
try {
// Attempting to divide by zero, which will cause ArithmeticException
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Catching the unchecked exception
System.out.println("Error: " + e.getMessage());
}
}
}
3. Errors
• Errors represent exceptional conditions that are not expected to be caught
under normal circumstances.
• They are typically caused by issues outside the control of the application,
such as system failures or resource exhaustion.
• Errors are not meant to be caught or handled by application code.
Examples of errors include:
OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot
allocate enough memory for the application.
StackOverflowError: It is thrown when the stack memory is exhausted due
to excessive recursion.
NoClassDefFoundError: It indicates that the JVM cannot find the definition
of a class that was available at compile-time.
public class ErrorHandlingExample {
public static void main(String[] args) {
try {
// Attempting to create a massive array to trigger
OutOfMemoryError
int[] largeArray = new int[Integer.MAX_VALUE];
} catch (OutOfMemoryError e) {
// Catching the Error
System.out.println("Error: " + e.getMessage());
}
System.out.println("Program continues after catching the error.");
}
User defined exception or Creating
Your Own Exception Subclasses
• In Java, we can write our own exception class by extends the
Exception class.
• We can throw our own exception on a particular condition using the
throw keyword.
• For creating a user-defined exception, we should have basic
knowledge of the try-catch block and throw keyword.
Output:
• Exception caught: nonexistent.txt (No such file or directory)
5) finally Block
The finally block executes regardless of whether an exception is thrown or caught.
Typically used for cleanup operations (e.g., closing files, releasing resources).
Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Exception occurs here
}
catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
finally {
System.out.println("Finally block executed");
}
}
}
• Output:
• Caught ArithmeticException: / by zero
• Finally block executed
Nested try block
• In Java, using a try block inside another try block is permitted. It is
called as nested try block. Every statement that we enter a
statement in try block, context of that exception is pushed onto
the stack. //try catch block within another try block
• Sometimes a situation may arise where a part of a block may try
cause one error and the entire block itself may cause another {
error. In such cases, exception handlers have to be nested. statement 3;
statement 4;
Syntax:
....
//main try block catch(Exception e2)
{
try //exception message
{ }
}
statement 1; catch(Exception e1)
statement 2; {
//exception message
}
}
....
public class NestedTryExample { catch (ArithmeticException e) {
public static void main(String[] args) { System.out.println("Caught ArithmeticException in inner try
block: " + e.getMessage());
try { // Outer try block }
System.out.println("Outer try block started."); System.out.println("Outer try block completed.");
int[] numbers = {1, 2, 3}; }
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Accessing an element: " + numbers[2]);
System.out.println("Caught ArrayIndexOutOfBoundsException
try { in outer try block: " + e.getMessage());
// Inner try block }
finally {
System.out.println("Inner try block started.");
System.out.println("Outer finally block executed.");
int result = 10 / 0; // This will cause an ArithmeticException }
System.out.println("This line won't be executed."); System.out.println("Program continues...");
} }
}
Built in exception
1) Checked Exceptions:These exceptions are checked at compile-time,
meaning the compiler requires you to handle them using a try-catch block
or declare them with a throws clause.
Exception Name Description
Signals an I/O operation failure (e.g., file not found or failed to read/write to a
IOException file).
FileNotFoundException Thrown when a file with the specified pathname does not exist.
SQLException Indicates database access errors.
ClassNotFoundException Thrown when a specified class cannot be found.
CloneNotSupportedExcept Thrown when attempting to clone an object that does not implement the
ion Cloneable interface.
InterruptedException Indicates that a thread was interrupted during sleep, wait, or join.
2. Unchecked Exceptions:Unchecked exceptions are not checked at
compile-time. They occur due to programming errors like invalid
operations or incorrect logic. These extend the RuntimeException class.
Exception Name Description
ArithmeticException Thrown when an illegal arithmetic operation occurs (e.g., divide by zero).
IllegalStateException Signals that a method has been invoked at an illegal or inappropriate time.
• 3. Errors