2

I was just curious which is the preferred way of coding as I've seen code written both of these ways.

import java.util.ArrayList;
import java.util.List;
 /**
 *Rest of code
 */
 List<Blah> blahs = new ArrayList();

or

import java.util.List;
 /**
 *Rest of code
 */
 List<Blah> blahs = new java.util.ArrayList();

So, which is preferred and why? What are the advantages & disadvantages of both methods? Just curious.

Skylion
  • 2,696
  • 26
  • 50
  • The only difference is readability (it makes no significant difference for the compiler and will lead to the same bytecode). So whichever you feel is more readable. IMO: option 1. – assylias Aug 31 '13 at 19:31

3 Answers3

5

So, which is preferred and why?

First one should be prefered. Code clarity is the most important concern.

What are the advantages & disadvantages of both methods?

Well, compiler will anyway convert the first approach to the later one, by replacing all the classes and types, with their fully qualified names. Both the codes would lead to the same byte code. As such you should really not bother about these stuffs. (You can check the byte code by running javap command)

The only reason you would use the fully qualified name is to resolve name clashes in different packages that you have imported. For e.g., if you are importing both java.util.* and java.sql.*, then you would need to use fully qualified name of Date class.

Related post:

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3
  • Fully-qualified names are preffered when you have several classes with the same simple name.

  • In all the other cases, the preffered and easy-to-read approach would be importing the fully-quallified name and using the simple class names.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

Probably the former because the latter looks kind of obscure. You should only use the latter (specifying package names before classes) if you are using multiple classes found in different packages.

Josh M
  • 11,611
  • 7
  • 39
  • 49