Practice: predict the output (Java)
Write your answers, then check against the key below.
Q1
int a = 10, b = 4;
System.out.println(a / b);
System.out.println(a % b);
System.out.println((double)(a / b));
System.out.println((double)a / b);
2
2
2.0
2.5
Q2
double d = -2.6;
System.out.println((int)d);
System.out.println((int)(d - 0.5));
System.out.println((int)(-d + 0.5));
-2
-3
3
Q3
int x = Integer.MAX_VALUE;
int y = x + 2;
System.out.println(x);
System.out.println(y);
2147483647
-2147483647
FRQ - style tasks
FRQ 1
Average with correct casting
Write a method avgInt that takes two int values and returns their average as a double, preserving the .5 if present.
public static double avgInt(int a, int b) {
return (double) (a + b) / 2;
}
System.out.println(avgInt(3, 4))
3.5
FRQ 2
Given int correct and int total, compute the percentage as a double from 0.0 to 100.0 without losing fractional precision.
public static double percent(int correct, int total) {
return (double) correct / total * 100.0;
}
System.out.println(percent(3, 5));
60.0
FRQ 3
Implement safeMod(int a, int b) that returns a % b, but if b == 0, it should return 0 instead of throwing.
public static int safeMod(int a, int b) {
if (b == 0) {
return 0;
}
return a % b;
}
System.out.println(safeMod(9, 29))
9