Just to know. Which is the proper way of ordering import statements? Also which has more readability?
like,
java.util.List
) and then internal packageThanks in advance.
An import statement tells the compiler the path of a class or the entire package. It is unlike “#include” in C++, which includes the entire code in the program. Import statement tells the compiler that we want to use a class (or classes) that is defined under a package.
In Java, the import statement is written directly after the package statement (if it exists) and before the class definition.
You can only have one import statement in a source file.
Press Ctrl+Alt+S to open the IDE settings and select Tools | Actions on Save. Enable the Optimize imports option. Additionally, from the All file types list, select the types of files in which you want to optimize imports. Apply the changes and close the dialog.
From the Java Programming Style Guidelines
The import statements must follow the package statement. import statements should be sorted with the most fundamental packages first, and grouped with associated packages together and one blank line between groups.
..... .....
The import statement location is enforced by the Java language. The sorting makes it simple to browse the list when there are many imports, and it makes it easy to determine the dependiencies of the present package The grouping reduce complexity by collapsing related information into a common unit.
Refere the Java Tutorial link for more info.
Most preferred, and used in most IDE, is alphabetical ordering, starting from domain level and a fully qualified class name.
java.*
and javax.*
takes precedence, and the rest are ordered.
Example:
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import com.neurologic.http.HttpClient;
import com.neurologic.http.impl.ApacheHttpClient;
Im not sure if there is a standard. But some projects such like android use the following rule.
Each group is seperated by an extra line. And each group has their imports in alphabetical order.
AFAIK these are based on our preference.
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