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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With