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

Unit 4 Java-Sem

The java.lang package is a core part of Java, automatically imported in every program, containing essential classes for programming, including Object, String, Math, System, Thread, and exception handling classes. It provides foundational support for operations like mathematical calculations, multithreading, and exception management. File handling in Java, facilitated by the java.io package, allows for permanent data storage and manipulation through classes like File, FileReader, and FileWriter.

Uploaded by

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

Unit 4 Java-Sem

The java.lang package is a core part of Java, automatically imported in every program, containing essential classes for programming, including Object, String, Math, System, Thread, and exception handling classes. It provides foundational support for operations like mathematical calculations, multithreading, and exception management. File handling in Java, facilitated by the java.io package, allows for permanent data storage and manipulation through classes like File, FileReader, and FileWriter.

Uploaded by

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

Unit 4

Question 2: Summarize [Link] package and its


classes. (10 Marks)

Answer:

1. Introduction

The [Link] package is one of the most fundamental packages in Java.​


It is automatically imported into every Java program, so we don’t need to explicitly use import
[Link].*;.​
It contains classes that are essential for the Java programming language.

2. Importance of [Link] Package

●​ It provides classes that form the foundation for Java programming.​

●​ It includes wrapper classes for primitive data types.​

●​ It supports mathematical operations, multithreading, exception handling, and type


conversions.​

3. Commonly Used Classes in [Link] Package

(a) Object Class

●​ The root class of the Java class hierarchy.​

●​ Every class in Java directly or indirectly inherits from the Object class.​

●​ Important Methods:​

○​ equals() → Compares two objects.​


○​ toString() → Returns string representation of an object.​

○​ hashCode() → Returns hash code of object.​

○​ clone() → Creates copy of an object.​

(b) String Class

●​ Represents a sequence of characters.​

●​ Immutable (cannot be changed once created).​

Example:​

String s1 = "Hello";
String s2 = new String("World");
[Link](s1 + " " + s2);

●​

(c) Math Class

●​ Provides mathematical functions and constants.​

●​ Important Methods:​

○​ [Link](25) → 5.0​

○​ [Link](2,3) → 8.0​

○​ [Link](-10) → 10​

○​ [Link]() → Generates a random number between 0 and 1.​

(d) Wrapper Classes


●​ Used to convert primitive data types into objects.​

●​ Classes: Integer, Double, Float, Character, Boolean, etc.​

Example:​

int a = 10;
Integer obj = [Link](a);
[Link](obj);

●​

(e) System Class

●​ Provides access to system-level resources such as input/output and environment


properties.​

●​ Common Methods:​

○​ [Link]() → Display output.​

○​ [Link](0) → Terminates the program.​

○​ [Link]() → Returns current time in milliseconds.​

(f) Thread Class

●​ Used for multithreading — allows running multiple tasks simultaneously.​

Example:​

class Demo extends Thread {
public void run() {
[Link]("Thread is running...");
}
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
}
}

●​

(g) Exception and Throwable Classes

●​ Handle runtime errors gracefully.​

●​ Throwable is the superclass of all exceptions and errors.​

●​ Common subclasses: Exception, RuntimeException, Error.​

4. Summary Table
Class Description
Name

Object Superclass of all classes

String Immutable sequence of


characters

Math Mathematical operations

System System-level resources

Thread Multithreading support

Exception Exception handling

Runtime Runtime environment control

Process Process management

5. Conclusion
The [Link] package is automatically available and provides the essential classes that form
the core of Java programming.​
Without this package, no Java program can be executed efficiently, as it contains the
foundation classes used throughout the Java API.

Question 3: Describe the file concept in Java with a


suitable example. (10 Marks)

1. Introduction

In Java, file handling is performed using the [Link] package.​


Files are used to store data permanently on disk, and Java provides classes to create, read,
write, and manipulate files.

2. What is a File in Java?

A file is a named location on the disk where data is stored permanently.​


Java provides the File class (in [Link] package) to handle file-related operations.

3. Common File Operations in Java


Operation Description

Create a file Make a new file using File or FileWriter

Write to a file Store data using FileWriter or


BufferedWriter

Read from a file Retrieve data using FileReader or


BufferedReader

Delete a file Remove an existing file using delete() method

4. Important Classes Used in File Handling


Class Name Purpose
File Represents file or directory path

FileReader Reads data from file (character by


character)

FileWriter Writes data into file

BufferedRea Reads text efficiently using buffer


der

BufferedWri Writes text efficiently using buffer


ter

5. Example Program – File Creation, Writing, and Reading


import [Link].*;

class FileExample {
public static void main(String[] args) {
try {
// Creating a file
FileWriter fw = new FileWriter("[Link]");

// Writing data into file


[Link]("Welcome to Java File Handling!\n");
[Link]("This file is created using FileWriter.");
[Link]();
[Link]("File written successfully.");

// Reading data from file


FileReader fr = new FileReader("[Link]");
int i;
[Link]("File contents:");
while ((i = [Link]()) != -1) {
[Link]((char) i);
}
[Link]();
} catch (IOException e) {
[Link]("An error occurred: " + e);
}
}
}

6. Explanation of the Code

1.​ FileWriter – Creates and writes data into the file.​

2.​ [Link]() – Writes text content.​

3.​ [Link]() – Closes the file to save data.​

4.​ FileReader – Opens the file for reading.​

5.​ [Link]() – Reads characters one by one.​

6.​ try-catch block – Handles exceptions like file not found or I/O errors.​

7. Output
File written successfully.
File contents:
Welcome to Java File Handling!
This file is created using FileWriter.

8. Exception Handling

●​ File operations may cause exceptions such as:​

○​ FileNotFoundException​

○​ IOException​

●​ Always use try-catch blocks for safety.​


9. Advantages of File Handling in Java

●​ Permanent data storage​

●​ Easy to read/write large data​

●​ Supports both binary and character-based data​

●​ Useful for real-world applications (logs, records, etc.)​

10. Conclusion

File handling in Java is essential for developing applications that need persistent storage.​
Using classes like File, FileReader, and FileWriter, we can easily perform operations
like creating, reading, writing, and deleting files efficiently.

Question 4: Write a short note on try, catch, throw,


throws, and finally. (10 Marks)

1. Introduction

In Java, exception handling is a mechanism that allows programmers to handle runtime errors
gracefully without stopping the normal flow of execution.​

➡️ ➡️ ➡️ ➡️ ➡️
The key keywords used in exception handling are:​
try catch throw throws finally

All of these are part of the [Link] package.

2. Exception Handling Keywords

(a) try Block

●​ The try block contains a set of statements that may cause an exception.​
●​ It must be followed by either a catch or a finally block.​

Syntax:​

try {
// Code that may throw an exception
}

●​

(b) catch Block

●​ The catch block handles the exception thrown by the try block.​

●​ You can have multiple catch blocks to handle different types of exceptions.​

Syntax:​

catch (ExceptionType e) {
// Code to handle the exception
}

●​

(c) throw Keyword

●​ The throw keyword is used to explicitly throw an exception from a method or block of
code.​

●​ It is mainly used for custom or user-defined exceptions.​

Syntax:​

throw new ExceptionType("Error Message");

●​
(d) throws Keyword

●​ The throws keyword is used in method declarations to declare the exceptions that a
method might throw.​

●​ It informs the caller of the method about potential exceptions.​

Syntax:​

void myMethod() throws IOException {
// Code that may throw exception
}

●​

(e) finally Block

●​ The finally block is used to execute important code such as closing files, releasing
resources, or ending database connections.​

●​ It always executes whether an exception is handled or not.​

Syntax:​

finally {
// Code that executes always
}

●​

3. Example Program: Using try, catch, throw, throws, and finally


class ExceptionExample {

// Method that throws an exception


static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
[Link]("Eligible to vote");
}
}

public static void main(String[] args) {


try {
checkAge(15); // May throw exception
}
catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
}
finally {
[Link]("Execution completed. Thank you!");
}
}
}

4. Output
Exception caught: [Link]: Not eligible to vote
Execution completed. Thank you!

5. Explanation of Program

1.​ try → Contains risky code (checkAge(15)).​

2.​ throws → Declared in method to indicate it may throw ArithmeticException.​

3.​ throw → Actually throws the exception when age < 18.​

4.​ catch → Catches and handles the thrown exception.​

5.​ finally → Always executes (used for cleanup).​


6. Advantages of Exception Handling

●​ Prevents abnormal termination.​

●​ Makes code more readable and maintainable.​

●​ Allows graceful recovery from runtime errors.​

●​ Separates error-handling logic from normal code.​

7. Conclusion

The try, catch, throw, throws, and finally keywords together form the core of Java’s
exception handling mechanism.​
They ensure that runtime errors are handled in a structured, safe, and controlled way,
improving program reliability and stability.

Question 5: Develop a Java program using exception


handling with multiple catch clauses. (10 Marks)

1. Introduction

In Java, a multiple catch block is used when a single try block may throw more than one
type of exception.​
Each catch block handles a specific type of exception.

This makes programs more robust and error-resistant.

2. Syntax
try {
// Code that may cause multiple exceptions
}
catch (ArithmeticException e) {
// Handles arithmetic errors
}
catch (ArrayIndexOutOfBoundsException e) {
// Handles array index errors
}
catch (Exception e) {
// Handles all remaining exceptions
}

3. Example Program
class MultipleCatchExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // May cause ArithmeticException

int arr[] = new int[3];


arr[5] = 20; // May cause ArrayIndexOutOfBoundsException

String s = null;
[Link]([Link]()); // May cause
NullPointerException
}

// Catching multiple exceptions separately


catch (ArithmeticException e) {
[Link]("Arithmetic Exception: Division by zero
is not allowed.");
}

catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Out Of Bounds Exception:
Invalid array index.");
}

catch (NullPointerException e) {
[Link]("Null Pointer Exception: String is
null.");
}
catch (Exception e) {
[Link]("General Exception: " + e);
}

finally {
[Link]("Program execution completed.");
}
}
}

4. Output
Arithmetic Exception: Division by zero is not allowed.
Program execution completed.

5. Explanation of Program

1.​ try block – Contains risky code that might throw multiple exceptions.​

2.​ ArithmeticException – Caught if division by zero occurs.​

3.​ ArrayIndexOutOfBoundsException – Caught if invalid index is accessed.​

4.​ NullPointerException – Caught if null reference is accessed.​

5.​ Exception – Acts as a general handler for all other exceptions.​

6.​ finally block – Executes every time to perform cleanup operations.​

6. Key Points

●​ Only one catch block is executed per try.​

●​ Catch blocks should be ordered from specific → general.​


●​ The finally block executes whether exception occurs or not.​

●​ It’s good practice to keep a final generic catch(Exception e) block.​

7. Advantages of Multiple Catch

●​ Makes code cleaner and organized.​

●​ Provides specific handling for different error types.​

●​ Prevents the program from abrupt termination.​

●​ Improves readability and debugging.​

8. Conclusion

Multiple catch clauses in Java make exception handling more flexible and precise.​
By handling each exception type separately, programs become more reliable, user-friendly,
and maintainable.

Question 6: Discuss about file concept in Java. (10


Marks)

1. Introduction

File handling in Java is used to store and retrieve data permanently.​


Java provides the [Link] package that contains classes and methods for reading, writing,
and managing files efficiently.​
The File class in Java represents a file or directory path.

2. What is a File?

A file is a named location on the disk used to store data permanently.​


Java uses the File class (from [Link]) to handle operations such as:
●​ Creating a file​

●​ Checking if a file exists​

●​ Reading and writing data​

●​ Deleting files​

3. Common File Operations in Java


Operation Description

Create a File Using File or FileWriter

Write to File Using FileWriter or


BufferedWriter

Read from File Using FileReader or


BufferedReader

Delete File Using delete() method

Check Using exists() method


Existence

4. Important Classes in File Handling


Class Description

File Represents file or directory

FileReader Reads data from files

FileWriter Writes data to files

BufferedRea Reads text efficiently


der

BufferedWri Writes text efficiently


ter
5. Example Program: File Creation, Writing, and Reading
import [Link].*;

class FileConceptExample {
public static void main(String[] args) {
try {
// Step 1: Create a File
File file = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}

// Step 2: Write to File


FileWriter writer = new FileWriter("[Link]");
[Link]("Java file handling is powerful and
easy.\n");
[Link]("This file is created using FileWriter
class.");
[Link]();
[Link]("Successfully written to the file.");

// Step 3: Read from File


FileReader reader = new FileReader("[Link]");
int i;
[Link]("\nReading from the file:");
while ((i = [Link]()) != -1) {
[Link]((char) i);
}
[Link]();

// Step 4: Delete File Example (optional)


// [Link]();
}
catch (IOException e) {
[Link]("An error occurred: " +
[Link]());
}
}
}

6. Output
File created: [Link]
Successfully written to the file.

Reading from the file:


Java file handling is powerful and easy.
This file is created using FileWriter class.

7. Explanation of the Code

1.​ File Creation: createNewFile() creates a new file on disk.​

2.​ File Writing: FileWriter writes character data into the file.​

3.​ File Reading: FileReader reads data from the file character by character.​

4.​ Exception Handling: IOException is handled using a try-catch block.​

5.​ File Deletion (optional): [Link]() removes the file if needed.​

8. Exception Handling in File Operations

Common exceptions include:

●​ IOException – for general input/output errors​

●​ FileNotFoundException – if file doesn’t exist while reading​

Hence, always use a try-catch block for safety.


9. Advantages of File Handling

●​ Data is stored permanently (persistent storage).​

●​ Enables reading/writing large amounts of data.​

●​ Can handle both text and binary data.​

●​ Commonly used for logs, data records, and config files.​

10. Conclusion

The file concept in Java provides a powerful and flexible way to manage data storage and
retrieval.​
Using classes like File, FileWriter, and FileReader, Java enables efficient and safe file
handling for both small and large applications.

Question 7: Explain about package concept with suitable


example. (10 Marks)

1. Introduction

A package in Java is a collection of related classes and interfaces.​


It helps in organizing code, avoiding name conflicts, and providing access control.​
Packages are similar to folders in a computer that contain related files.

2. Definition

A package is a namespace that organizes a set of related classes and interfaces in


Java.

3. Types of Packages
Type Description Example

Built-in Packages Provided by Java itself [Link], [Link], [Link],


[Link]

User-defined Created by the e.g. mypackage, [Link]


Packages programmer

4. Advantages of Using Packages

1.​ Code Reusability: Classes in a package can be reused in other programs.​

2.​ Name Conflicts Avoided: Packages prevent class name clashes.​

3.​ Code Organization: Keeps related classes together.​

4.​ Access Protection: Provides access control using access modifiers.​

5.​ Ease of Maintenance: Makes project structure more readable.​

5. Syntax

To create a package:
package packageName;

To use a package:
import [Link];
// or
import packageName.*;

6. Example Program: User-defined Package

Step 1: Create a package

File name: mypack/[Link]


package mypack; // Creating a package named 'mypack'

public class Addition {


public void add(int a, int b) {
[Link]("Sum = " + (a + b));
}
}

Step 2: Use the package in another file

File name: [Link]

import [Link]; // Importing the package

class MainProgram {
public static void main(String[] args) {
Addition obj = new Addition();
[Link](10, 20);
}
}

7. Steps to Run the Program

1.​ Save the first file as [Link] inside a folder named mypack.​

Compile it using:​

javac -d . [Link]

2.​ (-d . creates the package folder automatically)​

3.​ Save the second file ([Link]) in the same directory.​

Compile and run:​



javac [Link]
java MainProgram

4.​

8. Output
Sum = 30

9. Explanation of the Program

●​ The package keyword defines a new package.​

●​ The import statement allows using classes from that package.​

●​ Class Addition belongs to the mypack package.​

●​ MainProgram imports and uses it.​

●​ Packages make large projects modular and easy to maintain.​

10. Conclusion

Packages in Java are a powerful feature for organizing and structuring code.​
They make programs modular, reusable, and easy to manage.​
Java provides many built-in packages, and developers can also create custom (user-defined)
packages for project-specific needs.

Question 8: Explain about Standard I/O Streams and


Types with Example. (10 Marks)

1. Introduction

In Java, I/O (Input and Output) Streams are used to read data from input devices (like
keyboard, files, network) and write data to output devices (like monitor, files, printers).
A stream is a sequence of data that flows from a source to a destination.

All stream-related classes are available in the [Link] package.

2. What is a Stream?

A stream is a flow of data between a Java program and an external source (like file, console, or
network).

●​ Input Stream → Used to read data.​

●​ Output Stream → Used to write data.​

3. Types of Standard I/O Streams in Java

Java defines three standard I/O streams that are automatically created when a Java program
starts:

Stream Class Purpose

System.i InputStre Standard input device


n am (keyboard)

System.o PrintStre Standard output device (screen)


ut am

System.e PrintStre Standard error device (screen)


rr am

4. Description of Each Stream

(a) [Link]

●​ It is used to read data from the keyboard.​

●​ Usually wrapped in Scanner or BufferedReader for easier input.​


Example:

import [Link];

class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name + "!");
}
}

Output:

Enter your name: Ram


Hello, Ram!

(b) [Link]

●​ Used to display normal output messages on the screen.​

●​ It is connected to the console.​

Example:

[Link]("Welcome to Java!");

(c) [Link]

●​ Used to display error messages or exceptions.​

●​ It also prints to the console but can be redirected separately if needed.​

Example:

[Link]("Error: Invalid Input!");


Output:

Error: Invalid Input!

(Printed in red or highlighted color in most IDEs)

5. Classification of Streams

Java streams are divided into two major categories:

Type Description Example Classes

Byte Streams Handles 8-bit binary data (used for FileInputStream,


images, videos, etc.) FileOutputStream

Character Handles 16-bit Unicode text data (used FileReader, FileWriter


Streams for text files)

6. Example Program Demonstrating Standard Streams


import [Link].*;

class StandardIOExample {
public static void main(String[] args) {
try {
// Reading from keyboard ([Link])
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter a number: ");
int num = [Link]([Link]());

// Writing output ([Link])


[Link]("Square of the number is: " + (num *
num));

// Displaying error message ([Link])


if (num < 0) {
[Link]("Error: Negative numbers are not
allowed!");
}
}
catch (IOException e) {
[Link]("Input Error: " + e);
}
}
}

7. Output Example
Enter a number: 5
Square of the number is: 25

If you enter a negative number:

Enter a number: -3
Square of the number is: 9
Error: Negative numbers are not allowed!

8. Advantages of Standard I/O Streams

●​ Easy to handle input and output.​

●​ Automatically available (no need to create objects).​

●​ Can be redirected to files or devices.​

●​ Supports both text and binary data.​

9. Conclusion

The Standard I/O Streams ([Link], [Link], [Link]) are the backbone of
Java’s I/O system.​
They allow Java programs to interact easily with users and the operating system, making input
and output operations flexible, consistent, and reliable.

Question 9: Discuss about Java Input and Output and File


with Example. (10 Marks)

1. Introduction

Java provides a powerful Input/Output (I/O) system through the [Link] package.​
It allows programs to read data from input sources (keyboard, files, network) and write data
to output destinations (console, files, printers).​
File handling is an important part of this system.

2. What is Input and Output (I/O)?

●​ Input: The process of reading data from an external source (like keyboard or file).​

●​ Output: The process of sending data to an external destination (like monitor or file).​

Java performs I/O through streams.

3. What is a Stream?

A stream is a sequence of data that flows between the Java program and the external
source/destination.

Stream Type Description

Input Stream Used to read data from a source

Output Stream Used to write data to a


destination

4. Types of I/O Streams

Java I/O is mainly classified into two types:


Type Used For Example Classes

Byte Streams Binary data (images, audio, FileInputStream,


etc.) FileOutputStream

Character Streams Text data (characters) FileReader, FileWriter

5. File Handling in Java

A file is a storage location used to store data permanently.​


Java provides the File class (from [Link]) to work with files — create, read, write, and
delete them.

Common File Operations:

Operation Class Used

Create File File

Write Data FileWriter,


BufferedWriter

Read Data FileReader,


BufferedReader

Delete File [Link]()

6. Example Program: File Creation, Writing, and Reading


import [Link].*;

class FileIOExample {
public static void main(String[] args) {
try {
// Step 1: Create a new file
File file = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}

// Step 2: Write data to the file


FileWriter fw = new FileWriter("[Link]");
[Link]("Welcome to Java Input and Output Handling.\n");
[Link]("This is an example of File I/O in Java.");
[Link]();
[Link]("Data written successfully.");

// Step 3: Read data from the file


FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String line;
[Link]("\nReading from file:");
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
}
catch (IOException e) {
[Link]("An error occurred: " +
[Link]());
}
}
}

7. Output
File created: [Link]
Data written successfully.

Reading from file:


Welcome to Java Input and Output Handling.
This is an example of File I/O in Java.

8. Explanation of the Code


1.​ File Creation:​
createNewFile() creates a new file on disk if it doesn’t exist.​

2.​ Writing Data:​


FileWriter writes character data into the file.​

3.​ Reading Data:​


FileReader reads character data, while BufferedReader reads it line by line.​

4.​ Exception Handling:​


The IOException is handled to prevent runtime errors.​

9. Advantages of Java I/O and File Handling

●​ Supports both text and binary data.​

●​ Provides buffered streams for efficient data transfer.​

●​ Allows data persistence (storing data permanently).​

●​ Ensures portability across operating systems.​

●​ Helps in reading/writing data for real-world applications (like logs, databases, etc.).​

10. Conclusion

Java’s Input and Output system along with file handling provides a simple yet powerful
mechanism for data management.​
Using streams and classes like File, FileWriter, and FileReader, developers can
create, read, write, and process files efficiently — making it a vital concept in Java
programming.

Question 10: Write a Java Program Using Package


Concept. (10 Marks)
1. Introduction

In Java, a package is used to group related classes and interfaces together.​


It helps in:

●​ Organizing code logically​

●​ Avoiding name conflicts​

●​ Reusing code easily​

There are two types of packages:

1.​ Built-in packages (e.g., [Link], [Link], [Link])​

2.​ User-defined packages (created by the programmer)​

2. Definition

A package is a namespace that organizes a set of related classes and interfaces,


similar to folders on your computer.

3. Syntax

To create a package:
package package_name;

To use a package:
import package_name.ClassName;
// or
import package_name.*;

4. Steps to Create and Use a User-defined Package

Step 1: Create a folder (for example, mypack).


Step 2: Inside it, create a class file and define a package.

Step 3: Compile the file with javac -d . [Link]

→ This command automatically creates the package structure.

Step 4: Create another program in the same directory to import and use the package.

5. Example Program

File 1: (Inside the package folder)

📄 mypack/[Link]
package mypack; // Declaring the package

public class Calculation {


public void add(int a, int b) {
[Link]("Addition = " + (a + b));
}

public void sub(int a, int b) {


[Link]("Subtraction = " + (a - b));
}
}

File 2: (Main program using the package)

📄 [Link]
import [Link]; // Importing the user-defined package

class MainProgram {
public static void main(String[] args) {
Calculation c = new Calculation();
[Link](10, 5);
[Link](10, 5);
}
}
6. Compilation Steps

1.​ Save the first file ([Link]) inside a folder named mypack.​

Open Command Prompt (or terminal) and compile:​



javac -d . [Link]

2.​ This creates a mypack directory automatically (if not already).​

Compile and run the main file:​



javac [Link]
java MainProgram

3.​

7. Output
Addition = 15
Subtraction = 5

8. Explanation of the Program

1.​ package mypack; → Creates a custom package named mypack.​

2.​ public class Calculation → Declares a public class inside the package.​

3.​ import [Link]; → Imports the user-defined package into the main
program.​

4.​ The object c is used to access methods from the imported class.​

5.​ The program performs addition and subtraction using the package-defined class.​
9. Advantages of Using Packages

●​ Code Reusability – Classes can be reused in other projects.​

●​ Avoids Naming Conflicts – Two classes can have the same name if they’re in different
packages.​

●​ Easy Maintenance – Related classes are stored together.​

●​ Access Control – Classes and methods can be made public or private.​

●​ Improved Modularity – Large projects are easier to organize.​

10. Conclusion

Packages in Java help to organize code, improve modularity, and promote reusability.​
By using the package and import keywords, developers can create structured and
maintainable programs, which is especially useful in large software projects.

You might also like