Java - Automatic Import Declarations


Java always imports all types declared in the java.lang package automatically.

The following import-on-demand declaration is added to your source code before compilation:

import java.lang.*;

The following code will compile without errors:

import java.lang.*;  // ignored because it is automatically done for you

public class Main {
        String a; // Refers to java.lang.String

Shadow the class from java.lang

In the following code, which String class will be used: String above or java.lang.String

class String {
public class Main {
     String myStr;

It will refer to String you just defined,not java.lang.String, since the compilation unit is searched before any import declarations.

To use the java.lang.String class in the above code, you must use its fully qualified name, as shown:

public class Test {
   java.lang.String s1; // Use java.lang.String
   String s2;        // Use String

Related Topic