Type Casting (Widening & Narrowing), Type Promotion, Wrapper Classes & Autoboxing
new Integer(10) were deprecated in JDK 9 in favor of Integer.valueOf(10) or autoboxing (Integer x = 10;).1. Topic Introduction
Frequently, programs need to mix data types—say storing an int inside a double, squeezing a double into an int, or storing primitive numbers inside collections like Vector or ArrayList that only accept objects. Java solves this cleanly with two mechanisms: Type Casting (Widening/Narrowing) and Wrapper Classes (Autoboxing/Unboxing).
Widening is pouring water from a small teacup (int) into a big bucket (double)—nothing spills, so Java does it automatically! Narrowing is pouring a bucket (double) into a small cup (int)—water (decimal digits) might spill, so Java refuses unless you explicitly write (int) to take responsibility. Meanwhile, Wrapper Classes are gift boxes: Java's collections (Vector, ArrayList) only accept gift-wrapped Objects, not bare primitives. Autoboxing is Java automatically putting your int into an Integer box for you!
(type) cast, may lose data). Autoboxing = int -> Integer; Unboxing = Integer -> int.3. Essential Exam Definitions
byte -> short -> int -> long -> float -> double, and char -> int) without data loss.(targetType) value) required when precision or range may be lost (truncation).java.lang (Byte, Short, Integer, Long, Float, Double, Character, Boolean) that encapsulates a primitive value into an immutable object.javac between a primitive type and its corresponding wrapper class (int <-> Integer).4. Detailed Technical Explanation & Syntax
1. Widening vs Narrowing & Expression Type Promotion Rules
Java performs automatic widening whenever the target type is larger and compatible: byte -> short -> int -> long -> float -> double (and char -> int -> ...). Note that byte and short do NOT automatically convert to char (since char is unsigned 0..65535), and boolean never converts to any numeric type.
In mixed-type arithmetic expressions (Type Promotion Rule), Java automatically promotes operands before computing:
- Rule 1: All
byte,short, andcharoperands are ALWAYS promoted tointin expressions (sobyte b = 10; b = b * 2;is a compile error without(byte)(b * 2)!). - Rule 2: If one operand is
long, the entire expression promotes tolong. - Rule 3: If one operand is
float, the expression promotes tofloat. - Rule 4: If any operand is
double, the entire expression promotes todouble. - Narrowing Syntax:
int i = (int) 9.87;truncates fractional.87and stores9.
2. Wrapper Classes & Hierarchy
All six numeric wrapper classes (Byte, Short, Integer, Long, Float, Double) extend the abstract class java.lang.Number. Character and Boolean extend java.lang.Object directly.
Why are Wrapper Classes needed? (1) Collections (Vector, ArrayList, HashMap) store Objects only, not primitives; (2) Utility methods convert Strings to primitives (Integer.parseInt("42"), Double.parseDouble("3.14")) or format bases (Integer.toBinaryString(10)); (3) Wrapper variables can hold null to represent missing data.
3. Autoboxing & Unboxing Internals
Since Java 5, you can write Integer obj = 25; instead of Integer obj = Integer.valueOf(25); (Autoboxing) and int n = obj; instead of int n = obj.intValue(); (Unboxing).
Beware a classic exam trap: unboxing a null wrapper (Integer x = null; int y = x;) compiles cleanly but throws NullPointerException at runtime!
5. Working Principle: How Autoboxing & Expression Promotion Operate at Compile Time
- When writing
Integer num = 10;, the compiler silently rewrites it intoInteger.valueOf(10). - When arithmetic runs on
num + 5, the compiler insertsnum.intValue() + 5(unboxing), computes15, and if assigned back to anInteger, autoboxes15again. - When writing
byte a = 50; byte b = (byte)(a * 2);,a * 2first widensatoint, producesint 100, and(byte)narrows it back cleanly.
7. Complete Java Code Examples & Tracing
| 1 | import java.util.ArrayList; |
| 2 | |
| 3 | public class CastingAndWrapperDemo { |
| 4 | public static void main(String[] args) { |
| 5 | // 1. Widening (Implicit) |
| 6 | int num = 25; |
| 7 | double wideDouble = num; // int -> double automatically |
| 8 | System.out.println("Widened double: " + wideDouble); |
| 9 | |
| 10 | // 2. Narrowing (Explicit with truncation) |
| 11 | double pi = 3.99; |
| 12 | int truncated = (int) pi; // Fractional part .99 is truncated |
| 13 | System.out.println("Narrowed int from 3.99: " + truncated); |
| 14 | |
| 15 | // 3. Expression Type Promotion |
| 16 | byte b1 = 40, b2 = 50; |
| 17 | // byte b3 = b1 + b2; // COMPILE ERROR: b1 + b2 promotes to int! |
| 18 | byte b3 = (byte) (b1 + b2); |
| 19 | System.out.println("Promoted & cast byte sum: " + b3); |
| 20 | |
| 21 | // 4. Wrapper Utility + Autoboxing/Unboxing |
| 22 | int parsed = Integer.parseInt("42"); // String -> primitive int |
| 23 | Integer boxed = parsed; // Autoboxing: int -> Integer |
| 24 | int unboxed = boxed + 8; // Unboxing: boxed -> int, then + 8 |
| 25 | System.out.println("Parsed: " + parsed + ", Boxed: " + boxed + ", Unboxed+8: " + unboxed); |
| 26 | |
| 27 | ArrayList<Integer> list = new ArrayList<>(); |
| 28 | list.add(100); // Autoboxes 100 to Integer.valueOf(100) |
| 29 | int fetched = list.get(0); // Unboxes Integer to int |
| 30 | System.out.println("From ArrayList: " + fetched); |
| 31 | } |
| 32 | } |
Widened double: 25.0 Narrowed int from 3.99: 3 Promoted & cast byte sum: 90 Parsed: 42, Boxed: 42, Unboxed+8: 50 From ArrayList: 100
IntegerDoubleNumbervalueOfparseInt- Thinking
(int) 3.99rounds to4— casting ALWAYS truncates toward zero (3). - Writing
byte c = b1 + b2;without casting theintresult back tobyte. - Unboxing a
nullwrapper object, causingNullPointerExceptionat runtime.
Comparison Tables
| Aspect | Widening (Implicit / Upcasting) | Narrowing (Explicit / Downcasting) |
|---|---|---|
| Direction | Smaller -> Larger (byte -> int -> double) | Larger -> Smaller (double -> int -> byte) |
| Performed By | Java compiler automatically | Programmer explicitly using (type) |
| Data Loss | No data loss (except int/long -> float/double precision) | Possible truncation or overflow |
| Example | int a = 10; double d = a; | double d = 10.7; int a = (int) d; |
Real-World Applications
- Parsing text input from forms, CLI arguments, or JSON (
Integer.parseInt,Double.parseDouble). - Storing numeric values inside Generic Collections (
ArrayList<Integer>,Vector<Double>) and database fields that allownull.
Important KTU Exam Points
- Draw the widening chain:
byte -> short -> int -> long -> float -> double(andchar -> int). - State clearly:
Byte, Short, Integer, Long, Float, DoubleextendNumber;CharacterandBooleanextendObjectdirectly. - Always mention the
byte + byte -> intpromotion rule—it is a favorite KTU Find-the-Error question!
Memory Techniques & Revision
- Widening Ladder: 'B-S-I-L-F-D' (Buy Six Ice-creams, Love Fudge Daily):
byte -> short -> int -> long -> float -> double.
Common Pitfalls to Avoid
- Forgetting that
char(unsigned 0..65535) andshort(signed -32768..32767) are incompatible for implicit widening in either direction. - Using
==to compare twoIntegerwrapper objects above 127 (compares object references instead of values; use.equals()!).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
- Widening (Implicit): Automatically converts a smaller data type to a larger compatible type (
byte -> short -> int -> long -> float -> double), e.g.,int x = 10; double y = x;without data loss. - Narrowing (Explicit): Manually converts a larger type into a smaller type using cast syntax
(type), e.g.,double d = 9.75; int x = (int) d;(yields9via truncation).
Quick Understanding Check
1. Which statement causes a compile-time error in Java?
2. What is the parent class of Integer, Double, and Float?