19

I have one doubt. When we use ArrayList or HashMap in Java, we have to import java.util.ArrayList or java.util.HashMap. But when we use String, it doesn't require the import statement. Can anyone clarify, why?

peterh
  • 11,875
  • 18
  • 85
  • 108
Mahaveer Muttha
  • 1,727
  • 4
  • 21
  • 33

5 Answers5

24

String is present in package java.lang which is imported by default in all java programs.

Ankur
  • 12,676
  • 7
  • 37
  • 67
  • From the documentation: _...automatically imports all of the public types declared in the predefined package java.lang._ Source: https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html – AlikElzin-kilaka May 30 '15 at 15:17
12

Everything in the java.lang package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util package, which is not implicitly imported.

The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.

Community
  • 1
  • 1
Kris
  • 14,426
  • 7
  • 55
  • 65
2

Java compiler imports 3 packages by default. 1. The package without name 2. The java.lang package(That's why you can declare String, Integer, System classes without import) 3. The current package (current file's package)

That's why you don't need to declare import statement for the java.lang package.

begginerAll
  • 159
  • 7
  • 19
2

I'm bit late here, but just for new reader, According to my understanding

String is present in package java.lang which is imported by default at class loading time by rt.jar which is present at class path. Bootstrap Classloader (Primodial ClassLoader) is responsible for loading rt.jar.

We always include rt.jar in our classpath, otherwise, you don't have access to core java classes e.g. java.lang.String, java.lang.Thread, java.util.ArrayList or java.io.InputStream etc. and all other classes from Java API.

rt.jar will always reside under $JAVA_HOME/jre/lib and you can open it by using WinRAR or WinZip client

enter image description here

Avinash Nath
  • 132
  • 8
0

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).