why autoimport only java.lang package?

Viewed 17134

I know that the package java.lang is auto-imported by every java program we write, hence all the classes in it are automatically available to us.

My question is why not auto import java.util and other packages too? That sure will save some typing :)

So please explain why is this not done.

10 Answers

A good reason not to autoimport too much is to avoid namespace clashes. If everything in java.util was imported automatically and then you wanted to refer to a different class named 'Map', for example, you would have to refer to it by its fully-qualified name.

In response to other answers in this thread, import does not actually modify the internal representation of your class files. In fact, here is a link to the JVM spec describing the class file structure: see that imports are not stored anywhere.

All the good IDE's will resolve your imports automatically, only prompting when there is a conflict (two packages with the same classname).

Because java.lang have the core Java language classes, and java.util for example not.

But some other languages, like Groovy automatically imports java.util for you :)

I think the idea behind java.lang is that these classes all have some connection to the language and runtime which is special, and can't be implemented on your own. Primitive wrappers, VM security and permissions and inspection, package and class loading -- all things that must be built-in to the Java system. Everything in java.util, like collections, while incredibly useful, could be implemented in pure Java. Some parts of it (time zones come to mind) have even been implemented by third-party libraries even better.

Or at least, that was true back in the Java 1.0 days. Today, for example, Iterator is also integral to the language, since it's automatically used by for-each loops, right? But backwards-compatibility was always a big thing with Java, so we get to live with this inconsistency forever.

I came across with namespace collision even with java.lang.System (our application contains a System named class). An explicit import solved my problem, but it took some minutes until I pointed out that com.mycompany.classes.System isn't imported automatically for identifier System by Eclipse because it already exists in java.lang.

Anyways, it isn't a good idea to pollute the class scope with too much identifiers, because your code will org.classes.**look** com.application.**like** com.classes.**this**.

Auto-importing java.lang is a good idea because it contains the very core classes and interfaces used in java.

@gameover, May be every java program needs the class that comes from java.lang,

but the java.util class contains the class that my be need or not that is depended on programmer. So the java have the default configuration for java.lang but we need to import to java.util classes according to our program.

Related