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):
| Type | Size | Range / note |
|---|---|---|
| byte | 8 bit | -128 to 127 |
| short | 16 bit | -32768 to 32767 |
| int | 32 bit | -2147483648 to 2147483647 |
| long | 64 bit | up to 9223372036854775807 (suffix L) |
| float / double | 32 / 64 bit | decimals (f suffix for float) |
| char | 16 bit unsigned | 0 to 65535, Unicode |
| boolean | JVM-dependent | true / 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 + 1overflows silently to -2147483648.1 << 31is -2147483648 as anintbut1L << 31is 2147483648.5 / 0throwsArithmeticException: / by zero;5.0 / 0isInfinity.0.1 + 0.2prints 0.30000000000000004, so0.1 + 0.2 == 0.3is false.'a' + 1is the int 98;(char)('a' + 1)is 'b'."1" + 2 + 3is "123" but1 + 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
What is the value of 7 / 2 in Java when both operands are int?
- 3
- 3.0
- 3.5
- 4
Show the answer
A. Integer division truncates the fraction: 3.
int x = 5; int y = x++ + ++x; What are y and x afterwards?
- y = 12, x = 6
- y = 11, x = 6
- y = 12, x = 7
- y = 10, x = 7
Show the answer
C. x++ yields 5 (x becomes 6), ++x yields 7: 12 7.