1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 1

CAP477 · Unit 1: Java fundamentals

Data types, casting and operators

9 practice questions

Key points

  • Eight primitives; int is 32 bit, long 64 bit, char 16 bit unsigned
  • Narrowing needs a cast and truncates or wraps
  • Integer division truncates; int overflow wraps silently
  • && and || short-circuit, & and | do not

Primitive types (8):

TypeSizeRange / note
byte8 bit-128 to 127
short16 bit-32768 to 32767
int32 bit-2147483648 to 2147483647
long64 bitup to 9223372036854775807 (suffix L)
float / double32 / 64 bitdecimals (f suffix for float)
char16 bit unsigned0 to 65535, Unicode
booleanJVM-dependenttrue / false

Casting: widening (int -> long -> float -> double) is automatic; narrowing needs an explicit cast and may lose data: (int) 3.9 is 3, (int) -3.9 is -3 (truncation toward zero), (byte) 130 is -126.

Arithmetic facts (verified by running):

  • Integer division truncates: 7 / 2 = 3, 7 % 3 = 1, 7 / 2.0 = 3.5.
  • Integer.MAX_VALUE + 1 overflows silently to -2147483648. 1 << 31 is -2147483648 as an int but 1L << 31 is 2147483648.
  • 5 / 0 throws ArithmeticException: / by zero; 5.0 / 0 is Infinity.
  • 0.1 + 0.2 prints 0.30000000000000004, so 0.1 + 0.2 == 0.3 is false.
  • 'a' + 1 is the int 98; (char)('a' + 1) is 'b'. "1" + 2 + 3 is "123" but 1 + 2 + "3" is "33".
  • short s = 10; s += 5; compiles (compound assignment casts back).

Operators: && and || short-circuit; & and | always evaluate both sides. x++ + ++x with x = 5 gives 12 and x becomes 7. Bitwise: 5 & 3 = 1, 5 | 3 = 7, 5 ^ 3 = 6, ~5 = -6, -16 >> 2 = -4. Ternary: cond ? a : b.

Exam pitfall: float f = 1.1; is a compile error because 1.1 is a double.

Try two questions

Question 1 · Tier 1, Recall

What is the value of 7 / 2 in Java when both operands are int?

  1. 3
  2. 3.0
  3. 3.5
  4. 4
Show the answer

A. Integer division truncates the fraction: 3.

Question 2 · Tier 3, Apply

int x = 5; int y = x++ + ++x; What are y and x afterwards?

  1. y = 12, x = 6
  2. y = 11, x = 6
  3. y = 12, x = 7
  4. y = 10, x = 7
Show the answer

C. x++ yields 5 (x becomes 6), ++x yields 7: 12 7.