Packages in Java

What is a Package?

A package in Java is a namespace that groups related classes and interfaces together. Think of it like a folder in your computer — it helps organize your files (classes) and avoid name conflicts.

Why Use Packages?

Feature Description
Namespace Control Avoids name clashes between classes from different packages.
Code Organization Helps organize large projects logically (like utils, models, controllers).
Access Protection Supports access modifiers (e.g., protected, package-private).
Reusability Classes can be reused across projects via imports.

Types of Packages

Type Description Example
Built-in Provided by Java (JDK) java.util, java.io
User-defined Created by developers for custom use package myapp.utils;

Syntax of Defining a Package

At the top of the .java file:

package myproject; // define package name

public class Hello {
    public void greet() {
        System.out.println("Hello from ShikshaSanchar!");
    }
}

How to Use a Class from a Package

You need to import it before using:

import myproject.Hello;

public class Main {
    public static void main(String[] args) {
        Hello h = new Hello();
        h.greet();
    }
}

Example: Creating and Using a Package

File: myapp/Student.java

package myapp;

public class Student {
    public void show() {
        System.out.println("Student class inside 'myapp' package");
    }
}

File: Test.java (outside the package)

import myapp.Student;

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

Output:

Student class inside 'myapp' package

Folder Structure:

Project Root/
│
├── myapp/
│   └── Student.java
│
└── Test.java

Compile with:

javac myapp/Student.java
javac -cp . Test.java
java Test

Summary

Feature Explanation
Definition Container for related classes/interfaces
Syntax package packagename; at the top of file
Usage import packagename.ClassName;
Types Built-in (java.util), User-defined
Benefits Organization, name conflict resolution, access control

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar