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.
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.
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.
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.
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.
Related
I have a class with an existing import:
import org.packageA.Peeler
public class Potato {
Peeler peeler = new Peeler();
}
I'd like to be able to copy this class or create an object with it but change "import org.packageA.Peeler" to "import org.packZ.Peeler".
Is this possible to do dynamically?
No.
import statements are a bit of a misnomer. import com.foo.A; means: Anytime I write just A in this source file, imagine I wrote com.foo.A and that is all it means. It does not mean: Initialize this class or parse this source file or any other such thing (which is usually what import means in other environments).
Thus, what you're asking is: Can I take class Potato { org.packA.Peeler peeler = new org.packA.Peeler(); } and somehow dynamically create a different Potato class that is as if I wrote class Potato { org.packA.Peeler peeler = new org.packA.Peeler(); } - to which the answer is no; org.packA.Peeler is as related to org.packZ.Peeler as guns and grandmas (i.e.: That they have the same name is immaterial).
Even if you could, what would that mean? Java is statically and nominally typed, it wouldn't be possible to write code that refers to this rewritten potato class without using reflection or dynamic code generation which, in java at any rate, are almost always the wrong answer.
Some exotic options you do have:
Use a regexp or build script plugin to make a source file with some renames applied and include it in the build and compilation process (bad idea, but I guess you can do that)
Use ASM, BCEL or some other classfile tool to create a new class file in byte array form with renames applied, have a custom classloader that dynamically loads this, and then generate bytecode that uses this, or use reflective access. This is extremely convoluted, requires a ton of code, and is almost useless.
Perhaps take a step back and explain the problem you have that made you think: I know! I'll dynamically rewrite this class to use a different package! But I don't know how so I'll ask SO - except you're asking the wrong question, ask about your original problem.
Is there a way to use the standard library class Scanner without an import statement?
My professor is the type to include overly difficult problems that you are not expected to actually complete but aside from decompiling the standard library and adding all of the .java files to the project I am at a bit of a loss.
Edit: to clarify, this is the exact wording of the lab description:
"Use a scanner to get an integer value from the user. Your program may not use any import statements."
Yes. You can fully qualify them on usage:
java.util.Scanner scanner = new java.util.Scanner(System.in);
The import statement is not about the compiler asking where can I find the class?, but rather which class do you mean?
With the import statement you say to the compiler: "Everytime I say Scanner, I actually mean java.util.Scanner. So please save me some typing.
So indeed, as Andreas already mentioned in the comments. import is not necessary, it's just convenience.
Also note that all classes from the java.lang package (for example System in the abovementioned example) are implicitly imported (JLS § 7.3), so you can always use them without an import statement.
Today in private method I used Long.parseLong() (just once in whole class) with some String as value. At peer review colleague wrote that this method should be static import and then called without Long.. I asked why because as I know and what is in https://stackoverflow.com/a/421127/4952262 in such case we should just go with Long.parseLong() instead of trying to save 5 characters. The answer was that parseLong method is just in Java.lang.Long package and it's safe because this method was, is and will be just in this package. Is it good way? Does it really make a code more readable?
It depends how do you infer it, I have read a lot about it that static imports increase the code readability.
But let's think of a scenario where you have two classes namely Class A and B.
Think that both the classes have similar static fields/method that you want to use in some third Class C.
Now how does it increase the readability of code ?
Again i am not arguing where its wrong or correct to use static imports but yes i do believe in some of the cases it sounds good to do so in other it might not.
Note : Anyways it does not make any difference when it comes to performance as much as i know.
I have a small static method mymethod inside a relatively big (library) class com.package.pirulo. I can do one of two things: Either I import com.package.pirulo and then I just use pirulo.mymethod(...), or I can use direclty the method with com.package.pirulo.mymethod(...).
Which is cheaper from a resources/speed point of view? It looks like the second option is cheaper , but since mymethod can call other methods in com.package.pirulo maybe the whole library is always somehow imported anyway...
And: is the first option as expensive (same POV) as instantiating a pirulo object?
Importing makes absolutely no difference at runtime, and only a negligible (at most) difference at compile-time.
There is no difference in performance with calling a static import vs using a fully qualified name.
There is very little difference between the two different methods of importing.
There are probably very few cases were you should really worry that much about object creation.
In the extreme micromanagement perspective, it is better to not make an object, but its not noticable typically.
Import the class you need to use from the package.
The only time when you import a single method is on static imports, which no, don't save you time, and if they do, it's negligible, and you shouldn't be doing it for that reason anyway.
That said, sometimes static imports improve readability. For example, java.lang.String.format.
The import statements only make code readable and easy to be written. After code has been compiled, all the references are replaced by fully qualified name and unused imports are ignored. String s;" will become java.lang.String s; automatically so its does not matter.
Recently i cam across a statements :
import static java.lang.System.out;
import static java.lang.System.exit;
I read these statements in some tutorial. Are these statements O.K ?
If the statements are alright what do they mean and should they be used regularly while writing code ?
They are called static imports. The effect is to allow you to use the names out and exit in your program as if they were defined in the current scope; so you can write exit(0) instead of System.exit(0).
Now, are they a good idea? Sometimes, when used sparingly, they are a good way to reduce clutter. But most of the time, they actually just make your code harder to understand. The reader will ask "Where is this out defined?" and "Where does exit() come from?" In general, you should avoid them.
But if you're writing a class that's all about processing SomeReallyLongName objects, and SomeReallyLongName defines a bunch of FINAL_CONSTANTS, importing them with static imports will save a lot of typing and a lot of clutter, and it will be pretty clear where those constants are coming from.
They are static imports. It allows you to do something like exit(0) instead of System.exit(0).
I do not recommend this for well known Java classes because it can be confusing to some. But sometimes it is useful for utility classes like Guava.
Iterables.filter(list, SomeClass.class)
is very verbose but you can make it easier to read with static imports: filter(list, SomeClass.class)
You should check with your team to see what they code guidelines are and try to be consistent.
Yes,it is perfectly alright .
This is known as static import.This allows members defined in class as static and
public to be used without specifying the class in which the field is defined.
This feature was defined in J2SE 5.0.
For example :
import static java.lang.Math.*;
import static java.lang.System.out;
// in main
out.print( max(100,200) ); // prints 200.You didn't have to use Math.max(.,.)
I think it may not be a good idea to use static imports as it'll make your code hard to read.
Yes, these statements are referred to as static imports and are perfectly valid. Take a look at the javase guide on static imports for more information.
With respect to usage, the guide states:
So when should you use static import? Very sparingly! Only use it when
you'd otherwise be tempted to declare local copies of constants, or to
abuse inheritance (the Constant Interface Antipattern). In other
words, use it when you require frequent access to static members from
one or two classes. If you overuse the static import feature, it can
make your program unreadable and unmaintainable, polluting its
namespace with all the static members you import. Readers of your code
(including you, a few months after you wrote it) will not know which
class a static member comes from. Importing all of the static members
from a class can be particularly harmful to readability; if you need
only one or two members, import them individually. Used appropriately,
static import can make your program more readable, by removing the
boilerplate of repetition of class names.
Static imports are a new feature added in Java 1.5
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually
There is nothing wrong with your example if you want easy access to out and exit so that you can call them directly as out.println() for example. There is nothing syntactically incorrect about it nor from a style aspect though some may argue it is "confusing" and hard to figure out where out came from, but any modern IDE can help them figure that out.
These are static import concept.These are like simple imports but having different type of concept.See here you import one function exit() and one field out and both are static in their corresponding classes(in case both here Systen is their class).After this instead of writing System.out.println() you can simply write out.println().Similarly instead of System.exit(),you can write exit().