Reputation:
Is there a way to simplify this piece of code further? The codes aim is to return an absolute value given an integer.
public class Abs {
public static int abs(int x) {
if(x < 0) { return -x; }
if(x >= 0) { return x; }
assert false;
return 0;
}
}
Upvotes: 0
Views: 109
Reputation: 3302
You can use the ternary operator to simplify the code
public class Abs {
public static int abs(int x) {
return x < 0 ? -x : x;
}
}
Upvotes: 0
Reputation: 48
You could put this in an integer and check the condition when you assign a value.
int y = x < 0 ? -x : x;
Or in a method:
public static int abs(int x) {
return x < 0 ? -x : x;
}
The "assert false" will never be reached, so it is useless.
Upvotes: 1