Java import statement syntax - java

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?

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).

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.

import java.util.Scanner says.
Look in the package java.
Within that look in the package util.
Within that find the class Scanner.
Now whenever we use the name of a class/etc within this java file (for example Scanner s = new Scanner()) then the class found by the import will be used.
Alternatively you could not do the import and do java.util.Scanner s = new java.util.Scanner() but you can see how that would quickly become unwieldy, especially if you use it in a lot of places within your file. Imports are just a handy way to reduce repeatedly specifying which version of the Scanner class you mean when you refer to Scanner.

A few points:
the package name is java.util, not util. "java" is just part of the package name.
package names are any series of valid java identifiers separated by dots, AbC123.XYZ.foo is a valid package name
package may be omitted. If absent, the class is in the root directory of the project (I once worked on a project in production that had no packages! Everything was in one directory... Yikes!)
by convention, packages starting with java are part of the JDK (plus extensions). There is nothing in the language that specifies this or enforces it

java and util are names of nested packages. java.util is a path to final package.
They are directories inside rt.jar file.
rt.jar file is a zip archive, you can view it with 7-zip program.
Scanner is a Scanner.class file inside java/util directory inside rt.jar
import java.util.Scanner directive just allows you to use Scanner class name in code without specifying full path to it.
import java.util.* directive allows you to use ALL class names in java.util without a path.
import static java.util.Scanner.* directive allows you to use ALL static members inside Scanner, without a paths. But there are none.
List of all packages in JRE are here: http://docs.oracle.com/javase/7/docs/api/overview-summary.html

1) java is a package. (also represents a folder in file system).
It is directly in the classpath, so it is referenced by your program as 'java'. (subfolder in java folder)
2) util is a package inside java package (hence referenced as 'java.util').
3) Scanner is a class inside util package (hence 'java.util.Scanner')
You can have as many nested packages as you want like 'mypackage1.mypackage2.mypackage3. ...' and so on, as long as mypackage1 is in the classpath.
Hope this helps

the import statement represent a hierarchy
import java.util.Scanner;
java is the package
util is the subpackage (inside java)
Scanner is the class (inside util)
import java.util.*;
The class name could be subtituited with an asterisk,
and that means import all classes in the mentioned subpackage.

Related

why is it possible to create String.java?

Just trying to understand why I am able to create String.java file and it is compiled without any errors. As far as I know, the classloader chain will go to Bootstrap classloader and it has already loaded Sting.class.
Could you pls help me in understanding?
A class is not identified by just its name, but by its fully-qualified name, which is the name of the package followed by the name of the class.
If you create your own String class in some package com.myapp, then its fully-qualified name will be com.myapp.String. It doesn't conflict with the standard String class, which has the fully-qualified name java.lang.String.
Of course, it's going to be very confusing when you do this, especially because classes in the package java.lang are imported by default. Therefore, in practice you should never write your own class String, or name any of your own classes the same as classes from the standard library (especially standard classes from the package java.lang).
As highlighted by Jesper, the uniqueness of a class is determined by its fully qualified name i.e., package..
Try importing both the String classes in another class, and you will observe the difference when you will try to use it.
import java.lang.String;
import com.myclass.String;
Now, for resolving the ambiguity, you need to refer a class by its fully qualified name.

Why does Java allow nested method calls without importing the class? [duplicate]

Can any one clearly explain to me what exactly happens when we use the import statement in Java files? Does it increase the size of the file if we add more and more java classes? Why don't we use class loader for the same? And what are the restrictions for importing?
import declarations (not statements) are essentially short-hand enabler at the source code level: it allows you to refer to a type or a static member using a single identifier (e.g. List, min) as opposed to the fully qualified name (e.g. java.util.List, Math.min).
import declaration section is a compile-time element of the source codes, and has no presence at run-time. In JVM bytecodes, type names are always fully qualified, and unless you're using a poorly written compiler, the binary should only contain names for types that are actually being used.
Class loaders are used for an entirely different concept, and has nothing to do with import feature at all.
JLS 7.5 Import Declarations
An import declaration allows a static member or a named type to be referred to by a simple name that consists of a single identifier. Without the use of an appropriate import declaration, the only way to refer to a type declared in another package, or a static member of another type, is to use a fully qualified name.
A single-type-import declaration imports a single named type, by mentioning its canonical name.
A type-import-on-demand declaration imports all the accessible types of a named type or package as needed. It is a compile time error to import a type from the unnamed package.
A single static import declaration imports all accessible static members with a given name from a type, by giving its canonical name.
A static-import-on-demand declaration imports all accessible static members of a named type as needed.
References
JLS 7.5.1 Single-Type-Import Declaration
JLS 7.5.2 Type-Import-on-Demand Declaration
JLS 7.5.3 Single Static Import Declaration
JLS 7.5.4 Static-Import-on-Demand Declaration
See also
Java Tutorials/Using package members
Java Language Guide/static import
Various import related questions
On the grammatical role of import:
What is an import called? - it's a declaration, not a statement
On on-demand vs single-type:
Import package.* vs import package.SpecificType
Why is using a wild card with a Java import statement bad?
What’s the difference between import java.util.*; and import java.util.Date;?
On import static:
What does the static modifier after import mean?
What is a good use case for static import of methods?
Should I use static import?
Performance-related issues:
Does importing of packages change visibility of classes? - ABSOLUTELY NOT!
Do multiple import statements in a program affect performance? - NOPE!
Any reason to clean up unused imports in Java, other than reducing clutter?
Packages consist of classes, classes in a package consist of methods, variables etc etc.
A class has a full name which comprises of the package name and the class name. If you need to use a class in your code,you need to give the compiler the full name of the class.So, you use an import statement OR you can type the fully qualified name every place you use that class in your code.
For example, if you need an AraryList in your code, you use the import statement import java.util.ArrayList; instead of typing the fully qualified class name every place you need an Arraylist.
For more detailed info, see JLS.
The imports in java are only hints for the compiler. It doesn't affect the size of the binary class file at all. You can either use an imports once or write the full name of the Class every time you use it.
Imports are just a concession to readability and the laziness of the developer.
import statements say to the compiler: if you have a function that cannot be found in this class look in the list of imports.
This way you can refer to functions in other packages without having to copy the definition (like C(++) .h files) to your own package.
The import statement in Java allows to refer to classes which are declared in other packages to be accessed without referring to the full package name. You do not need any import statement if you are willing to always refer to java.util.List by its full name, and so on for all other classes. But if you want to refer to it as List, you need to import it, so that the compiler knows which List you are referring to.
Classes from the java.lang package are automatically imported, so you do not need to explicitly do this, to refer to String, for example.
Read more: http://wiki.answers.com/Q/Why_import_statement_is_needed_in_Java_program#ixzz1zDh2ZBhE

"The import [...] conflicts with a type defined in the same file" error [java]

I'm importing a package (in my case, mongodb.DB) into a java file with an identically named class.
In python, I know I can import a module as another name to avoid conflicts. How does Java solve this problem?
It's not feasible to change the name of the class I'm working in.
You say you are "importing a package..." - do you mean you are importing all classes in a package, like "a.b.c.*"? If so, the answer might be to import only those classes you need, not the entire package.
There is no way to import a class as another class.
Hopefully you don't really mean "identically named" as in both of them having the same fully-qualified name. If that's the case, you're screwed, I don't know anything you can do. Hopefully you just mean that the class name is the same in two different packages.
You can extend a class with your own class, and use your new class in the place of the one extended. In other words, if you're importing the class D as in a.b.c.D, and there is another D class, you could extend the first of them (class Z extends a.b.c.D), and then refer to it as Z instead of D. You might need to provide constructors for Z that match ones in D, but no code should be required other than that.
And the fully-qualified names of the classes will always work.
You can use the fully qualified name "mongodb.DB" instead of just the class name.

Should a java package have only one public class?

I tired creating a package with one public class and one with multiple public classes and then import them through another package and both times the program worked. I understand the difference, in the first i can only use the methods of the one public class, but that class can use other classes in its package, and when more classes are public i can directly access all those classes through the alien package.
Now when we import java.util.Scanner, and we import java.util.ArrayList isn't this the same package? When we import our package with one public class it only shows the one public. That means that java.util has multiple public classes, or?
Also what does that java. mean, does it make the difference between my package and java library packages?
Yes, a package can have multiple public classes.
Creating a new package for every public class would be extremely cumbersome and provide no overview at all.
java. are just the standard libraries that come with the JDK/JRE.
Packages are really just like folders on your system. You can have multiple files in a folder without a problem.
Typically packages are structured in a way that they combine related classes to make it easier for the developer. If you want to have no packages at all, or you want a new package for every class: it doesn't matter. You'll be your own worst enemy, but it is surely possible.
import java.util.ArrayList;
means: let me use the class ArrayList, which is in the package java.util, by only typing ArrayList and not java.util.ArrayList.
java.util is the name of the package, nothing else. It's where the Java developers chose to store the ArrayList class. It's not different from any other package name, except you're not allowed to use the java package for your own classes, because it's reserved for standard Java classes.
import java.util.*;
means: let me use all the classes of the package java.util (ArrayList, LinkedList, Collection, etc.) by typing their simple name (ArrayList, LinkedList, Collection, etc.) instead of their fully qualified name (java.util.ArrayList, java.util.LinkedList, java.util.Collection, etc.)
All these classes are public (as documented in their javadoc). If they weren't public, you wouldn't be able to use them in your own classes.

Java package and classpath question

Can anyone please explain the answer to the following question:
Given a correctly compiled class whose source code is:
package com.sun.test;
public class Commander {
public static void main(String[] args) {
}
}
Assume that the class file is located in /foo/com/sun/test/, the current directory is /foo/, and that the classpath contains "." (current directory). Which command line correctly runs Commander?
A. java Commander
B. java com.sun.test.Commander
C. java com/sun/test/Commander
D. java -cp com.sun.test Commander
E. java -cp com/sun/test Commander
And the best answer would be B. C also works on some platforms but is not recommended and is very uncommon (at least, I've not seen it in over 10 years programming Java).
EDIT
A common misconception with beginners in Java is that a class name is something like "MyClass". But that is not accurate; the nomenclature "MyClass" as seen in the declaration class MyClass is really a convenience for the programmer which the compiler combines with the package declaration to create what Java refers to as a qualified class name, which all class names really are to the runtime. (In C#, they use namespaces for this).
This becomes quite evident in many cases such as stack traces and method signatures which always contain, for example, java.lang.String. Because "String" is just a short form that is resolved to java.lang.String. You can prove this by making your own String in your own package... but beware doing so will require that you explicitly use java.lang.String or my.package.String everywhere that both packages or classes are imported.
Once you assimilate the fact that all class names are fully qualified, and that the compiler helps you avoid tedious work by using imports to resolve short forms to fully qualified forms, things become clearer.
It should then be evident why:
java -cp com/sun/test Commander
doesn't work. The cp option puts the directory ./com/sun/test (relative to the current directory) on the class path, but there is no class named Commander... it's com.sun.test.Commander. This implies two things: (a) the command line requires com.sun.test.Commander and (b) the classpath must contain an entry for the directory which contains "com" in order to resolve this class since a class named x.y.MyClass must be in x/y relative to some classpath element.
PS: You should not be using com.sun as a package name unless you are employed by Sun, since the domain name sun.com belongs to Sun. This convention exists to avoid class packaging and naming collisions.
PPS: There is such a thing as the default package, which is "specified" by omitting the package declaration -- but it should almost never be used. The one legitimate place I have found is with a self-contained "Launcher/Classloader" where it is desired to be able to do:
java -cp . Launcher com.xxx.yyy.TargetApp
with Launcher.class in the current directory... and that is only because JAR files are held locked while the app is running while class files are not, which means that Launcher.class can self-update, while Launcher.jar cannot.
Assuming CLASSPATH environment variable is not set (and thus current working directory is in the classpath by default), the answers are the following:
A. Does not work, there is no Commander class in the default package
B. This one works
C. This one works also, but B is preferred
D. Class path is foo/com.sun.test where there is no Commander class in the default package
E. Class path is foo/com/sun/test where there is no Commander class in the default package
A. Not working, as Java will not found the Commander class
B. Will work, as Java will not found the com.sun.test.Commander class
C. Will work, at least on a Windows plateform. That's why you must use . instead of /.
D and E. They will not work because we still ask Java to search for the class Commander and not com.sun.test.Commander

Categories

Resources