Giriş
Metodlar şöyle.
addExact metodu
Şöyle yaparız.
Metodlar şöyle.
Math.addExact(int x, int y);
Math.subtractExact(int x, int y);
Math.multiplyExact(int x, int y);
Math.incrementExact(int a);
Math.decrementExact(int a);
Math.negateExact(int a);
Math.toIntExact(long value);
Açıklaması şöyleThe methods will throw an ArithmeticException if overflow would have occurred.
absExact metodu
Açıklaması şöyle
absExact() is similar to the abs() function in the Math class; it returns the absolute value of a number, which is the positive value of a number regardless of its sign.
However, the difference is that it only does so if it is exactly representable as its data type (int or long).
If the resulting return value overflows the original data type, an ArithmeticException is thrown.
Örnek
Şöyle yaparız
System.out.println(Math.absExact(-11));
// Output: 11
Şöyle yaparız.
public int distanceTo(Point that) throws ArithmeticException {
int distanceX = Math.subtractExact(this.x, that.x);
int distanceY = Math.subtractExact(this.y, that.y);
return (int) Math.sqrt(Math.addExact(Math.multiplyExact(distanceX, distanceX),
Math.multiplyExact(distanceY, distanceY)));
}
decrementExact metoduAçıklaması şöyle
decrementExact() is a basic function in java from the Math class that decrements/subtracts the given argument (a number) by one, and returns the result. This function is the opposite of the incrementExact() function.
If the argument given is 11, then the result would be 10.
If decrementing the argument overflows its data type, an exception is thrown. Therefore, it is important to be careful when using this function, especially for larger numbers. Usually, integers are used for this function.
Örnek
Şöyle yaparız
System.out.println(Math.decrementExact(11));
// Output: 10
toIntExact metodu
Long değeri int'e çevirir. Taşma varsa exception fırlatır.Şöyle yaparız.
Long değeri int'e çevirir. Taşma varsa exception fırlatır.Şöyle yaparız.
final static List<String> friends = Arrays.asList("Brian", "Nate", "Neal");
public static int countFriendsStartWithN() {
return Math.toIntExact(friends
.stream()
.filter(name -> name.startsWith("N"))
.count());
}
Hiç yorum yok:
Yorum Gönder