Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java import statement syntax

Tags:

java

import

This is a simple question, but I am really bugged by it. I was trying to find a duplicate, and googled it, but I was more surprised when I couldn't find a satisfying answer.

import java.util.Scanner; 

In this statement .Scanner is the class,

.util is the name of the package

What is java or javax or whatever would stand before the first period in general?

UPDATE:

I also found this picture:

http://www.javatpoint.com/package

Is it true?

like image 658
user3081519 Avatar asked Dec 25 '13 22:12

user3081519


2 Answers

Per the JLS 7.1:

The members of a package are its subpackages and all the top level class types (§7.6, §8) and top level interface types (§9) declared in all the compilation units (§7.3) of the package.

For example, in the Java SE platform API:

  • The package java has subpackages awt, applet, io, lang, net, and util, but no compilation units.

  • The package java.awt has a subpackage named image, as well as a number of compilation units containing declarations of class and interface types.

If the fully qualified name (§6.7) of a package is P, and Q is a subpackage of P, then P.Q is the fully qualified name of the subpackage, and furthermore denotes a package.

So you can glean from that:

  • java is a package with no classes, only subpackages.
  • util is a subpackage of java whose fully qualified name is java.util.
  • util does not denote a package, java.util does.

"I also found this picture: ... Is it true?"

Yes, util is a subpackage of java. However, util is not a package. java.util is a package.

You can think of packages as a directory structure, if you wish, where each subpackage is a folder inside its outer package. So there would be a "folder" java and, inside that, another "folder" util. A package is denoted by its fully qualified name ("full path") so java is a package and java/util is a package. /util is not a package. But packages represented by a directory structure is not a spec. It is only a common implementation. It is up to the host system to decide how packages are stored (JLS 7.2).

like image 60
Radiodef Avatar answered Oct 10 '22 13:10

Radiodef


Classes in Java are identified by a fully qualified name consisting in a concatenation of the package of the class and the name of the class (and any outer classes, if any). In general, in an import statement like:

import foo.bar.baz.MyClass;

everything except the last dot-separated field is the package name (foo.bar.baz) and the last field is the class name (MyClass). In your example, java.util is the package name and Scanner is the class name.

The process is actually a bit more complicated, as inner/nested classes and interfaces may be involved, but you get the idea.

like image 45
Darkhogg Avatar answered Oct 10 '22 12:10

Darkhogg