Метод StrictMath toIntExact () в Java с примерами
Java.lang.StrictMath.toIntExact () - это встроенный в Java метод, используемый для возврата значения длинного аргумента. Если результат превышает int, он вызовет исключение. Создание объекта не является обязательным, поскольку toIntExact (длинное число) статично.
Синтаксис:
общедоступный статический int toIntExact (длинное число)
Параметры: метод принимает один параметр num длинного типа, значение int которого возвращается.
Возвращаемое значение: метод возвращает аргумент как int.
Исключение: если аргумент переполняет int, он вызывает ArithmeticException .
Примеры:
Ввод: число = 2727 л. Выход: 2727 Ввод: число = -86262l Выход: -86262
Ниже программы иллюстрируют метод java.lang.StrictMath.toIntExact ():
Program 1:
// Java program to demonstrate working // of java.lang.StrictMath.toIntExact() method import java.lang.StrictMath; class Geeks { // driver code public static void main(String args[]) { // Get the long value // whose IntExact value is needed long num = 266526l; // Get the IntExact value // using toIntExact() method int intvalue = StrictMath.toIntExact(num); // Print the IntExact value System.out.print( "IntExact value of " + num + " = " + intvalue); } } |
IntExact value of 266526 = 266526
Program 2:
// Java program to demonstrate working // of java.lang.StrictMath.toIntExact() method import java.lang.StrictMath; class Geeks { // driver code public static void main(String args[]) { // Get the long value // whose IntExact value is needed long num = -7226526l; // Get the IntExact value // using toIntExact() method int intvalue = StrictMath.toIntExact(num); // Print the IntExact value System.out.print( "IntExact value of " + num + " = " + intvalue); } } |
IntExact value of -7226526 = -7226526
Program 3: To demonstrate ArithmeticException
// Java program to demonstrate working // of java.lang.StrictMath.toIntExact() method import java.lang.StrictMath; class Geeks { // driver code public static void main(String args[]) { try { // Get the long value // whose IntExact value is needed long num = 654456645546l; System.out.println( "Trying to get " + "IntExact value of: " + num); // Get the IntExact value // using toIntExact() method int intvalue = StrictMath.toIntExact(num); // Print the IntExact value System.out.print( "IntExact value of " + num + " = " + intvalue); } catch (Exception e) { System.out.println( "Exception throwm: " + e); } } } |
Trying to get IntExact value of: 654456645546 Exception throwm: java.lang.ArithmeticException: integer overflow
Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .