Which Package is Imported by Default in Java?
A package in Java is a collection of similar Java classes, sub-packages, and interfaces. Packages wrap related classes and interfaces together thus, it is easier for programmers.
In Java, two packages java.lang package and a no-name package (also called default package) are imported by default in all the classes of Java. Default Package doesn't have a name but it is present by default and thus, it is named the default package. Java Virtual Machine imports these packages by default in Java internally. And that is the reason we are able to access all the classes of these packages.
We are not required to explicitly import java.lang package or any of its classes like we import other packages and their classes such as java.math or java.util.
The default package in Java doesn't have a name and is a collection of classes whose source files do not contain a package declaration.
Package Declaration
Here package project1 is a package declaration and it tells the compiler that this class is a part of project1.
When we don't mention package declaration and directly create a class it is placed in the default package or no-name package of Java. This default package is also imported along with java.lang every time a java class file is created.
This class DefaultPackage is part of the default package.
java.lang package
The java.lang package provides fundamental classes of the Java Programming language design. The two important classes Object and Class, instances of which represent classes at runtime are part of this package.
Other important classes of the package are:
- Integer, Character, Double, Float, Long, Number, String, void, etc. which are common data types used in java programs to store data.
- Compiler, Process, ProcessBuilder, Runtime, SecurityManager, System, StackTraceElement, Thread, etc. which are important to run a java program securely and properly.
- StrictMath class which contains common numeric operations.
Example:
Output:
In the example above, the object of the String class sayHello is created as the String class is part of the java.lang package and it is by default imported. Also, as we don't declare any package, the class myClass is part of the default package. The class System that we use to take input from the user or to print the output is also part of the java.lang package. Using Object and Class classes we are able to represent MyClass as a class and create its objects such as fun.
Learn more about Packages in Java.
Explore Scaler Topics Java Tutorial and enhance your Java skills with Reading Tracks and Challenges.
Conclusion
- The default package (which is also known as the no-name package as it doesn't have the name) and java.lang packages are by default imported in the java class by the JVM.
- They contain classes that are fundamental to the design of the Java language. These classes provide basic functions to the java program.