0% found this document useful (0 votes)
2 views20 pages

Unit 4 Java

The document provides an overview of Java packages, explaining their purpose, types (built-in and user-defined), and how to create and use them. It also covers exception handling in Java, detailing the mechanism for managing runtime errors, the types of exceptions, and the keywords used in exception handling. Key concepts include the structure of packages, the advantages they offer, and the flow of exception handling.
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)
2 views20 pages

Unit 4 Java

The document provides an overview of Java packages, explaining their purpose, types (built-in and user-defined), and how to create and use them. It also covers exception handling in Java, detailing the mechanism for managing runtime errors, the types of exceptions, and the keywords used in exception handling. Key concepts include the structure of packages, the advantages they offer, and the flow of exception handling.
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

Notes on Java Packages

1. Introduction to Packages
A Package in Java is a collection of related classes, interfaces, enums, and sub-packages. Packages are
used to organize Java programs in a structured manner.
Just like folders organize files in a computer, packages organize Java classes.
Definition
A package is a namespace that groups related classes and interfaces together to avoid naming
conflicts and improve code organization.

Why do we use Packages?


Packages provide several advantages:
 Avoid class name conflicts.
 Organize large applications.
 Improve code readability.
 Provide access protection.
 Make code reusable.
 Easy maintenance of programs.

Types of Packages
Java provides two types of packages:
1. Built-in (System) Packages
2. User-defined Packages
Packages
|
-----------------------------
| |
Built-in Packages User-defined Packages

2. Basics of Packages
A package is declared using the package keyword.
Syntax
package packageName;
Example
package student;
This statement should always be the first statement in the Java program.

Importing Packages
To use another package, Java uses the import keyword.
Syntax
import [Link];
or
import packageName.*;
Example
import [Link];
or
import [Link].*;
Package Naming Rules
 Package names should be in lowercase.
 Reverse internet domain naming is preferred.
Example
[Link]
[Link]
[Link]

3. System Packages (Built-in Packages)


Java provides many predefined packages.
Some commonly used packages are:
Package Purpose
[Link] Fundamental classes
[Link] Utility classes
[Link] Input/Output
[Link] Networking
[Link] Database Connectivity
[Link] GUI Programming
[Link] Swing GUI
[Link] Date and Time

3.1 [Link] Package


This package is automatically imported.
Contains classes like
 String
 System
 Math
 Object
 Integer
Example
public class Demo
{
public static void main(String args[])
{
[Link]("Hello Java");

int x = [Link](20,40);

[Link](x);
}
}
Output
Hello Java
40

3.2 [Link] Package


Contains
 Scanner
 ArrayList
 Vector
 Random
 Date
Example
import [Link];
class Demo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);

[Link]("Enter Name : ");

String name=[Link]();

[Link]("Welcome "+name);
}
}
Output
Enter Name : Rahul
Welcome Rahul

3.3 [Link] Package


Used for file handling.
Example
import [Link].*;

class Demo
{
public static void main(String args[])
{
[Link]("Input Output Package");
}
}

3.4 [Link] Package


Used for networking.
Classes
 URL
 Socket
 ServerSocket

3.5 [Link] Package


Used for database connectivity.
Classes
 Connection
 Statement
 ResultSet

4. Creating Packages
Suppose we create a package called college.
Step 1
Create a Java file.
package college;

public class Student


{
public void display()
{
[Link]("Student Package");
}
}
Save as
[Link]

Step 2
Compile
javac -d . [Link]
The compiler creates
college
[Link]

Accessing the Package


Create another program.

import [Link];

class Test
{
public static void main(String args[])
{
Student s=new Student();

[Link]();
}
}
Compile
javac [Link]
Run
java Test
Output
Student Package

5. Creating User Defined Packages


User-defined packages are packages created by programmers.
Suppose we create package
employee
[Link]
package employee;

public class Employee


{
public void show()
{
[Link]("Employee Package");
}
}
Compile
javac -d . [Link]

Main Program
import [Link];

class Company
{
public static void main(String args[])
{
Employee e=new Employee();

[Link]();
}
}
Output
Employee Package

Example 2
Create package
calculator
[Link]
package calculator;

public class Calculator


{
public int add(int a,int b)
{
return a+b;
}
}
Compile
javac -d . [Link]
[Link]
import [Link];
class Main
{
public static void main(String args[])
{
Calculator c=new Calculator();

int sum=[Link](10,20);

[Link]("Addition = "+sum);
}
}
Output
Addition = 30

6. Adding Classes to Packages


One package can contain multiple classes.
Example
college
[Link]
[Link]
[Link]

[Link]
package college;

public class Student


{
public void display()
{
[Link]("Student Class");
}
}

[Link]
package college;

public class Teacher


{
public void display()
{
[Link]("Teacher Class");
}
}

[Link]
package college;

public class Principal


{
public void display()
{
[Link]("Principal Class");
}
}
Compile
javac -d . [Link] [Link] [Link]

Main Program
import college.*;

class Test
{
public static void main(String args[])
{
Student s=new Student();
Teacher t=new Teacher();
Principal p=new Principal();

[Link]();
[Link]();
[Link]();
}
}
Output
Student Class
Teacher Class
Principal Class

Package Hierarchy
Java supports sub-packages.
Example
college
|
department
|
physics
Program
package [Link];

public class Lab


{
public void show()
{
[Link]("Physics Lab");
}
}
Import
import [Link];

Access Modifiers in Packages


Modifier Same Class Same Package Subclass Other Package
private ✔ ✘ ✘ ✘
default ✔ ✔ ✘ ✘
protected ✔ ✔ ✔ ✔*
public ✔ ✔ ✔ ✔

Import Statement Examples


Import single class
import [Link];
Import all classes
import [Link].*;
Import user package
import [Link];
Import all classes
import college.*;

Package Compilation Commands


Compile package
javac -d . [Link]
Compile another class
javac [Link]
Run
java Test

Complete Folder Structure


Project

|
|--college
| [Link]
| [Link]
|
|--[Link]
|--[Link]
|--[Link]

Advantages of Packages
 Avoids duplicate class names.
 Better organization of programs.
 Easy maintenance.
 Improves security using access modifiers.
 Encourages code reuse.
 Simplifies project management.
 Supports modular programming.

Difference Between Built-in and User-defined Packages


Built-in Package User-defined Package
Provided by Java Created by programmer
Already available Must be created manually
Examples: [Link], [Link] Examples: college, employee
No need to create Need package statement

Frequently Used Built-in Packages


Package Important Classes
[Link] String, Math, System
[Link] Scanner, Vector, ArrayList, Random
[Link] File, FileReader, BufferedReader
[Link] URL, Socket
[Link] Connection, Statement
[Link] JFrame, JButton, JLabel
[Link] Frame, Button, TextField

Viva Questions
1. What is a package in Java?
2. Why are packages used?
3. What is the difference between built-in and user-defined packages?
4. What is the purpose of the package keyword?
5. What is the purpose of the import keyword?
6. Which package is automatically imported in every Java program?
7. How do you compile a package using javac?
8. What is the difference between import [Link]; and import package.*;?
9. Can a package contain multiple classes?
10. What are the advantages of packages in Java?

Summary
 A package groups related classes and interfaces into a single namespace.
 Java packages are of two types: System (built-in) and User-defined.
 The package keyword creates a package, while the import keyword makes its classes
available in another program.
 System packages such as [Link], [Link], [Link], and [Link] provide commonly used
functionality.
 User-defined packages improve modularity, code reuse, and maintenance.
 Multiple classes can be placed in a single package, and packages can also contain sub-
packages to organize large applications.

Exception Handling in Java


Introduction
Exception Handling is a mechanism in Java used to handle runtime errors so that the normal flow of
the program is not interrupted. An exception is an event that occurs during program execution that
disrupts the normal execution of instructions.
Without exception handling, a program terminates abruptly whenever an error occurs. Java provides
a robust exception handling mechanism through the use of try, catch, throw, throws, finally, nested
try blocks, multiple catch blocks, and user-defined exceptions.

What is an Exception?
An Exception is an unwanted or unexpected event that occurs during the execution of a program.
Examples
 Dividing a number by zero
 Accessing an invalid array index
 Opening a file that does not exist
 Entering invalid input
Example
public class ExceptionExample {
public static void main(String[] args) {

int a = 10;
int b = 0;

int c = a / b; // ArithmeticException

[Link](c);
}
}
Output
Exception in thread "main"
[Link]: / by zero

Types of Exceptions
Java exceptions are mainly divided into two categories.
1. Checked Exceptions
These are checked at compile time.
Examples:
 IOException
 SQLException
 ClassNotFoundException
Example:
import [Link].*;

public class CheckedException {


public static void main(String args[]) {

FileReader file = new FileReader("[Link]");

}
}
Compiler gives an error because the exception is not handled.

2. Unchecked Exceptions
These occur during runtime.
Examples
 ArithmeticException
 ArrayIndexOutOfBoundsException
 NullPointerException
 NumberFormatException
Example
public class UncheckedException {

public static void main(String args[]) {

int arr[] = {10,20,30};

[Link](arr[5]);

}
}
Output
ArrayIndexOutOfBoundsException

Exception Handling Keywords


Java provides five important keywords.
Keyword Purpose
try Defines a block where exceptions may occur
catch Handles the exception
throw Explicitly throws an exception
throws Declares exceptions in method declaration
finally Executes whether exception occurs or not

try Block
The try block contains code that may generate an exception.
Syntax
try
{
// risky code
}
Example
public class TryDemo {
public static void main(String args[]) {

try {

int x = 10 / 0;

}
This alone is invalid because try must be followed by catch or finally.

catch Block
The catch block handles the exception generated inside the try block.
Syntax
try
{
// code
}
catch(ExceptionType e)
{
// handling code
}
Example
public class CatchDemo {

public static void main(String args[]) {

try {

int x = 20 / 0;

catch(ArithmeticException e) {

[Link]("Cannot divide by zero.");

[Link]("Program Continues");

}
Output
Cannot divide by zero.
Program Continues

try-catch Example
public class TryCatchExample {

public static void main(String args[]) {

int marks[] = {50,60,70};

try {

[Link](marks[5]);

catch(ArrayIndexOutOfBoundsException e) {

[Link]("Invalid Array Index");

[Link]("End of Program");

}
Output
Invalid Array Index
End of Program

finally Block
The finally block always executes whether an exception occurs or not.
It is mainly used for
 Closing files
 Closing database connections
 Releasing resources
Syntax
try
{
}
catch(Exception e)
{
}
finally
{
}

Example
public class FinallyDemo {

public static void main(String args[]) {

try {
int a = 10 / 0;

catch(ArithmeticException e) {

[Link]("Exception Handled");

finally {

[Link]("Finally Block Executed");

}
Output
Exception Handled
Finally Block Executed

throw Keyword
The throw keyword is used to explicitly create and throw an exception.
Syntax
throw new ExceptionType("message");

Example
public class ThrowExample {

public static void main(String args[]) {

int age = 15;

if(age < 18) {

throw new ArithmeticException("Not Eligible for Voting");

[Link]("Eligible");

}
Output
Exception in thread "main"
[Link]:
Not Eligible for Voting
throws Keyword
The throws keyword is used in the method declaration to declare exceptions.
Syntax
returnType methodName() throws ExceptionType

Example
import [Link].*;

public class ThrowsExample {

static void readFile() throws IOException {

FileReader f = new FileReader("[Link]");

public static void main(String args[]) {

try {

readFile();

catch(IOException e) {

[Link]("File Not Found");

}
Output
File Not Found

Difference Between throw and throws


throw throws
Used inside a method Used with method declaration
Throws one exception at a time Can declare multiple exceptions
Used explicitly Used to declare responsibility

Multiple catch Statements


One try block can have multiple catch blocks.
Syntax
try
{
}
catch(Exception1 e)
{
}
catch(Exception2 e)
{
}
catch(Exception3 e)
{
}

Example
public class MultipleCatch {

public static void main(String args[]) {

try {

int a = 20 / 0;

int arr[] = {1,2};

[Link](arr[5]);

catch(ArithmeticException e) {

[Link]("Arithmetic Exception");

catch(ArrayIndexOutOfBoundsException e) {

[Link]("Array Index Exception");

catch(Exception e) {

[Link]("General Exception");

}
Output
Arithmetic Exception
Note: Always place the most specific catch blocks first and the general Exception catch block last.

Nested try Block


A nested try block means placing one try block inside another try block.
Example
public class NestedTry {
public static void main(String args[]) {

try {

[Link]("Outer Try");

try {

int a = 10 / 0;

catch(ArithmeticException e) {

[Link]("Inner Catch");

catch(Exception e) {

[Link]("Outer Catch");

}
Output
Outer Try
Inner Catch

User Defined Exception


Java allows programmers to create their own exception classes.
A custom exception is created by extending the Exception class.
Syntax
class MyException extends Exception
{
}

Example
class InvalidAgeException extends Exception {

InvalidAgeException(String msg) {

super(msg);

}
}

public class UserDefinedException {

static void checkAge(int age) throws InvalidAgeException {

if(age < 18) {

throw new InvalidAgeException("Age must be 18 or above.");

else {

[Link]("Eligible for Voting");

public static void main(String args[]) {

try {

checkAge(15);

catch(InvalidAgeException e) {

[Link]([Link]());

}
Output
Age must be 18 or above.

Flow of Exception Handling


Program Starts


Execute try block


Exception Occurs?
/ \
No Yes
│ │
▼ ▼
Continue Jump to catch
│ │
└──────┬──────┘

Execute finally block


Program Ends

Advantages of Exception Handling


 Prevents abnormal termination of programs.
 Separates error-handling code from normal code.
 Improves program readability and maintainability.
 Enables graceful recovery from runtime errors.
 Supports resource cleanup using the finally block.

Common Built-in Exceptions in Java


Exception Cause
ArithmeticException Divide by zero
NullPointerException Using a null reference
ArrayIndexOutOfBoundsException Invalid array index
NumberFormatException Invalid number conversion
ClassCastException Invalid object casting
IOException File input/output error
FileNotFoundException File does not exist

Viva/Exam Questions
1. What is exception handling in Java?
2. What is the difference between checked and unchecked exceptions?
3. Explain the purpose of the try, catch, throw, throws, and finally keywords.
4. What is the difference between throw and throws?
5. What is a nested try block? Give an example.
6. What are multiple catch statements? Why should specific exceptions be caught before
general ones?
7. How do you create a user-defined exception in Java?
8. What is the purpose of the finally block?
9. Name any four predefined exceptions in Java.
10. Why is exception handling important in Java programming?

Summary
 Exception handling manages runtime errors and prevents abrupt program termination.
 The try block contains code that may throw an exception.
 The catch block handles specific exceptions.
 The throw keyword explicitly throws an exception.
 The throws keyword declares exceptions that a method may propagate.
 The finally block always executes for resource cleanup.
 Multiple catch blocks handle different exception types in a single try.
 Nested try blocks allow exceptions to be handled at different levels.
 User-defined exceptions are created by extending the Exception class to represent
application-specific error conditions.

You might also like