Hierarchy of Java Packages - java

I was trying to understand the general hierarhcy of Java packages.
If you consult this Oracle page, it seems that there are 3 main packages:
java, javax and org.
All packages, in Java platform 7, start with one of these three.
Are these ones part of a bigger package?
I'd love to see a complete tree, but the one offered by Oracle is very confusing, because it's too detailed.
Another thing I did not undestand is why packages like "java.awt" and "java.awt.color", or "java.lang" and "java.lang.annotation", are put by Oracle on the same level.
I did read online that if you import a "parent-package", you don't import any classes form the "child-packages", and that makes sense. However, it's hard to think that there isn't a relation between java.awt and java.awt.color; It seems intuitive that the least is contained in the fromer.
So, given my current understanding, I would draw a tree that look like this:

No, there is no "bigger" package. The structure evolved over time, with different ideas and marketing influencing the naming.
You do not import packages in java, just classes. So before Java9, it does not really matter much even in which package a class resides except for the package-protected visibility scope (which is not used that much), and the lack of need to import classes from the same package.
Often classes from a subpackage are used by classes in a parent package, but not the other way round. But there is no strict rule about this.

Related

Is it more efficient for Java to import java.math.* or java.math.BigInteger and java.math.BigDecimal? [duplicate]

It is much more convenient and cleaner to use a single statement like
import java.awt.*;
than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
What is wrong with using a wildcard in the import statement?
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:
You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
When you compile your code, there is no com.mycompany.calendar.Event, but when they later add one, your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.
Here's a vote for star imports. An import statement is intended to import a package, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. java.sql.Date vs java.util.Date) are easily remedied by other means, not really addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.
Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove all of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.
If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.
Here's how to deal with class conflicts:
import java.sql.*;
import java.util.*;
import java.sql.Date;
Please see my article Import on Demand is Evil
In short, the biggest problem is that your code can break when a class is added to a package you import. For example:
import java.awt.*;
import java.util.*;
// ...
List list;
In Java 1.1, this was fine; List was found in java.awt and there was no conflict.
Now suppose you check in your perfectly working code, and a year later someone else brings it out to edit it, and is using Java 1.2.
Java 1.2 added an interface named List to java.util. BOOM! Conflict. The perfectly working code no longer works.
This is an EVIL language feature. There is NO reason that code should stop compiling just because a type is added to a package...
In addition, it makes it difficult for a reader to determine which "Foo" you're using.
It's not bad to use a wild card with a Java import statement.
In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.
Here is the recommendation:
J1: Avoid Long Import Lists by Using
Wildcards
If you use two or more classes from a
package, then import the whole package
with
import package.*;
Long lists of imports are daunting to
the reader. We don’t want to clutter
up the tops of our modules with 80
lines of imports. Rather we want the
imports to be a concise statement
about which packages we collaborate
with.
Specific imports are hard
dependencies, whereas wildcard imports
are not. If you specifically import a
class, then that class must exist. But
if you import a package with a
wildcard, no particular classes need
to exist. The import statement simply
adds the package to the search path
when hunting for names. So no true
dependency is created by such imports,
and they therefore serve to keep our
modules less coupled.
There are times when the long list of
specific imports can be useful. For
example, if you are dealing with
legacy code and you want to find out
what classes you need to build mocks
and stubs for, you can walk down the
list of specific imports to find out
the true qualified names of all those
classes and then put the appropriate
stubs in place. However, this use for
specific imports is very rare.
Furthermore, most modern IDEs will
allow you to convert the wildcarded
imports to a list of specific imports
with a single command. So even in the
legacy case it’s better to import
wildcards.
Wildcard imports can sometimes cause
name conflicts and ambiguities. Two
classes with the same name, but in
different packages, will need to be
specifically imported, or at least
specifically qualified when used. This
can be a nuisance but is rare enough
that using wildcard imports is still
generally better than specific
imports.
Performance: No impact on performance as byte code is same.
though it will lead to some compile overheads.
Compilation: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.
It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:
import java.util.*;
import java.awt.*;
...
List blah; // Ambiguous, needs to be qualified.
It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.
It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.
Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.
I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)
In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.
A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.
In DDD book
In whatever development technology the implementation will be based on, look for ways of minimizing the
work of refactoring MODULES . In Java, there is no escape from importing into individual classes, but you
can at least import entire packages at a time, reflecting the intention that packages are highly cohesive units
while simultaneously reducing the effort of changing package names.
And if it clutters local namespace its not your fault - blame the size of the package.
Here are the few things that I found regarding this topic.
During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code.
In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports.
Using .* import helps to make code more cleaner
Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.
import java.util.*;
import java.sql.*;
public class DateDemo {
private Date utilDate;
private Date sqlDate;
}
The most important one is that importing java.awt.* can make your program incompatible with a future Java version:
Suppose that you have a class named "ABC", you're using JDK 8 and you import java.util.*. Now, suppose that Java 9 comes out, and it has a new class in package java.util that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class in java.awt.
You won't have that problem when you import only those classes explicitly from java.awt that you actually use.
Resources:
Java Imports
Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.
For the record:
When you add an import, you are also indicating your dependencies.
You could see quickly what are the dependencies of files (excluding classes of the same namespace).
There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see import ...*.
C# always uses * (implicitly) as you can only using package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic).
In Intellij Idea when you do "organize imports", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).
The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.
Forget about cluttered namespaces... And consider the poor soul who has to read and understand your code on GitHub, in vi, Notepad++, or some other non-IDE text editor.
That person has to painstakingly look up every token that comes from one of the wildcards against all the classes and references in each wildcarded scope... just to figure out what in the heck is going on.
If you're writing code for the compiler only - and you know what you're doing - I'm sure there's no problem with wildcards.
But if other people - including future you - want to quickly make sense of a particular code file on one reading, then explicit references help a lot.
Why is using a wild card with a Java import statement bad?
If you're using an IDE (which you should be doing), and there are more code owners than just you, using wildcard imports is bad because it:
conceals information from the rest of the team
provides only false benefits (things which are better-solved using IDE functionality than with wildcard imports) to you as an individual
Most of the "use wildcards" proponents have a focus on the individual: I don't want to maintain the list, I don't want see the clutter, etc. Here are several of the common examples:
maintenance is harder – when you want to introduce a new class into your source code, you have to manually add the import statement
refactoring is more difficult – if code is moved around, then import statements have to be updated
reduce clutter, tidy up file contents – goal here is something along the lines of "removing distractions"
These arguments were more convincing before IDEs did all of that automatically. If you're using a plain text editor instead of an IDE, then these arguments have some merit. But if you're using a plain text editor, you are already subjecting yourself to a number of other much more significant inefficiencies, and managing import statements is just one among many things that you should stop doing by hand. IDEs offer automatic management of imports, powerful refactoring tools, and folding (hiding) of any parts of the code you don't want to see.
For the "avoid wildcards" proponents, there are many examples, but I'll point out only one:
clarity – specifically, when someone new enters the codebase. They will arrive with questions, and continue to discover new questions as they explore the code. For this new code contributor, wildcard import statements do not answer any questions, and at worst can produce confusion, misunderstanding, new questions. In contrast, with explicit imports (and using an IDE) the worst case is neutral: no new info provided; at best, it not only reduces ambiguity but it can also provide answers.
At the end of the day, it helps the entire team to reduce (albeit in a small way) code complexity, to reduce confusion, to add clarity.
Importing all the classes in a package is considered a blind approach. A major reason for this is that it clutters the class namespace and could lead to conflicts between classes in different packages with the same name.
Specifically populating the necessary classes avoids that problem and clearly shows which versions were wanted. This is good for code maintainability.

Do I have to use "package" term in every class?

Firstly, I'm trying to learn Java with Java, A Beginner's Guide, 4th Edition. I use Ubuntu as my OS and Netbeans as my IDE. I need to create a project to create a class when using Netbeans.
Here is my hello world app.
class First{
public static void main(String args[])
{
System.out.println("Hello!");
}
}
But this returns a lot of errors. When I put package first; line to top line of my Java class it runs. But, the book isn't using package term. Is this a rule of Netbeans, or what I need to know about this?
You never need to put a class in a package. However, it is almost always a good idea. This is something that Netbeans aggressively tries to encourage you to do.
For small projects, using the default package (that is, a file without a package statement) is OK. However, once your project grows and starts adding external libraries, bad things can happen. What if someone else decided to use the default package and happened to have an identically-named class? Now, since you're both in the same package, collisions can occur!
Your file structure should also reflect your package. That is, a file in package com.myurl.helloworld should be located in a folder called com/myurl/helloworld. This is for the same reasons as above.
Also, and you probably haven't gotten here in your studies, you cannot import classes from the default package, or use the package-private visibility modifier in a default package class.
That's because the author of Java, A Beginner's Guide, 4th Edition most likely used the "default package". This way, you don't have to include any package. A package is a namespace declaration.
What the heck is a namespace declaration!?
A namespace declaration is simply a package which is made to organize your classes. For an instance, if you're going to have multiple classes for, let's say your GUI, and multiple classes for algorithms, blending them together is always a bit confusing. Sorting them in different packages, however is a superior solution.
There is also a naming convention which you should follow if other people are going to look at your code. Packages should be named after a top-level domain. I tend to create SourceForge projects and then I end up with something like this:
net.sourceforge.softwarename.security, net.sourceforge.softwarename.gui, etc...
Also note that you should never use upper case when naming your package. More info here.
You're going to encounter lots of situations like these when learning to programming. They're all a part of the game. You'll just have to figure out a bit by yourself.
The best I can do for you is to recommend Eclipse. Also, when learning Java, I would suggest that you do not use an IDE at ALL! That's because you'll learn to code independently. It's up to you, though.
No you don't need to put in a package into your class UNLESS you are going to import it to another class that will be in it's own file. This is where protected type variables come in when you don't want to make them priviate but only want the subclasses (or child classes) access to them. You are also missing your public statement for your class so it should look like
public class First{
public static void main(String[] args){
System.out.println("Hello!");
}
}
Package represents a directory that contains related group of classes and interfaces.
A package is a namespace that organizes a set of related classes and
interfaces. Conceptually you can think of packages as being similar to
different folders on your computer. You might keep HTML pages in one
folder, images in another, and scripts or applications in yet another.
Because software written in the Java programming language can be
composed of hundreds or thousands of individual classes, it makes
sense to keep things organized by placing related classes and
interfaces into packages.
Below you can find some good discussions regarding java packages:
Java packages com and org
Are there best practices for (Java) package organisation?
Java com.* package namespace

Why do Java sources have so many folders inside each other?

Every time I look at some Java source code, I find myself surfing in a folder that has folder that has folder that has folder in it etc. Why does Java require so many nested folders, which have nothing else in them except the new subfolder?
For example:
https://github.com/halfninja/android-dragcontrol3d/tree/master/src/uk/co/halfninja/android
That's probably not the worst example, but there are two folders "uk" and "co" that just don't make sense. I see this in Java sources only!
And for example minicraft: http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&uid=398
import com.mojang.ld22.gfx.Font;
import com.mojang.ld22.gfx.Screen;
import com.mojang.ld22.gfx.SpriteSheet;
Why not just write:
import gfx.Font;
import gfx.Screen;
import gfx.SpriteSheet;
That's so much cleaner.
(I have never programmed in Java.)
These are there to prevent conflicts with other jars. Having something like the company url in the package name makes it likely to be unique enough to not conflict with someone else's package and classes.
Your example is a good one, since it seems pretty reasonable to imagine two people thinking of using "gfx" as a package name and with classes like Font or Sprite. Now, if you wanted to use both of them, how could you since the package and class name would be the name?
Your way is cleaner, but it assumes nobody else in the world is ever going to create a package called gfx, which is a pretty weak assumption. By prepending your reversed domain name, you create a unique namespace that avoids collisions.
This fits perfectly with the "culture of sharing" that pervades Java programming, in which applications typically combine large libraries from many sources.
In Java, the convention is to name your packages (which correspond to the folder structure containing your code) with information identifying your organization (typically including a TLD and the company name) and project (which might add a few more sections).
Being more specific like this also reduces the likelihood of namespaces accidentally colliding with eachother.
It's merely an organizational technique for preventing namespace conflicts. Nothing more or less. Java package names match the underlying directory structure, so any organizational pattern at the package level will be reflected there. It's typical for teams to start their package names with their organization's name and wax specific. This is simply convention, but it's ingrained and should be followed absent a very good reason.
It's all about Namespaces. With 'Namespaces', you can create 2 classes with the same name, located in different packages/folders. This Namespace logic can also be used for creating 'Access Privileges', etc etc. Below are some links:
1) Namespace
2) Java Package
3) Java Package Naming Conventions
EDIT: Let us assume that you are creating a new project and are using 2 open source frameworks from companies/organizations - comA and comB. Also, let us assume that comA and comB have created a class in their projects with the same classname. Now, with the Java package naming conventions, we have com.comA.SomeClass and com.comB.SomeClass. You can import and use both the classes in your class, without having a conflict. This is just a simple example. There are other uses from this naming convention.
If you want to share code with everyone else, but use generic names without conflict. its considered good practice to include you domain name (backwards)
Everyone write a package called gfx.Font you wouldn't be able to use more than one version in the same application.
You might feel your code will not be shared with the world (or even should not be shared) In which case, a shorted package structure may be simpler.
If you use an IDE, it does a good job of hiding long package structures so you don't need to worry about it.
This is due to recommended packaging structure. In large projects, so many packages/libraries are used and in order not to put source files into same folder with another library, programmers put their source codes into unique folders. As websites are unique, it is a convention to use packaging structure that looks like folder structure of websites.
Java does not require anything: you can just put all your classes in the default package and surf away. But for serious projects that kind of organization is not only wise, it's mandatory. The com.mojang.ld22 part is just a convention:
com = either this or org, java/javax for official packages
mojang = second part is company name
ld22 = third part is application name

why autoimport only java.lang package?

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.
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.
java.lang package provides fundamental classes to built java programs. Object is the root of class hierarchy so it needs to be available for every programmer whether the programmer is beginner or expert.
While if we talk about other packages they are used for enlarging the programs. For example, java.util package which is only used when Collection classes are needed. While in every program Collection classes are not used while basic datatypes are essential for every java program.
To avoid unnecessary load of other classes in program other packages are not auto imported while essential package java.lang is auto imported.
There are different reason for to become java.lang package is default
1)
Actually ,whatever we are declaring variable in java program.that will be stored in object,Object class is available in java.lang package.it is super class of class hierarchy,Many we have performed operation in object class method like thread programming.
2)
Many time it is required class for developing program ,that class is available in java.lang package,
So, it is necessary to import,when java people developed jdk, it was default package,
Auto importing also leads some memory issue and some times it may conflict.
Eg: Date Type in java & SQL .
Also whatever the base core java objects are defined in Java.lang package .
Eg: any datatype & return type all are declared in java.lang package so to do some basic program also we need this package imports.
Without java.lang package, development is not possible.
But without java.util, java.io or any other packages, we can still write any number of programs.
That is the reason why java.lang package is being imported by default.

Why is using a wild card with a Java import statement bad?

It is much more convenient and cleaner to use a single statement like
import java.awt.*;
than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
What is wrong with using a wildcard in the import statement?
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:
You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
When you compile your code, there is no com.mycompany.calendar.Event, but when they later add one, your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.
Here's a vote for star imports. An import statement is intended to import a package, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. java.sql.Date vs java.util.Date) are easily remedied by other means, not really addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.
Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove all of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.
If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.
Here's how to deal with class conflicts:
import java.sql.*;
import java.util.*;
import java.sql.Date;
Please see my article Import on Demand is Evil
In short, the biggest problem is that your code can break when a class is added to a package you import. For example:
import java.awt.*;
import java.util.*;
// ...
List list;
In Java 1.1, this was fine; List was found in java.awt and there was no conflict.
Now suppose you check in your perfectly working code, and a year later someone else brings it out to edit it, and is using Java 1.2.
Java 1.2 added an interface named List to java.util. BOOM! Conflict. The perfectly working code no longer works.
This is an EVIL language feature. There is NO reason that code should stop compiling just because a type is added to a package...
In addition, it makes it difficult for a reader to determine which "Foo" you're using.
It's not bad to use a wild card with a Java import statement.
In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.
Here is the recommendation:
J1: Avoid Long Import Lists by Using
Wildcards
If you use two or more classes from a
package, then import the whole package
with
import package.*;
Long lists of imports are daunting to
the reader. We don’t want to clutter
up the tops of our modules with 80
lines of imports. Rather we want the
imports to be a concise statement
about which packages we collaborate
with.
Specific imports are hard
dependencies, whereas wildcard imports
are not. If you specifically import a
class, then that class must exist. But
if you import a package with a
wildcard, no particular classes need
to exist. The import statement simply
adds the package to the search path
when hunting for names. So no true
dependency is created by such imports,
and they therefore serve to keep our
modules less coupled.
There are times when the long list of
specific imports can be useful. For
example, if you are dealing with
legacy code and you want to find out
what classes you need to build mocks
and stubs for, you can walk down the
list of specific imports to find out
the true qualified names of all those
classes and then put the appropriate
stubs in place. However, this use for
specific imports is very rare.
Furthermore, most modern IDEs will
allow you to convert the wildcarded
imports to a list of specific imports
with a single command. So even in the
legacy case it’s better to import
wildcards.
Wildcard imports can sometimes cause
name conflicts and ambiguities. Two
classes with the same name, but in
different packages, will need to be
specifically imported, or at least
specifically qualified when used. This
can be a nuisance but is rare enough
that using wildcard imports is still
generally better than specific
imports.
Performance: No impact on performance as byte code is same.
though it will lead to some compile overheads.
Compilation: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.
It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:
import java.util.*;
import java.awt.*;
...
List blah; // Ambiguous, needs to be qualified.
It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.
It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.
Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.
I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)
In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.
A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.
In DDD book
In whatever development technology the implementation will be based on, look for ways of minimizing the
work of refactoring MODULES . In Java, there is no escape from importing into individual classes, but you
can at least import entire packages at a time, reflecting the intention that packages are highly cohesive units
while simultaneously reducing the effort of changing package names.
And if it clutters local namespace its not your fault - blame the size of the package.
Here are the few things that I found regarding this topic.
During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code.
In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports.
Using .* import helps to make code more cleaner
Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.
import java.util.*;
import java.sql.*;
public class DateDemo {
private Date utilDate;
private Date sqlDate;
}
The most important one is that importing java.awt.* can make your program incompatible with a future Java version:
Suppose that you have a class named "ABC", you're using JDK 8 and you import java.util.*. Now, suppose that Java 9 comes out, and it has a new class in package java.util that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class in java.awt.
You won't have that problem when you import only those classes explicitly from java.awt that you actually use.
Resources:
Java Imports
Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.
For the record:
When you add an import, you are also indicating your dependencies.
You could see quickly what are the dependencies of files (excluding classes of the same namespace).
There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see import ...*.
C# always uses * (implicitly) as you can only using package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic).
In Intellij Idea when you do "organize imports", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).
The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.
Forget about cluttered namespaces... And consider the poor soul who has to read and understand your code on GitHub, in vi, Notepad++, or some other non-IDE text editor.
That person has to painstakingly look up every token that comes from one of the wildcards against all the classes and references in each wildcarded scope... just to figure out what in the heck is going on.
If you're writing code for the compiler only - and you know what you're doing - I'm sure there's no problem with wildcards.
But if other people - including future you - want to quickly make sense of a particular code file on one reading, then explicit references help a lot.
Why is using a wild card with a Java import statement bad?
If you're using an IDE (which you should be doing), and there are more code owners than just you, using wildcard imports is bad because it:
conceals information from the rest of the team
provides only false benefits (things which are better-solved using IDE functionality than with wildcard imports) to you as an individual
Most of the "use wildcards" proponents have a focus on the individual: I don't want to maintain the list, I don't want see the clutter, etc. Here are several of the common examples:
maintenance is harder – when you want to introduce a new class into your source code, you have to manually add the import statement
refactoring is more difficult – if code is moved around, then import statements have to be updated
reduce clutter, tidy up file contents – goal here is something along the lines of "removing distractions"
These arguments were more convincing before IDEs did all of that automatically. If you're using a plain text editor instead of an IDE, then these arguments have some merit. But if you're using a plain text editor, you are already subjecting yourself to a number of other much more significant inefficiencies, and managing import statements is just one among many things that you should stop doing by hand. IDEs offer automatic management of imports, powerful refactoring tools, and folding (hiding) of any parts of the code you don't want to see.
For the "avoid wildcards" proponents, there are many examples, but I'll point out only one:
clarity – specifically, when someone new enters the codebase. They will arrive with questions, and continue to discover new questions as they explore the code. For this new code contributor, wildcard import statements do not answer any questions, and at worst can produce confusion, misunderstanding, new questions. In contrast, with explicit imports (and using an IDE) the worst case is neutral: no new info provided; at best, it not only reduces ambiguity but it can also provide answers.
At the end of the day, it helps the entire team to reduce (albeit in a small way) code complexity, to reduce confusion, to add clarity.
Importing all the classes in a package is considered a blind approach. A major reason for this is that it clutters the class namespace and could lead to conflicts between classes in different packages with the same name.
Specifically populating the necessary classes avoids that problem and clearly shows which versions were wanted. This is good for code maintainability.

Categories

Resources