Davis Rash
Davis Rash

Reputation: 123

What is more efficient in importing in Java?

I am a novice high school Java programmer and I am having an internal conflict as to which of the following methods is more efficient in Java. If you are importing a single class in Java, is it more efficient to import it as per usual, e.g., import java.util.Scanner; or to use that import statement as part of the Scanner's declaration, as in java.util.Scanner scan = new java.util.Scanner(System.in);.

I know the first is more common and looks nicer, but what if you only need one scanner object? I am sorry if this question is a duplicate; I did not know how to properly word this question in my searches to see if it already existed.

Upvotes: 0

Views: 265

Answers (4)

Jed Schaaf
Jed Schaaf

Reputation: 1085

The efficiency lies in how often you might need to write out the package/class/symbol path to the type. If you are certain that you will use it only once, not using an import would work.

But, that is the only upside. There are multiple downsides to avoiding an import statement, including readability, ease of seeing which classes are used in this code file, and extra typing if adding more references becomes necessary. The compiler is completely neutral in all of it, as source either way will compile to the same JVM code.

Upvotes: 0

aaray
aaray

Reputation: 41

Pick the more readable of the two. There is no difference in performance, at the end of the day they both get compiled to exactly the same bytecode.

Upvotes: 0

XeroG
XeroG

Reputation: 37

There is no added expense to importing a class, so it makes sense to put all of your imports in the header where anyone looking at your code can easily see what classes are utilized in the program. If you decide later that you want to have more than one scanner object or more than one class from java.util you can use import java.util.* as well.

Upvotes: 0

jkinkead
jkinkead

Reputation: 4411

import statements create a compiler-time alias to the symbol imported. That is, it's just a shortcut for typing the full name out - it has no effect on the program while it's running. The compiled code is identical in both cases.

Upvotes: 4

Related Questions