0% found this document useful (0 votes)
19 views44 pages

Module 4 Topic Wise 2024-25 End

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

Module 4 Topic Wise 2024-25 End

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

MODULE 4

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

public Fully accessible Fully accessible

Protected Accessible Accessible in subclasses only

default Accessible not Accessible

Private Accessible not Accessible


Importing Packages in Java
• In Java, the import statement is used to bring classes, interfaces, or
entire packages from other namespaces into the current file, so you can
use them without specifying their fully qualified names.

• Why Import a Package?


Simplifies Code: Instead of using fully qualified names (e.g.,
java.util.ArrayList), you can directly use the class name (ArrayList).
Organized Access: You can access only the specific classes or entire
packages that you need.
There are two main ways to import packages in Java:
1. Importing a Single Class or Interface
You can import a specific class or interface from a 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.

note: u can lab 9 custom program as an example


import java.util.*;
class UserDefinedException{
public static void main(String args[]){
try{
throw new NewException(5);
}
catch(NewException ex){
System.out.println(ex) ;
}
}
}
class NewException extends Exception{
int x;
NewException(int y) {
x=y;
}
public String toString(){
return ("Exception value = "+x) ;
}
}
Keywords of exception
• Java uses try, catch, throw, throws, and finally to manage exceptions.
1) Try
 A try block is used to enclose code that might throw an exception.
 If an exception occurs within the try block, control immediately passes to the corresponding catch block.
SYNTAX:
EXAMPLE:
public class TryExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
}
catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:Exception caught: / by zero
2) catch Block
 The catch block handles the exception thrown in the try block.
 You can have multiple catch blocks for different types of exceptions.
Example:
public class CatchExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length()); // NullPointerException
}
catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
catch (Exception e) {
System.out.println("Caught General Exception: " + e.getMessage());
}
}
}
• Output:
Caught NullPointerException: Cannot invoke "String.length()" because "str" is null
3) throw statement
 The throw statement in Java is used to explicitly throw an exception.
 It is commonly used within a method or block of code to indicate that an error has occurred, typically by creating an instance of an exception
class and passing it to the throw keyword.
 The throw statement is often used for custom error handling or to propagate exceptions to higher levels in the program.
public class ThrowExample {
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
System.out.println("Access granted");
}
public static void main(String[] args) {
try {
checkAge(16); // Throws IllegalArgumentException
}
catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}}}
• Output:
• Exception caught: Age must be 18 or above
4) The throws keyword
 The throws keyword in Java is used in a method declaration to indicate that the method might throw
one or more exceptions.
 It allows the caller of the method to handle the specified exceptions rather than catching them
within the method itself.
 For example, void readFile() throws IOException means the method might throw an IOException,
and the caller must either handle it using a try-catch block or declare it using throws.
 This keyword is commonly used with checked exceptions to propagate errors up the call stack.
import java.io.*;
public class ThrowsExample {
static void readFile() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("nonexistent.txt"));
reader.readLine();
}
public static void main(String[] args) {
try {
readFile(); // Throws IOException
}
catch (IOException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

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

NullPointerException Indicates that a null reference is being accessed or dereferenced.

ArrayIndexOutOfBoundsException Thrown when accessing an array with an invalid index.

StringIndexOutOfBoundsException Indicates accessing an invalid index of a string.

ClassCastException Occurs when an object is cast to a subclass it is not an instance of.

IllegalArgumentException Thrown when an illegal or inappropriate argument is passed to a method.

NumberFormatException Indicates an attempt to convert a string to a number fails.

IllegalStateException Signals that a method has been invoked at an illegal or inappropriate time.
• 3. Errors

• Errors represent serious problems that applications should not try to


catch. These are generally related to the JVM and system-level failures.

Error Name Description


Thrown when the stack limit is exceeded, often due
StackOverflowError to infinite recursion.
OutOfMemoryError Thrown when the JVM runs out of memory.
Indicates a class required during execution is not
NoClassDefFoundError
found.

Thrown when an assertion fails, used for debugging


AssertionError purposes.

Occurs when a class dependency cannot be linked


LinkageError correctly.
Uncaught exceptions
• Uncaught exceptions specifically refer to exceptions that are not
caught by any catch block within a program.
• When an uncaught exception occurs, the Java Virtual Machine (JVM)
terminates the program's execution and prints a stack trace, providing
valuable information about the cause and location of the exception.
• public class UncaughtExceptionExample {
• public static void main(String[] args) {
• int result = 10 / 0; // This will throw ArithmeticException
• System.out.println("This line will not be executed.");
• }
•}
• Output:

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


at UncaughtExceptionExample.main(UncaughtExceptionExample.java:3)
Chained exceptions
• Chained exceptions in Java allow developers to associate one
exception (the cause) with another exception (the primary exception),
providing a way to represent a sequence of errors that occurred
during the program's execution.
• This feature is particularly useful when an exception is caused by
another exception, as it helps in debugging by showing the entire
chain of exceptions leading to the problem.
• The following methods in the Throwable class are used to handle chained
exceptions:
1)initCause(Throwable cause)
• Sets the cause of the current exception.
• Must be invoked on an exception before the exception is thrown.
• Throws IllegalStateException if the cause is already initialized.
2)getCause()
• Retrieves the cause of the exception (another Throwable object).
• Returns null if no cause was set.
Constructors Supporting Chained Exceptions
• Most exception classes provide constructors to set the cause at the time of
instantiation:
• Exception(String message, Throwable cause)
• RuntimeException(String message, Throwable cause)
public class ChainedExceptionExample {
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void methodA() throws Exception {
try {
methodB();
} catch (Exception e) {
throw new Exception("Exception in methodA", e); // Chain exception
}
}
public static void methodB() throws Exception {
throw new Exception("Exception in methodB");
}
}
output
java.lang.Exception: Exception in methodA
at ChainedExceptionExample.methodA(ChainedExceptionExample.java:12)
at ChainedExceptionExample.main(ChainedExceptionExample.java:6)
Caused by: java.lang.Exception: Exception in methodB
at ChainedExceptionExample.methodB(ChainedExceptionExample.java:16)
at ChainedExceptionExample.methodA(ChainedExceptionExample.java:10)
... 1 more

You might also like