Namespace management refers to the concept of preventing naming collisions. There are a lot of programmers out there writing a lot of Java files, some of which are bound to have the same name.
For example, say you're writing a program and you want to use two different
Graph
classes, written by two different people. The packages they're in can be used to distinguish them.Importing
Previously in this class, when you wanted to use a class someone else wrote (say, the
ArrayList
), you imported it with the statementimport java.util.ArrayList;
Then you could instantiate a new
ArrayList
like so:ArrayList arr = new ArrayList();
It turns out that the
import
statement is doing nothing more than namespace management. It allows the programmer to refer to a class by its name rather than by its full name including the package it is within. The compiler later substitutes the shorthand for the full class names.In the example above, all the
import
statement is doing is telling Java that we want to use the ArrayList
class that is in the package java.util
, and not some other ArrayList
class that someone else wrote. Java actually allows you to forego the import statement if you fully name the package yourself. For example, if you don't import
ArrayList
, you can still use it, but you have to refer to it with its complete package name. Here's something to try out: initialize a new ArrayList
object without importing it first.java.util.ArrayList arr = new java.util.ArrayList();
This looks like a lot of effort to type out every time. The
import
statement allows us to state upfront that every time we refer to the class ArrayList
, we mean to use the one inside java.util
. If you want to use two different ArrayList
classes in your code, each from different packages, then the import
statement won't help you. You just need to refer to each by their complete package name.