Christian
Christian

Reputation: 1411

Why won't abs() in java work?

I have always had a question about java.lang.Math: (It might by very basic)

Why do I have to Math.abs(-100) and can't to abs(-100)?

I figure that Math is a class. And abs is a static method. But why can I not simply import java.lang.Math and use abs(-100)?

Upvotes: 1

Views: 897

Answers (4)

Manu
Manu

Reputation: 89

As you know everything in java is within the class. So their can be only two alternatives.

Static Function and Non Static Function

And java.lang.Math is a utility library. Creating object of this is not worth for you. so Java guys created all the functions static in this library.

And for your question you can call a member function directly if and only if they are member of same class.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500595

You can import all the methods in Math:

import static java.lang.Math.*;

or just the one method you want:

import static java.lang.Math.abs;

Normal imports just import classes, making that class available via its short name.

Upvotes: 8

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

abs is a static method and in order the compiler knows where it's defined, you have to specify the class (in your case - Math).

Note that you could do a static import on Math.abs and then you'd be able to just do abs(-100) instead of Math.abs(-100). In this case you'll have to add an import statement like this one:

import static java.lang.Math.abs;

Note also that in Java, unlike JavaScript and PHP, there aren't any public functions, which is why import statements are important.

Upvotes: 3

user
user

Reputation: 745

java.lang.Math is statically imported in every Java Class.

static import java.lang.Math;

Every class of the java.lang package is imported that way.

Upvotes: 1

Related Questions