2pts The following piece of code is intended to protect z ag
[2pts] The following piece of code is intended to protect z against integer overflow.
Put this piece of code into a java program and test it.
a.) [1pt] When you run it with values x=250100 and y=340200, what do you see as
output?
b.) [1pt] Find out what can be done to provide such protection in Java 8.
static boolean multiply (int x, int y) int z System. out println (\"x x and y y) if (x y> Integer .MIN VALUE && x ySolution
a) The code when tested in java prints the wrong value of x*y for the values x=250100 and y=340200 as due to small size allocated to int, it wraps to the small nearest value
b) Java 8 provides this new feature of integer overflow protection
java.lang.math package in java 8 provides new methods such as addExact() and multiplyExact() which would give either the exact values of the operation if within the range or would throw an ArithmeticException.
I am giving an example for better understanding:
public class OverflowTest
{
public static void main(String[] args)
{
int a = Integer.MAX_VALUE;
int b = Integer.MAX_VALUE;
try
{
int c = Math.addExact(a, b);
System.out.println(a + \" + \" + b + \" = \" + c);
}
catch (ArithmeticException ex)
{
System.err.println(\"int is too small, falling back to long.\");
long c = (long) a + (long) b;
System.out.println(a + \" + \" + b + \" = \" + c);
}
}
}
This is the console:
$ javac OverflowTest.java
$ java OverflowTest
int is too small, falling back to long.
2147483647 + 2147483647 = 4294967294
![[2pts] The following piece of code is intended to protect z against integer overflow. Put this piece of code into a java program and test it. a.) [1pt] When you [2pts] The following piece of code is intended to protect z against integer overflow. Put this piece of code into a java program and test it. a.) [1pt] When you](/WebImages/47/2pts-the-following-piece-of-code-is-intended-to-protect-z-ag-1147692-1761617275-0.webp)
![[2pts] The following piece of code is intended to protect z against integer overflow. Put this piece of code into a java program and test it. a.) [1pt] When you [2pts] The following piece of code is intended to protect z against integer overflow. Put this piece of code into a java program and test it. a.) [1pt] When you](/WebImages/47/2pts-the-following-piece-of-code-is-intended-to-protect-z-ag-1147692-1761617275-1.webp)