what do these statements mean and is this style recommended ? - java

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().

Related

Primitive function in JAVA [duplicate]

I'm mostly a c/C++/objective-C programmer, presently working in Java on an android application. My question is simple: I want a utility function, preferably not associated with any class that I can invoke from anywhere in my project (#include of some sort necessary?).
I know I can make a public static function of a class and invoke it as Class.someFunction();. I would like to just have someFunction(); I'm not sure if this is possible in java, or what the syntax for it is.
You can achieve the same "effect" by using a static import, by adding the following import in each file that you want to use it in:
import static x.y.Class.someFunction; // or x.y.Class.*;
...
// some code somewhere in the same file
someFunction();
However, all methods in Java must be part of a class. Static imports just let you pretend (briefly) otherwise.
P.S. This also works for static fields.
You could use a static import:
import static com.example.MyUtilityClass.*; // makes all class methods available
// or
import static com.example.MyUtilityClass.myMethod; // makes specified method available
You don't see this used very often because, if overused, it causes harder-to-debug code (see the last paragraph at the link above).
Here's a related question about when it's advisable to use this.
Also, following the programming best practices, You should define all such common, frequently used functionality in some utility class where you can define your functions or fields(probably constants- i.e. static and final attributes) that is going to be used/called at different places within the API.
Although, you still need to import the Utility class.
Else define such functionality in the top most parent class in your API hierarchy structure, that way you even don't have to import the class.
Hope this helps.
thanks....!!!
Yeap import static..
For instance:
import static java.lang.Math.max; // Allowing to use max method anywhere in the source
class SomeClass {
int m = max( 1, 2 );// m now is 2 due t Math.max( int, int )
}

Static import Long.parseLong in Java

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.

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.
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.

Is using a static method cheaper than importing the whole class?

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.

Correct use of static imports in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is a good use case for static import of methods?
I rarely ever see a static import in java like this:
import static java.lang.Math.*;
Then you could access PI without having to call Math.PI.
Since you don't see this that often, does that mean it is a bad design to do this?
I prefer not to use them, simply because I want to see where each constant is defined. If your classes and your constants are named appropriately, it helps readability a lot.
Then again, if you're using a lot of constants from the same class and it's obvious where they come from, you're better off with a wildcard import.
It is not bad design, but in my opinion Math.PI is clearer for maintaneinance than just PI.
Sometimes yes. When you use a static import, the fields and methods from the class you statically imported might "look like" they come from your class.
This does impact understandability, IMHO.
That said, I use it all the time in JUnit tests!
It's not bad. It's just usually not necessary. I personally use it whenever my program uses a lot of calls to java.lang.Math.
Most people also don't know about it since it's so infrequently used. Same thing goes to other constructs like static constructors.
Math was around before import static which is why most developers would tend to use the older form.

Categories

Resources