Unit 3 Notes
Unit 3 Notes
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:
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:
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.
Example:
package com.example.myapp;
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.
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).
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.");
}
}
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;
Importing all classes from a package: You can import all classes from a package using
the * wildcard:
import com.example.utility.*;
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.
// File: UtilityClass.java
package com.example.utility;
// File: Main.java
import com.example.utility.UtilityClass;
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
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.
@Override
public void eat() {
System.out.println("Dog is eating.");
}
}
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:
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:
Interface:
interface AnimalActions {
void sound(); // abstract method
void sleep(); // abstract method
}
@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...
}
}
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.
Let’s create an example where a class extends an abstract class and implements multiple interfaces.
interface Animal {
void sound();
}
interface Domestic {
void breed();
}
void feed() {
System.out.println("Feeding...");
}
}
@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.
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
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:
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");
}
}
}
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:
6. Types of Exceptions
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:
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);
}
}
Output:
Here, we defined a custom exception InvalidAgeException and used it in a method that throws the
exception when the age is invalid.