Java Packages | ||
| ||
| In Java, packages act like file folders to group related classes, helping developers write maintainable code and prevent naming conflicts. Packages are divided into built-in packages from the Java API library and user-defined packages created by developers. Built-in functionality, such as utility classes like Scanner, can be accessed using the import keyword to bring in either a single class or an entire package using an asterisk. Developers can also create their own user-defined packages by placing a package declaration at the top of a source file, keeping package names in lowercase, and compiling them with the javac -d command to generate the required directory structure for execution.
Java Packages & APIA package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:
Built-in PackagesThe Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment. The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/. The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package. To use a class or a package from the library, you need to use the
Import a ClassIf you find a class you want to use, for example, the In the example above, To use the
Import a PackageThere are many packages to choose from. In the previous example, we used the To import a whole package, end the sentence with an asterisk sign (
User-defined PackagesTo create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer: MyPackageClass.java Save the file as MyPackageClass.java, and compile it: Then compile the package: This forces the compiler to create the "mypack" package. The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign ".", like in the example above. Note: The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called "mypack". To run the MyPackageClass.java file, write the following: The output will be:
| ||
| | ||
| |