Which Package is Imported by Default in Java?
In Java, the package is the collection of Java classes and interfaces. When we use the classes of a particular package, we need to import that particular package in which that classes are defined. The class uses the fully qualified name that includes the package name. In most of the basic Java programs, we do not import any package. Here, a question arises that when we do not import any package then how Java programs allow us to use classes defined in the particular package. JVM internally resolve this problem by importing java.lang package by default.
Java compiler imports java.lang package internally by default. It provides the fundamental classes that are necessary to design a basic Java program. The important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time.
Let's create a Java program that finds the number is even or odd. In this program, we have not imported any package.
87 is odd number.
Look at the above program, we have not imported any package. Nevertheless, we have used the String class. While we must write the fully qualified name of the class at the top of the program followed by the import keyword. But we have not done so. It is because Java compiler imports the java.lang package by default in which String class is defined.
If we want to check it is true or not, we can decompile the Java program. If you do not know how to decompile a Java program manually go through the link https://www.javatpoint.com/java-decompiler or use an online Java decompiler http://www.javadecompilers.com/upload/processfile. We have decompiled the above Java program and found that java.io.PrintStream package imports by default. The hierarchy to import PrintStream class, as follows:
The hierarchy shows that the Object class of the java.lang package imports by default. It means the java.lang imports by default but does not show to the user.
After decompiling the above program, the program looks like the following:
Therefore, we need not import java.lang package explicitly. Without importing the java.lang package, we can use the classes of the package in our Java program.