Meaning of the import statement in a Java file - java

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

Related

Grouping Imports at Java

Does Java support grouping the imports like following:
import package.{Class1,Class2}
I know that * operator imports sub packages but I want to import specific ones.
In Rust or some modern languages it is supported like following:
use package::{Class1, Class2};
Are there any alternative instead of writing each import line by line specifically like this?
import package.Class1;
import package.Class2;
Java Language Specification, section 7.5. Import Declarations, shows:
An import declaration allows a named type or a static member to be referred to by a simple name (§6.2) that consists of a single identifier.
[...]
A single-type-import declaration (§7.5.1) imports a single named type, by mentioning its canonical name (§6.7).
A type-import-on-demand declaration (§7.5.2) imports all the accessible types of a named type or named package as needed, by mentioning the canonical name of a type or package.
A single-static-import declaration (§7.5.3) imports all accessible static members with a given name from a type, by giving its canonical name.
A static-import-on-demand declaration (§7.5.4) imports all accessible static members of a named type as needed, by mentioning the canonical name of a type.
As you can see, it's either a single named type, or all accessible types. No syntax for a list of types.
Side note: I almost never look at the import statements of my code. I let Eclipse manage that for me (Source > Organize Imports... (Ctrl+Shift+O)), so I don't really care about having many single-type import statements. The section with the imports is collapsed anyway, so I don't even have to scroll past them. Oh the joy of using a good IDE.
In java, only supported ways to import multiple classes are as follows :
A - import individual classes
import package.Class1;
import package.Class2;
B - import all classes in a package or subpackage
import package.*;
import package.subpackage.*;
Refer Oracle doc for more information : https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
No. Java doesn't have a construct to import a set of select classes using one statement. You either import all types from the package, or you import them one by one.
Using * lets you import all classes from the same package (not to import sub-packages, as you mentioned):
import package.*; //Both Class1 and Class2 are imported
import static package.Class1.* //All static members of Class1 are imported
The first form import package.* is usually discouraged because of the increased potential for name clashes (same class names from different packages). This is probably where import package.{Class1,Class2} would have helped, but there's no such construct in Java.

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

A wildcard is said to import all classes in a package. "It doesn't import child packages, fields, or methods." What does this mean?

In the Sybex book, OCA Oracle Certified Associate Java SE 8 Programmer I - Study Guide, page 10 of Chapter 1 states the following:
The * is a wildcard that matches all classes in the package. Every
class in the java.util package is available to this program when Java
compiles it. It doesn’t import child packages, fields, or methods; it
imports only classes. (Okay, it’s only classes for now, but there’s a
special type of import called the “static import” that imports other
types. You’ll learn more about that in Chapter 4.)
It was my naive understanding that since a class contains members (fields and methods), it is implied that those are imported, as well. However, according to the author of this book, it appears that the situation is more caveated.
If you are importing a class, and you don't have access to the members of that class, then what is the point of importing that class?
what is the point of importing that class?
Imagine that you do not import classes inside java.util. If you want to create a Map you type:
java.util.Map<String, Integer> myMap = new java.util.HashMap<>();
If you import the class in that package like import java.util.*;:
Map<String, Integer> myMap = new HashMap<>();
If you are importing a class, and you don't have access to the members
of that class
Imports do nothing with access, they are all about readability and convenience. You don't have to type that much and the second declaration is much more readable, but you can use the same methods of myMap in both cases.
The static import that the book mentions (from the doc):
The static import declaration is analogous to the normal import
declaration. Where the normal import declaration imports classes from
packages, allowing them to be used without package qualification, the
static import declaration imports static members from classes,
allowing them to be used without class qualification.
A good example for static import is the usage of Mockito in unit tests. Without any imports you can verify some behavior like:
org.mockito.Mockito.verify(mock, org.mockito.Mockito.never()).someMethod();
If you use normal import import org.mockito.Mockito;:
Mockito.verify(mock, Mockito.never()).someMethod();
and with static import import static org.mockito.Mockito.*; you can type
verify(mock, never()).someMethod();
Here the verify and never static methods can be used even without specifying their class (Mockito).
If you are importing a class, and you don't have access to the members of that class, then what is the point of importing that class?
Suppose you have a package com.ebony.maw.utils, and that package has a class MyUtilities, and the class has a static method findFizgigs(). If you say
import com.ebony.maw.utils.*;
you can now say
MyUtilities.findFizgigs("thingy-002");
instead of having to say
com.ebony.maw.utils.MyUtilities.findFizgigs("thingy-002");
But you still can't say
findFizgigs("thingy-002");
without the class name. That's what they mean by importing the class, but not importing the method. It just means you can use the class name without having to supply a package name prefix. But you can still use the method--you just have to supply the class name as a prefix.

Does the star import include subpackages in Java?

When you declare an import like this:
import com.microsoft.azure.storage.*;
Does that include everything in its subpackages too? For example, does it include this?
import com.microsoft.azure.storage.blob.*
If not, why not? (Edit: the "why" question is basically off topic. ignoring that bit when considering a correct answer.)
No it does not. It only imports everything in the package (i.e. the directory itself). Sub-directories are considered to be different packages, so you would need to:
import com.microsoft.azure.storage.*
import com.microsoft.azure.storage.blob.*
As to why the language designers chose to go this route, one can only guess, but the system that they decided to go with does allow for a more fine-grained approach.
yes you can import all the classes from an import but it does not make it possible to import multiple packages with similar names. For example import java.util*; does not also import java.util.prefs or .jar you have to import these all separately. I don't know if that answers your question, and to the why I am not really sure it just makes sense to do it this way. If you were to import similar packages that had the same static variables, but you only need two or three of the packages then you would get errors or code that does not run properly.
There's a name for these - type import on demand.
A type-import-on-demand declaration allows all accessible types of a named package or type to be imported as needed.
They're only also importing the package itself, and not any subpackages, as clarified by the example, emphasis mine:
import java.util.*;
causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places in the compilation unit where that type declaration is not shadowed (§6.4.1) or obscured (§6.4.2).
does that include everything in / subdirectories too? including
something like this?
* stands for all the compilation units inside the package com.microsoft.azure.storage where sub packages are actually not compilation units and thus not fetched when you write myPack.*. Compilation unit includes class, interface, enum etc.

Java import statement syntax

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.

Categories

Resources