Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Java classes/packages are automatically imported? [duplicate]

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); 
    }
}

In the above example we are using the println method without importing the package of it. So I want to know: What are the packages or classes included automatically?

like image 685
Tushar Mia Avatar asked Dec 19 '18 13:12

Tushar Mia


Video Answer


2 Answers

Everything in java.lang is imported by default - here you are using java.lang.System and java.lang.String

like image 191
Elliott Frisch Avatar answered Sep 27 '22 19:09

Elliott Frisch


There are two packages imported by default:

  • java.lang
  • The package in which the current class is located (in the case of the above code, this is ostensibly the default package, from which you can't otherwise import explicitly).

From the language spec:

Code in a compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.

So, you only have access to public types in java.lang, but you have access to all top-level types in the current package.

But it's important to note that Java packages aren't hierarchical, despite the appearance, so this means that e.g. java.lang.reflect is not also imported automatically because of java.lang being imported.

like image 26
Andy Turner Avatar answered Sep 27 '22 21:09

Andy Turner