Java Packages - Detailed Notes
1. What is a package in Java?
A package in Java is a namespace that groups related classes and interfaces together. It helps
organize code and avoid naming conflicts.
package mypackage;
public class Hello {
public void display() {
[Link]("Hello from package");
}
}
2. Why are packages used in Java?
Packages help in code organization, avoiding naming conflicts, providing access control, and
enabling code reusability.
3. How do you create a package in Java?
package mypackage;
public class Test {
public static void main(String[] args) {
[Link]("Package created");
}
}
Compile using: javac -d . [Link]
4. Syntax to declare a package
package [Link];
5. Default package
If no package is declared, the class belongs to the default package.
6. Compile and run package program
javac -d . [Link]
java [Link]
7. Package vs Folder
Package is logical grouping, folder is physical storage.
8. Built-in packages
Examples: [Link], [Link], [Link], [Link]
import [Link];
ArrayList<Integer> list = new ArrayList<>();
9. Import keyword
Used to access classes from other packages.
import [Link];
10. Without package statement
Class goes to default package and cannot be imported elsewhere.
Complete Example
package mypack;
public class Add {
public int sum(int a, int b) {
return a + b;
}
}
import [Link];
public class Main {
public static void main(String[] args) {
Add obj = new Add();
[Link]([Link](5, 3));
}
}