[go: up one dir, main page]

0% found this document useful (0 votes)
18 views12 pages

Unit 3 Notes

The document provides an overview of Java packages, interfaces, and exception handling. It explains how to define packages, manage classpath, and use access modifiers, along with the differences between interfaces and abstract classes. Additionally, it covers exception types, handling mechanisms, and the creation of custom exceptions in Java.

Uploaded by

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

Unit 3 Notes

The document provides an overview of Java packages, interfaces, and exception handling. It explains how to define packages, manage classpath, and use access modifiers, along with the differences between interfaces and abstract classes. Additionally, it covers exception types, handling mechanisms, and the creation of custom exceptions in Java.

Uploaded by

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

PACKAGES IN JAVA

A Java package is a group of similar types of classes, interfaces and sub-packages.

Packages in java can be categorized in two forms, built-in packages and user-defined packages.

1. Defining a Package

In Java, a package is a namespace that groups related classes and interfaces. By defining a
package, you can avoid class name conflicts and organize your code better.

To define a package, use the package keyword at the top of your Java source file:

// Defining a package called "com.example.utility"


package com.example.utility;

public class UtilityClass {


public void performAction() {
System.out.println("Action performed!");
}
}

 Key Points:
o The package statement must be the first line in your Java file (excluding
comments).
o The directory structure must match the package name, so in the above example,
the file UtilityClass.java should be inside a directory com/example/utility/.

2. CLASSPATH

The CLASSPATH is an environment variable that tells the Java Virtual Machine (JVM) and
Java compiler where to look for classes and libraries during execution and compilation.

 When you compile or run Java programs, the JVM needs to know where to find the
classes or packages that are being referenced. The CLASSPATH points to the directories
or JAR files containing the class files.

You can set the CLASSPATH using the -cp or -classpath option in the command line:

javac -cp /path/to/classes MyProgram.java


java -cp /path/to/classes MyProgram

Alternatively, you can set the CLASSPATH in your environment variables for global use.

 Example: If you have a folder C:\JavaClasses containing your .class files, you can set your
CLASSPATH as:

set CLASSPATH=C:\JavaClasses
3. Package Naming

Package names help to logically group related classes and avoid naming conflicts. It's a
convention to use reverse domain names (like com.example) for package naming.

 Rules for naming packages:


o Package names are usually written in lowercase.
o The name should be a unique identifier (typically reflecting your website's
domain).
o If the domain is example.com, the package name could be com.example.myapp.

Example:

package com.example.myapp;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass in com.example.myapp package");
}
}

In the above example:

o The package name is com.example.myapp.


o The Java class MyClass is inside that package.

4. Accessibility of Packages

Java provides different access modifiers that control the accessibility of classes, methods, and
variables in a package. These modifiers allow you to define the visibility of package members.

 Public (public):
o Classes, methods, and variables that are public can be accessed from any other
class in any package.

public class MyClass {


public void display() {
System.out.println("This is a public method.");
}
}

 Private (private):
o private members are accessible only within the class they are declared.
o Note: private can only be applied to fields, methods, and inner classes, not to top-
level classes.

class MyClass {
private int number;
private void setNumber(int number) {
this.number = number;
}
}

 Protected (protected):
o Members marked as protected are accessible within the same package or by
subclasses (even if they're in a different package).

public class MyClass {


protected void display() {
System.out.println("This is a protected method.");
}
}

 Default (Package-Private):
o If no access modifier is specified, the default access level applies. This means the
member is accessible only within the same package.

class MyClass {
void display() {
System.out.println("This is a default (package-private) method.");
}
}

5. Using Package Members

To use the members (classes, methods, variables) of a package in another package, you need to
import them.

 Importing a single class: To access a specific class in a package, you can import it:

import com.example.utility.UtilityClass;

public class Main {


public static void main(String[] args) {
UtilityClass obj = new UtilityClass();
obj.performAction();
}
}

 Importing all classes from a package: You can import all classes from a package using
the * wildcard:

import com.example.utility.*;

public class Main {

public static void main(String[] args) {


UtilityClass obj = new UtilityClass();

obj.performAction();

Note: Using the wildcard import * is generally not recommended for large projects, as it
can cause unnecessary imports and make the code harder to maintain.

Example of Package Usage

Let’s combine everything:

1. Package definition in a file com/example/utility/UtilityClass.java:

// File: UtilityClass.java
package com.example.utility;

public class UtilityClass {


public void performAction() {
System.out.println("Action performed!");
}
}

2. Package usage in a different file Main.java:

// File: Main.java
import com.example.utility.UtilityClass;

public class Main {


public static void main(String[] args) {
UtilityClass obj = new UtilityClass();
obj.performAction();
}
}
INTERFACES

1. Implementing Interfaces

An interface in Java is a reference type, similar to a class, but it can contain only abstract methods
(methods without a body) and constants (fields that are public, static, and final by default). A class that
implements an interface must provide concrete implementations of all the interface's abstract methods.

Defining an Interface

To define an interface, use the interface keyword.


interface Animal {
void sound(); // abstract method
void eat(); // abstract method
}

Implementing an Interface

A class implements an interface using the implements keyword. The class must provide implementations
for all the abstract methods defined in the interface.

class Dog implements Animal {


@Override
public void sound() {
System.out.println("Bark");
}

@Override
public void eat() {
System.out.println("Dog is eating.");
}
}

Using the Interface and Implementing Class


public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.sound(); // Output: Bark
dog.eat(); // Output: Dog is eating.
}
}

2. Interface and Abstract Classes

Both interfaces and abstract classes allow you to define methods that must be implemented by concrete
classes. However, there are key differences between the two:

Key Differences Between Interface and Abstract Class:

1. Methods:
o Interface: Can only have abstract methods (before Java 8). From Java 8 onwards,
interfaces can also have default methods (with implementation) and static methods.
o Abstract Class: Can have both abstract methods (without body) and concrete methods
(with implementation).
2. Variables:
o Interface: All fields are public, static, and final by default (i.e., constants).
o Abstract Class: Can have instance variables (non-final), and fields with any access
modifier.
3. Inheritance:
o Interface: A class can implement multiple interfaces.
o Abstract Class: A class can extend only one abstract class.
Example of Abstract Class and Interface:

 Abstract Class:

abstract class Animal {


abstract void sound(); // abstract method

void eat() { // concrete method


System.out.println("Eating...");
}
}

 Interface:

interface AnimalActions {
void sound(); // abstract method
void sleep(); // abstract method
}

 Concrete Class Implementing Both:

class Dog extends Animal implements AnimalActions {


@Override
public void sound() {
System.out.println("Bark");
}

@Override
public void sleep() {
System.out.println("Sleeping...");
}
}

In this example:

 The Dog class extends the abstract class Animal (which provides the concrete eat() method).
 The Dog class also implements the interface AnimalActions (which forces the class to implement
both sound() and sleep()).

Usage:
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Bark
dog.eat(); // Output: Eating...
dog.sleep(); // Output: Sleeping...
}
}

3. Extends and Implements Together


In Java, a class can extend only one class (whether abstract or concrete) but can implement multiple
interfaces. This allows a class to inherit behavior from a superclass and also provide concrete
implementations for multiple interfaces.

 extends is used when a class is inheriting from another class (either abstract or concrete).
 implements is used when a class is adopting the contract defined by an interface.

Example: Combining extends and implements

Let’s create an example where a class extends an abstract class and implements multiple interfaces.

interface Animal {
void sound();
}

interface Domestic {
void breed();
}

abstract class Mammal {


abstract void sleep();

void feed() {
System.out.println("Feeding...");
}
}

class Dog extends Mammal implements Animal, Domestic {


@Override
public void sound() {
System.out.println("Bark");
}

@Override
public void breed() {
System.out.println("Breeding...");
}

@Override
void sleep() {
System.out.println("Dog is sleeping...");
}
}

In this example:

 The Dog class extends the Mammal class (so it inherits the feed() method and must implement
the abstract sleep() method).
 The Dog class implements both the Animal and Domestic interfaces, which require it to
implement the methods sound() and breed().
Usage:
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Bark
dog.breed(); // Output: Breeding...
dog.sleep(); // Output: Dog is sleeping...
dog.feed(); // Output: Feeding...
}
}

EXCEPTIONS HANDLING

Exception handling in Java allows developers to manage runtime errors effectively by using
mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception
handling, etc.
An Exception is an unwanted or unexpected event that occurs during the execution of a
program (i.e., at runtime) and disrupts the normal flow of the program’s instructions. It occurs
when something unexpected things happen, like accessing an invalid index, dividing by zero,
or trying to open a file that does not exist.

1. Exception

An exception in Java is an event that disrupts the normal flow of the program. When an exception occurs,
Java creates an exception object that contains information about the error. Exceptions are derived from
the Throwable class.

There are two main types of exceptions in Java:

1. Checked Exceptions: These exceptions are checked at compile-time. They are generally
recoverable, and the compiler forces you to handle them using try-catch or declare them using
throws.
o Examples: IOException, SQLException.
2. Unchecked Exceptions: These exceptions are not checked at compile-time. They are usually a
result of programming errors and can be avoided.
o Examples: NullPointerException, ArrayIndexOutOfBoundsException.

2. Handling Exceptions

Java uses try-catch blocks to handle exceptions. Here's how it works:

 try block: Contains the code that might throw an exception.


 catch block: Catches and handles the exception if it occurs.

Example:
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}

 In the example above, dividing by zero throws an ArithmeticException. The catch block handles the
exception by printing a message.

3. Using try-catch

A try-catch block is used to handle exceptions. The code inside the try block will execute normally until an
exception is thrown. If an exception occurs, the catch block will catch and handle it.

Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handling exception
}

 Example:

public class Main {


public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 25; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index is out of bounds!");
}
}
}

4. Catching Multiple Exceptions

From Java 7 onwards, you can catch multiple exceptions in a single catch block using the | (OR) operator.
This simplifies the code when multiple exceptions need the same handling logic.

Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType1 | ExceptionType2 e) {
// Handling both exceptions
}

Example:
public class Main {
public static void main(String[] args) {
try {
String str = null;
int length = str.length(); // This will throw NullPointerException
} catch (NullPointerException | ArithmeticException e) {
System.out.println("Caught either NullPointerException or ArithmeticException");
}
}
}

5. Using the finally Clause

The finally block is used to execute code that must run regardless of whether an exception was thrown or
not. It’s typically used to clean up resources, like closing files or database connections.

Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handling exception
} finally {
// Code that will always run
}

 The finally block is always executed after the try block, whether an exception was thrown or not.

Example:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This will always be executed.");
}
}
}

Output:

Cannot divide by zero.


This will always be executed.

6. Types of Exceptions

Java exceptions are divided into two main categories:

1. Checked Exceptions: These are exceptions that must be either caught or declared in the method
signature using throws.
o Examples: IOException, SQLException, ClassNotFoundException.
2. Unchecked Exceptions (Runtime Exceptions): These exceptions are not checked at compile
time and are usually a result of programming errors.
o Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
3. Error: These are serious problems that typically cannot be handled by the program (e.g.,
OutOfMemoryError, StackOverflowError).

7. Throwing Exceptions

You can throw exceptions explicitly using the throw keyword. When you throw an exception, you create
an exception object and pass it to the throw statement.

Syntax:
throw new ExceptionType("Exception message");

Example:
public class Main {
public static void main(String[] args) {
try {
throw new ArithmeticException("Custom exception: Cannot divide by zero");
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}

Output:

Custom exception: Cannot divide by zero

 In this example, we explicitly throw an ArithmeticException.

8. Writing Exception Subclasses

You can create your own custom exceptions by extending the Exception class (for checked exceptions) or
RuntimeException (for unchecked exceptions). This allows you to define custom behavior and messages
for exceptions.

Syntax:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

Example:
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class Main {


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
}

public static void main(String[] args) {


try {
validateAge(15); // This will throw InvalidAgeException
} catch (InvalidAgeException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

Output:

Exception: Age must be 18 or older.

 Here, we defined a custom exception InvalidAgeException and used it in a method that throws the
exception when the age is invalid.

You might also like