Skip to the content.

Casting and Range of Variables

Student Teaching Lesson

Practice Quiz

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

Q1

double x = 7.9;
int y = (int) x;
System.out.println(y);
7

Answer: C (7)

Q2

int a = 10;
double b = 5.5;

int c = a + b;
int c = (int)(a + b);
int c = a + (int)b;
|   int c = a + b;

incompatible types: possible lossy conversion from double to int

Answer: A (int c = a + b);

because b is a double and you can’t asign a double to init without an error so its the only one that will compile with an error

Q3

int num = 9 / 2;
System.out.println(num);
4

Answer: B (4)

Q4

double d = 15.7;
int i = (int)(d + 0.5);
System.out.println(i)
16

Answer: B (16)

Q5

Answer: B (Casting from double to int requires explicit casting)

Because in java casting from double to int is a shrinking conversion because you’re going from a larger more precise number (doubles have variables) to a smaller, less precise type (Int has whole numbers)