package is a bundle or group of classes, interfaces, sub packages combined in a one file. there are two types of packages in java 1) built-in 2) User-defined
In java programming are there are several built-in packages created by the official java developers. for example for taking a input from the user ,we use scanner class
- import is a keyword to use packages in program
- java is a main package ,or top level package
- util is a sub-package
- Scanner is a class inside the util package
Advantages of packages in java
- Name Conflicts: if you have two classes with the same name, that would become a conflict to run the program, so you use name different packages for two same class names, there will be no issue
- Code Maintenance: packages in java are useful when you have a large project,you cant maintain bulky code, so we can split the code into packages and use it in the program. when you need something like any class, you can quickly locate it and use it, which improves efficiency.
- Reusability: once the package is created, you can use the same package to any number of programs, you don’t need to rewrite the whole program.
- Java package provides access protection
Creating a simple package in java
packages can be created using package keyword in java.
Save the above code in the file name as its class name,here in the example file name saved is basic.java
first after writing a package, you should compile and to test your package you can run it
To compile the program ,use the below command
If your package is in the present working directory,then you can use . (dot)
to run the package use below command
For better understanding check the screenshot provided below, for the package basicpack and the file name is basic.java
If use any custom IDE’s like eclipse, Atom, VScode, you have so many plugins to use package in java , I use VScode IDE ,so i use java saber plugin to configure java packages
Packages can be accessed using the import keyword.
To import complete package you can follow below syntax.
Syntax to import complete package
if the package name end with .* then, all classes and interfaces except sub packages are accessabel