javaimportstatic-import

java.lang.Math.abs not imported by default?


I'm studying for a beginners Java Exam through Oracle.

One of the questions says given:

int absoluteValue = abs(-21)

What import statement will compile all the code?

Correct answer given as:

import static java.lang.Math.abs;

But my question is if java.lang.* is imported by default then why is the Math class not imported and the abs() method not available?


Solution

  • But my question is if java.lang.* is imported by default then why is the Math class not imported and the abs method not available?

    Because it isn't.

    Because that is the way that Java works. An implicit (or explicit) wildcard import of the classes in a package only imports the classes. It doesn't also do a static import of class members.

    If you want to refer to all static members of a class without qualifying them, you should use a wildcard static import; e.g.

    import static java.lang.Math.*;
    

    Alternatively you can static import individual members; e.g.

    import static java.lang.Math.abs;
    

    Why did they define Java this way?

    Well it is most likely rationale is that implicit importing makes it harder to read code. If methods like abs get imported by default, then you need to know what they all are ... and where they are imported from ... in order to understand the true meaning of the code.

    It is worth knowing that static imports were only added in Java 5. Prior to that, it was not possible to refer to Math.abs without the Math qualification.


    If you just import the class not its static members then what are you getting when you import it?

    You just get the class name. For example:

    import java.util.HashMap;
    

    allows me to write new HashMap() rather than new java.util.HashMap() etcetera. This is significant. (Imagine if you always had to refer to classes by their full name ....)