3.2 Primitive Casting, Numeric Promotion & final Constants
Key Takeaways
Implicit widening flows along byte -> short -> int -> long -> float -> double, and char -> int -> long -> float -> double; byte/short and char never widen to each other
Java allows implicit narrowing to byte, short, or char only when the right-hand side is a compile-time constant expression (of type byte, short, char, or int) whose value fits the target range
An integer narrowing cast keeps the target type’s low bits, so
(byte) 200is-56. Casting a finite floating-point value tointtruncates toward zero and saturates outside theintrange.In binary numeric promotion, the common type is
double,float,long, orint, in that priority. Compound assignment converts the result back to the left-hand type.A final variable can be assigned once (including blank final fields in constructors or static blocks), whereas const is a reserved but unused keyword that fails compilation
Implicit Widening Conversions
When assigning a smaller primitive type to a larger primitive type, Java performs an implicit widening conversion automatically when allowed by the widening conversion rules. A widening conversion to floating point can lose precision.
The two widening paths are:
byteshortintlongfloatdoublecharintlongfloatdouble
Notice three crucial exam details in these paths:
byteandshortdo NOT widen tochar, andchardoes NOT widen toshort. Becausebyteandshortare signed (capable of holding negatives) whilecharis unsigned (0..65535), signedbyteandshortinclude negative values. Thecharrange also extends beyondshort’s upper bound. Writingchar c = 'A'; short s = c;orbyte b = 10; char c = b;fails to compile.intfloat,longfloat, andlongdoubleare widening conversions even though they can lose low-order precision (floathas 24 bits of significand;doublehas 53 bits). Java permitsfloat f = 1234567890L;without a cast.booleannever widens or narrows to or from any numeric type.
Compile-Time Constant Narrowing
Normally, assigning an int expression to a byte, short, or char requires an explicit cast because int is wider. Java makes one heavily tested exception (JLS Section 5.2): implicit narrowing is permitted when:
- The target variable has type
byte,short, orchar(notlong,float, ordouble), and - The source expression is a compile-time constant expression of type
byte,short,char, orint, and - Its value fits within the target type's range. Assignment can also narrow then box the constant for
Byte,Short, orCharacter, as inByte level = 12;.
byte b1 = 127; // OK: 127 is an int constant fitting in -128..127
// byte b2 = 130; // COMPILE ERROR: 130 exceeds byte max 127
short s1 = 'Z'; // OK: 'Z' is char constant 90, fits in short
char c1 = 65535; // OK: fits in 0..65535
// char c2 = -1; // COMPILE ERROR: -1 is outside 0..65535
int x = 10;
// byte b3 = x; // COMPILE ERROR: x is not a compile-time constant
final int fx = 10;
byte b4 = fx; // OK: final + literal initializer = constant expression
final int blank;
blank = 10;
// byte b5 = blank; // COMPILE ERROR: blank final is NOT a constant expression
final long fl = 10L;
// byte b6 = fl; // COMPILE ERROR: long constants never implicitly narrow
Tip
Remember the blank final trap: final int blank; blank = 10; cannot be reassigned, but it is not a compile-time constant expression, so byte b = blank; fails compilation.
Explicit Narrowing Casts & Two's-Complement Truncation
To force a wider value into a narrower primitive type when implicit conversion is disallowed, place (targetType) before the expression. For integer-to-integer narrowing, Java keeps the lowest bits and discards all higher bits—meaning overflow wraps silently using two's-complement arithmetic rather than throwing an exception.
Let us trace byte b = (byte) 200; bit by bit:
200as a 32-bitintis00000000 00000000 00000000 11001000().- Casting to
bytekeeps only the lowest 8 bits:11001000. - Because the most significant bit is
1, this 8-bit two's-complement pattern represents a negative number: .
Casting a finite, in-range floating-point number to int truncates toward zero. For example, (int) 3.9 is 3 and (int) -3.9 is -3. A conversion to int or long yields zero for NaN and clamps out-of-range values to the nearest limit. For byte, short, or char, Java first converts to int and then narrows again. Note also that the cast operator has higher precedence than binary arithmetic: (byte) 200 + 1 casts 200 to -56 first and then adds 1, producing an int result of -55.
Unary and Binary Numeric Promotion
Whenever Java evaluates arithmetic, relational, or bitwise operators on primitives, it applies strict numeric promotion rules before executing the operation:
- Unary numeric promotion (used by unary
+,-,~, each shift operand independently, and array index expressions): promotesbyte,short, andcharoperands toint. - Binary numeric promotion (used by
*,/,%,+,-,<,<=,>,>=,==,!=,&,^,|): unboxes wrappers when required, then converts to the first type from this list that either operand has:double,float,long. With none of those types, both operands becomeint. This applies only to numeric forms of the listed operators.
byte a = 10, b = 20;
// byte sum = a + b; // COMPILE ERROR: a + b is promoted to int
byte sum = (byte) (a + b);// OK: explicit cast handles int result
byte neg = 5;
// byte r = -neg; // COMPILE ERROR: unary minus promotes neg to int
char ch = 'A'; // 65
int next = ch + 1; // OK: 66 (char promotes to int)
// char cNext = ch + 1; // COMPILE ERROR: int cannot assign to char
int p = 5, q = 2;
double wrong = p / q; // 2.0 (int / int = 2, then widened to 2.0)
double right = (double) p / q; // 2.5 (double / int promotes q to double)
Compound Assignment and Increment
Compound assignment converts the operator result back to the variable’s type. E1 op= E2 behaves like E1 = (TypeOfE1) (E1 op E2), with E1 evaluated only once. Increment and decrement also convert their result back before storing it. Postfix returns the old value, while prefix returns the updated value.
byte x = 10;
x += 5; // Compiles! Equivalent to x = (byte) (x + 5) -> 15
x += 200; // Compiles! (byte) (15 + 200) = (byte) 215 -> -41
short s = 5;
s *= 2.5; // Compiles! (short) (5 * 2.5) = (short) 12.5 -> 12
final Primitives, Blank final Fields & const
Marking a primitive variable final ensures it can be assigned at most once:
- Blank
finallocal variable: May be declared without an initializer (final int rate;) and assigned later, provided it is definitely assigned before being read and never assigned twice. - Blank
finalinstance field: Must be definitely assigned either in an instance initializer block{ ... }or in every constructor of the class; a constructor path that can finish normally must definitely assign the field. - Blank
finalstatic field: Must be assigned in astatic { ... }initializer block if not initialized at declaration. constkeyword:const(likegoto) is a reserved keyword in Java with no implementation. Writingconst int MAX = 10;is always a compile-time error; constants in Java usefinal(and typicallystatic final).
Which lines follow Java SE 8 compile-time rules? Treat an invalid line as a separate error and assess the other lines in order.
byte b1 = 100; // Line 1
final int k = 50; // Line 2
byte b2 = k; // Line 3
byte b3 = b1 + 1; // Line 4
b1 += 200; // Line 5
Lines 1, 2, 3, and 4 only
Lines 1, 2, 3, and 5 only
Lines 1, 2, and 5 only
All five lines compile
What does the following code print?
int value = 200;
byte truncated = (byte) value;
int a = 5, b = 2;
double ratio = a / b;
System.out.println(truncated + " " + ratio);
200 2.5
-56 2.5
127 2.0
-56 2.0
Which statement about final, blank final, and const in Java SE 8 is accurate?
A blank final instance field must be assigned either in an instance initializer or in every constructor
The const keyword declares a compile-time numeric constant equivalent to static final
A blank final local variable automatically receives a default value of 0 if left unassigned
Any final long variable initialized to 5L can be assigned directly to a byte without casting
Sections you finish are checked off in the contents.