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

Packages in Java Unit - 5

A package in Java is a collection of related classes and interfaces that enhances code organization and modularity. There are built-in packages provided by the Java API and user-defined packages created by programmers. Benefits of using packages include code reusability, better organization, and easier maintenance.

Uploaded by

Daksh Rathi
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)
0 views

Packages in Java Unit - 5

A package in Java is a collection of related classes and interfaces that enhances code organization and modularity. There are built-in packages provided by the Java API and user-defined packages created by programmers. Benefits of using packages include code reusability, better organization, and easier maintenance.

Uploaded by

Daksh Rathi
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/ 3

1.

Definition

A package in Java is a collection of related classes, interfaces, and sub-packages. It is used


to group similar types of classes under a single name to improve code organization and
modularity.

2. Types of Packages

Type Description

Built-in Package Provided by the Java API.

User-defined Package Created by the programmer to organize their own classes.

3. Common Built-in Packages

Package Name Purpose

java.lang Core classes (String, Math, Object) – imported by default

java.util Utility classes (ArrayList, HashMap, Date, Scanner)

java.io Input and Output classes (File, InputStream, OutputStream)

java.net Networking classes (Socket, URL)

java.sql Database access (Connection, Statement, ResultSet)

4. Creating a User-defined Package

Folder Structure:

MyPackage/

└── Hello.java

Main.java

File: Hello.java
package MyPackage;

public class Hello {

public void greet() {

System.out.println("Hello from MyPackage!");

File: Main.java

import MyPackage.Hello;

public class Main {

public static void main(String[] args) {

Hello obj = new Hello();

obj.greet();

5. Compilation & Execution

Compile:

javac MyPackage/Hello.java

javac Main.java

Run:

java Main

Output:

Hello from MyPackage!

8. Sub-packages

A package inside another package.


Example:

package college.cs;

To compile:

javac college/cs/Example.java

To run:

java college.cs.Example

9. Real-life Analogy

Think of a package like a folder on your computer.

 Each folder contains related files (classes).

 Helps in keeping things organized.

 You can have subfolders (sub-packages).

10. Benefits of Packages

a. Code Reusability
b. Better Organization
c. Avoids Naming Conflicts
d. Access Control
e. Makes Maintenance Easier

You might also like