The package is an encapsulation mechanism to group related classes and interfaces.
Example of package in Java –
- All classes and interfaces which are required for file input /output are grouped into a seprate package
java.io
. - All classes and interfaces required for Data Base operations are grouped into a single package which is the
java.sql
package.
Package rules in Java
- In any Java source file, there can be at most one package statement if there is more than one package statements in the Java source file then we will get compile time error – “java: class, interface, enum, or record expected”.
package thecodedata.com;
package thecodedata;
public class PackageInJava {
public static void main(String[] args) {
System.out.println("The Code Data");
}
}
- In any Java program, the first non-comment statement should be a package statement (If it is available) otherwise we will get compile time error – “java: class, interface, enum, or record expected”.
import java.util.*;
package thecodedata.com;
public class PackageInJava {
public static void main(String[] args) {
System.out.println("The Code Data");
}
}
Advantage of package in Java
- Unique identification of our component (resolve naming conflict).
- It improves modularity.
- It imporoves maintainabilty of the code.
Similar Java Tutorials
- Odd Even in Java
- Fibonacci Series Java
- Prime Number Java
- Literals in Java
- Variables in Java
- Command Line Arguments in Java
- Java Coding Standards
- Var-Args Method in Java
- new operator in Java
- Conditional operator in Java
- Assignment operator in Java
- Bitwise operator in Java
- Operators in Java
- Public static void main
- Command line argument in Java
- Java coding standards
- Control Flow Statements in Java
- If – else in Java
- Switch statements in Java
- For loop in Java
- While loop in Java
- Do while loop in Java
- Import statement in Java