Packages in Java
Packages in Java: Beginner Guide (With Examples)
✨ Quick Summary
In this post, you’ll learn what Packages are in Java and why they are used. We will cover built-in packages, user-defined packages, import statement, and simple examples to help you understand clearly.
In our previous post, we learned about Interfaces in Java. Now, let’s learn a very important topic used in every Java project: Packages.
1) What is a Package in Java?
A package in Java is used to group related classes and interfaces.
Think of a package like a folder on your computer. Inside that folder, you store similar files together.
2) Why Do We Use Packages?
Packages are used because they help in:
- ✅ Organizing code properly
- ✅ Avoiding class name conflicts
- ✅ Reusing classes easily
- ✅ Making large projects manageable
3) Types of Packages in Java
Java has two types of packages:
- Built-in Packages (provided by Java)
- User-defined Packages (created by programmer)
4) Built-in Packages Examples
5) What is import in Java?
The import keyword is used to bring classes from a package into your program.
import java.util.Scanner;
This line imports the Scanner class from the java.util package.
6) Example Program Using import
import java.util.Scanner;
public class ImportExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello " + name);
sc.close();
}
}
7) User-Defined Package Example
You can also create your own package using the keyword package.
package mypackage;
public class Demo {
public void show() {
System.out.println("Hello from mypackage!");
}
}
Java will store this class inside a folder named mypackage.
Conclusion
Packages are used in every Java project to keep code clean, organized, and reusable. Once you understand packages, you will easily understand large Java projects and frameworks.
🔥 Next Post: Java Access Modifiers (public, private, protected, default)
You’re on the right track now.
ReplyDelete