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

java_Unit_3

This document provides an overview of packages, interfaces, and exception handling in Java. It explains the purpose of packages for organizing code, the structure and access control of classes, and the concept of interfaces as contracts for classes. Additionally, it covers exception handling, including checked and unchecked exceptions, try-catch blocks, and nested try statements for managing errors in Java programs.

Uploaded by

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

java_Unit_3

This document provides an overview of packages, interfaces, and exception handling in Java. It explains the purpose of packages for organizing code, the structure and access control of classes, and the concept of interfaces as contracts for classes. Additionally, it covers exception handling, including checked and unchecked exceptions, try-catch blocks, and nested try statements for managing errors in Java programs.

Uploaded by

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

UNIT 3

Packages Interfaces, & Exception


Handling
COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTRODUCTION TO PACKAGES
 A package is a way to organize and group related classes, interfaces, enums, and
other types.
 It provides a hierarchical structure for managing classes and helps prevent naming
conflicts between classes with the same name in different contexts.
 Packages also promote modularity and code organization in larger projects.
Here are some key points to understand about packages in Java:
• Package Naming Convention: Packages are named using the reverse domain
name convention to ensure uniqueness. For example, if you own the domain
example.com, your package names might start with com.example.

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTRODUCTION TO PACKAGES
• Package Naming Convention: Packages are named using the reverse domain
name convention to ensure uniqueness. For example, if you own the domain
example.com, your package names might start with com.example.
• Package Declaration: At the beginning of a Java file, you can declare the
package to which the class belongs using the package keyword. For example:

package com.example.myproject;
public class MyClass {
// class code
}

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTRODUCTION TO PACKAGES
• Access Control: Packages provide a level of access control. Classes within the
same package can access package-private (default) members of other classes
in the same package. However, to access members of classes in different
packages, you need to use appropriate access modifiers (public, protected,
private).

• Import Statements: To use classes from other packages, you typically need to
import them using the import statement. For example:

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTRODUCTION TO PACKAGES

import com.example.otherpackage.OtherClass;

public class MyClass {


public static void main(String[] args) {
OtherClass obj = new OtherClass();
// use obj
}
}

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTRODUCTION TO PACKAGES
• Java Standard Libraries: Java's standard libraries are also organized into
packages. For example, commonly used classes and utilities are part of the
java.lang package.
• Subpackages: You can have subpackages within packages to further organize
your code. For instance, com.example.myproject.utilities would be a
subpackage of com.example.myproject.
• Accessing Classes from Different Packages: To access classes from different
packages, you can either use the fully qualified class name (with the package
name) or import the class using the import statement. For example:

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTRODUCTION TO PACKAGES

// Using fully qualified name


com.example.otherpackage.OtherClass obj = new
com.example.otherpackage.OtherClass();

// Using import statement


import com.example.otherpackage.OtherClass;
// ...
OtherClass obj = new OtherClass();

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
ACCESS PROTECTION IN PACKAGES
• Access protection in Java refers to the level of visibility or accessibility that
classes, members (fields and methods), and types have within and outside
their defining packages. The access modifiers (public, protected,
default/package-private, and private) control this visibility.
Here's how access protection works when importing packages:
• public Modifier: When a class, method, or field is declared as public, it can be
accessed from any other class or package.
• Default/Package-Private Modifier: If no access modifier is specified (also known as
package-private or default access), the class, method, or field can only be accessed
within the same package. It's not accessible from classes in other packages.

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
ACCESS PROTECTION IN PACKAGES
• Protected Modifier: A protected member is accessible within the same package
and by subclasses (even if they are in different packages) through inheritance.
However, it's not directly accessible from classes outside the package that aren't
subclasses of the declaring class.
• Private Modifier: A private member is accessible only within the same class. It's
not accessible from other classes, including classes in the same package.
 When importing packages and accessing members from different packages, here's how
access protection comes into play:
• public Members: public members of a class can be accessed from any other class,
regardless of whether they are in the same package or a different package. Importing
the package that contains the class is sufficient to access its public members.

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
ACCESS PROTECTION IN PACKAGES
• Default/Package-Private Members: Members with default/package-private
access are accessible only within the same package. If you import a package
containing a class with default access members, you can access those
members only if you are in the same package.
• Protected Members: protected members can be accessed by subclasses, even if they
are in different packages. However, they are not directly accessible by unrelated classes
outside the package.
• Private Members: private members are accessible only within the same class. They
cannot be accessed from any other class, regardless of whether they are in the same
package or a different package.

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTERFACES
• An interface is a reference type that defines a contract or a set of abstract methods
that a class implementing the interface must provide concrete implementations for.
• Think of an interface like a "contract" or a "to-do list" that a class agrees to follow.
Imagine you're playing a game, and you and your friends decide to create a set of
rules to play the game. These rules are like the methods that need to be in the class.
• For example, let's say you have an interface called Animal with a method
makeSound(). Any class that wants to be an Animal must have a makeSound()
method.
• When a class implements an interface, it's like signing a contract. The class says, "I
promise to have all the methods from the interface." So, you create those methods in
your class to follow the rules of the interface.

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTERFACES: IMPLEMENTATION
• Imagine you have an interface named Shape that defines a method called
calculateArea(). Any class that wants to be a Shape must have this method.
Here's how you would implement this interface in a class:
• Create the Interface:
interface Shape {
double calculateArea();
}
• Implement the Interface: Let's say you want to create a class for a Circle. You know that
circles have a way to calculate their area, so you implement the Shape interface in the Circle
class.

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTERFACES: IMPLEMENTATION
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 15
INTERFACES: IMPLEMENTATION
• Now, the Circle class has promised to have a calculateArea() method as per the
Shape interface. You've provided the specific implementation of this method
for circles by using the formula for the area of a circle.
• Using the Implementation: You can now create Circle objects and use the
calculateArea() method:
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
double area = circle.calculateArea();
System.out.println("Area of the circle: " + area);
}}

COURSE CODE: BCECCE3103 21-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 16
Exception Handling
 In Java, exceptions are unexpected events that occur during the execution of a
program. These events can disrupt the normal flow of the program. Examples
include division by zero, accessing an array element out of bounds, or trying to
open a file that doesn't exist.
 Exception handling allows you to gracefully manage errors and unexpected
situations in your Java programs. It prevents your program from crashing and
helps you provide meaningful error messages to users.
Types of Exceptions
 Checked Exceptions: Checked exceptions are exceptions that are checked by
the Java compiler during compilation.

COURSE CODE: BCECCE3103 25-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 16
Types of Exceptions
 This means that the compiler will ensure that you handle or declare these
exceptions, either by using a try-catch block to handle the exception or by
declaring that your method can throw the exception using the throws
keyword. Common checked exceptions include:
• IOException: This exception occurs when there's an issue with input or
output operations, such as reading from or writing to files.
• SQLException: This exception is related to database operations and occurs
when there's a problem with database connectivity or SQL queries.
• ClassNotFoundException: This exception is thrown when the Java Virtual
Machine (JVM) can't find a required class at runtime.

COURSE CODE: BCECCE3103 25-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 16
Types of Exceptions
 Unchecked Exceptions: Unchecked exceptions are exceptions that are not
checked by the compiler at compile time. This means you're not required to
handle or declare them explicitly. Unchecked exceptions are typically caused
by programming errors and are often referred to as runtime exceptions.
Common unchecked exceptions include:
• NullPointerException: This occurs when you try to access a method or field on
an object that is null.
• ArrayIndexOutOfBoundsException: This occurs when you try to access an
array element at an invalid index.
• ArithmeticException: This occurs during arithmetic operations, such as
division by zero.
COURSE CODE: BCECCE3103 25-08-2023=sameday UNIT 3
COURSE TITLE: OOPs WITH JAVA
LECTURE 17
Types of Exceptions
• IllegalArgumentException: This occurs when you pass an illegal or
inappropriate argument to a method.
• RuntimeException: This is a superclass for various unchecked exceptions,
indicating a wide range of potential issues.
Types of Exception Handling
 Try-Catch Block: The try-catch block is a fundamental construct for handling
exceptions. It allows you to enclose a block of code that might raise an exception
within a try block. If an exception occurs, it's caught by the corresponding catch
block, where you can specify how to handle the exception. The general syntax is:

COURSE CODE: BCECCE3103 26-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 17
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}}
 Multiple Catch Blocks: You can have multiple catch blocks after a single try block to
handle different types of exceptions. Java will execute the code in the block that
matches the caught exception type. The order of catch blocks matters, as the first
matching block will be executed.

COURSE CODE: BCECCE3103 26-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 17
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int value = numbers[4]; // This will cause an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
}
catch (Exception e) {
System.out.println("Generic exception");
}
}}

COURSE CODE: BCECCE3103 26-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 17
 Finally Block: The finally block is used after a try-catch block and is optional. The
code within the finally block is always executed, regardless of whether an
exception was thrown or not. It's often used for cleanup operations that need to be
performed regardless of the exception outcome.:

public class FinallyExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}}

COURSE CODE: BCECCE3103 26-08-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
NESTED TRY STATEMENTS
 In Java, a "try" statement is used to enclose a block of code that may throw
exceptions, and it is typically followed by one or more "catch" blocks to handle
those exceptions.
 In some situations, you may encounter the need for nested try statements,
which means you have one "try" block inside another.
 This allows you to handle exceptions at different levels of granularity or to
perform different actions depending on where the exception occurs in your
code.
Here's how nested try statements work:

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
NESTED TRY STATEMENTS
 The outer "try" block contains code that might throw exceptions. If an exception
occurs inside the outer "try" block, the program will look for an appropriate catch
block to handle it. If it doesn't find a matching catch block within the outer "try"
block, it will propagate to the next outer scope (if there's one) and continue
searching.
 If there's an inner "try" block within the outer "try" block, any exceptions
thrown inside the inner "try" block will be first caught by the inner catch blocks
(if any) that match the exception type. If no matching catch block is found in
the inner "try" block, the exception will propagate to the outer "try" block's
catch blocks.

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
NESTED TRY STATEMENTS
 If an exception propagates from an inner "try" block to an outer "try" block and the
outer catch block can handle it, the outer catch block will be executed. If there is
no matching catch block in the outer "try" block, the exception will propagate
further up the call stack.

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
NESTED TRY STATEMENTS
try { // Outer try block
int[] numbers = {1, 2, 3};
try { // Inner try block
System.out.println(numbers[5]); // This will throw an
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Inner catch: " + e.getMessage()); // Handle the exception
}} catch (Exception e) {
System.out.println("Outer catch: " + e.getMessage()); // This catch block will not be
executed for the specific exception
}

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
NESTED TRY STATEMENTS
 Imagine you have a special box called a "try" block, and inside that box, you
put some instructions that might go wrong and make your program crash.
Now, you also have another box, a smaller one inside the first box, and that's
your "nested try" block.
 Little Boxes for Small Problems: Sometimes, you have small problems in your
instructions, like trying to read a book that's too big for you. The small box inside
the big box helps you with these small problems without making everything stop.
 Big Box for Big Problems: But if you have a really big problem, like you can't find
the book at all, the big box outside catches that problem. It's there to help with the
really big stuff.

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
THROWS
 The throws keyword is used in method declarations to indicate that a particular
method might throw one or more types of exceptions during its execution. This
keyword is a way to declare which exceptions can potentially be thrown by a
method so that callers of the method are aware of the exceptions they need to
handle or propagate.
returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ... {
// Method code that may throw exceptions of the specified types
}
 The throws keyword is used for declaration, not for handling exceptions. It doesn't
handle the exceptions; instead, it declares that the method may throw exceptions
of the specified types.

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
User Defined Exceptions
 In Java, you can define your own custom exceptions to handle situations specific to
your application or domain.
 This allows you to create exception classes tailored to your needs, making your
code more organized and understandable.
 To define your own custom exception in Java, you create a new class that extends
either the built-in Exception class or one of its subclasses (e.g., RuntimeException)
 In your code, when you encounter a situation that requires raising your custom
exception, you use the throw keyword to throw it. For instance, suppose you have
a method that checks if a number is negative and throws MyCustomException

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
User Defined Exceptions
 To handle your custom exception, you use try-catch blocks just like you would for
any built-in exception. In your application code, you catch and handle the custom
exception where it's expected

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
User Defined Exceptions
public class CustomExceptionExample {
public static void main(String[] args) {
try {
checkNumber(-5); // This will throw MyCustomException
} catch (MyCustomException e) {
System.out.println("Custom exception caught: " + e.getMessage());
}}
public static void checkNumber(int number) throws MyCustomException {
if (number < 0) {
throw new MyCustomException("Number cannot be negative.");
}

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3


COURSE TITLE: OOPs WITH JAVA
LECTURE 18
User Defined Exceptions
}
}
class MyCustomException extends Exception {
public MyCustomException() {
super("This is a custom exception.");
}
public MyCustomException(String message) {
super(message);
}
}

COURSE CODE: BCECCE3103 04-09-2023=sameday UNIT 3

You might also like