Java Day 7
What is a Java Package? 📦
In Java, a package is a mechanism for organizing related classes and interfaces into a single group, much like using a folder to organize files in Windows. By grouping classes this way, you can manage your code more effectively.
The package keyword is used to declare a package, and it must be the very first statement in your Java source file.
Example:
Get Aman Verma’s stories in your inbox
Join Medium for free to get updates from this writer.
Java
package sum;public class Addition {
// Class content goes here
}## Advantages of Using Packages
Organizing your Java classes into packages provides two main benefits:
- Fast Searching: It becomes easier and faster to locate the classes you need because they are logically grouped. For example, all database-related classes might be in a
databasepackage. - Name Reusability: Packages prevent naming conflicts. You can have two classes with the same name, as long as they are in different packages. For instance, you could have a
com.example.Dateclass and also use the built-injava.util.Dateclass in the same project without any issues.
## Types of Packages
There are two main types of packages in Java:
1. Predefined (Built-in) Packages
These are packages that are part of the Java API, created by the developers of Java. They provide a rich library of pre-written classes to perform common tasks.
- Examples:
java.lang: Contains fundamental classes likeStringandSystem. It's automatically imported into every Java program.java.util: Provides utility classes likeScanner,ArrayList, andDate.java.io: Includes classes for input and output operations.java.sql: Used for database connectivity (JDBC).java.net: Provides classes for network programming.
2. User-defined (Custom) Packages
These are packages created by you, the programmer, to organize your own project’s classes.
- Examples:
basiccom.tcs.online_shopping
## Compiling a Class with a Package
When you have a .java file that includes a package statement, you need to use a specific command to compile it correctly so that the folder structure is created.
- Command:
javac -d . FileName.java javac: The Java compiler.-d: An option that specifies the destination directory for the generated.classfiles..: Represents the current directory. This tells the compiler to create the package folder structure within the current directory.
Example: If you have a file named Addition.java with the statement package sum; at the top, you would compile it using:
Bash
javac -d . Addition.javaThis command will compile the Addition.java file and then automatically create a folder named sum. Finally, it will place the compiled Addition.class file inside the sum folder.









