Packages in Java
- Packages in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
- We can reuse existing classes from the packages as many time as we need it in our program.
- All we need to do is put related classes into packages.
- After that, we can simply write an import class from existing packages and use it in our program.
- Packages names and directory structure are closely related. For example, if a package name is DevBhoomi.BTech.CSE.Deepak, then there are three directories, DevBhoomi, BTech and CSE such that CSE is present in BTech, BTech is present in DevBhoomi and Deepak is the class name.
There are two types of packages in Java:
- In-Built packages
- User-defined packages
In-Built packages
These packages consists of a large number of classes which are a part of Java API (Application Programming Interface). Some of the commonly used built-in packages are:
- java.lang: Provides classes that are fundamentals to the design of the Java Programming Language. This package is automatically imported.
- java.io: Provides for system input and output through data streams, serialization and the file system.
- java.util: Contains the collections framework, a service loader, properties, random number generation, string parsing and scanning classes.
- java.applet: Provides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context.
- java.awt: Contains all the classes for creating user interfaces and for painting graphics and images.
- java.net: Provides the classes for implementing networking applications.
User-defined packages
These are the packages that are defined by the user. To create a package, write package keyword at the top of program followed by the directory name, and then compile the program.
Creating a Java Package
To Compile :
javac -d. Calculator.java
This will create a package of name MyPackage that will contain the class file of that program. Now, we can move the program to that folder.
Using a Java Package
import keyword is used to import packages in the java program. There are three ways to import a class in Java, let's try these ways for a Scanner class
- Writing at top: import java.util.Scanner; This will import the Scanner class only.
- Writing at top: import java.util.*; This will import all classes inside the util directory.
- Importing while creating object or without using import keyword: java.util.Scanner object_name = new java.util.Scanner; This will also import the Scanner class.
Output :
Performing some basic mathematical operations...
The sum of numbers is 150.0
The difference of 20 and 10 is 10.0
The product of numbers is 0.0
The division of 10 by 3 is 3.3333333333333335
Comments
Post a Comment