KTU OOP Java2024 Scheme • 60M ESE
MODULE 1/Section 1: Introduction to Java

Type Casting (Widening & Narrowing), Type Promotion, Wrapper Classes & Autoboxing

HIGH PRIORITY (Prep Guide)Official Syllabus~15 min study
Official KTU 2024 Syllabus Topics Covered Here
Wrapper classes and wrapper typesType castingWidening and narrowing conversionsAutoboxing and unboxing
Java Version Note: Autoboxing/Unboxing was introduced in Java 5 (JDK 1.5). Explicit wrapper constructors like 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).

2. Start From Zero: Pouring Water Between Cups & Gift-Wrapping Primitives

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!

Key Takeaway: Widening = small to large (automatic). Narrowing = large to small (explicit (type) cast, may lose data). Autoboxing = int -> Integer; Unboxing = Integer -> int.

3. Essential Exam Definitions

Widening Conversion (Implicit Casting)
Automatic conversion of a smaller compatible primitive type into a larger type (byte -> short -> int -> long -> float -> double, and char -> int) without data loss.
Narrowing Conversion (Explicit Casting)
Manual conversion of a larger type to a smaller type ((targetType) value) required when precision or range may be lost (truncation).
Wrapper Class
One of 8 classes in java.lang (Byte, Short, Integer, Long, Float, Double, Character, Boolean) that encapsulates a primitive value into an immutable object.
Autoboxing and Unboxing
Compile-time automatic conversion performed by 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, and char operands are ALWAYS promoted to int in expressions (so byte b = 10; b = b * 2; is a compile error without (byte)(b * 2)!).
  • Rule 2: If one operand is long, the entire expression promotes to long.
  • Rule 3: If one operand is float, the expression promotes to float.
  • Rule 4: If any operand is double, the entire expression promotes to double.
  • Narrowing Syntax: int i = (int) 9.87; truncates fractional .87 and stores 9.

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

  1. When writing Integer num = 10;, the compiler silently rewrites it into Integer.valueOf(10).
  2. When arithmetic runs on num + 5, the compiler inserts num.intValue() + 5 (unboxing), computes 15, and if assigned back to an Integer, autoboxes 15 again.
  3. When writing byte a = 50; byte b = (byte)(a * 2);, a * 2 first widens a to int, produces int 100, and (byte) narrows it back cleanly.

7. Complete Java Code Examples & Tracing

Widening, Narrowing, Type Promotion, Wrappers & AutoboxingCastingAndWrapperDemo.java
Demonstrates implicit widening, explicit narrowing with truncation, byte expression promotion, Integer.parseInt, and autoboxing/unboxing.
1import java.util.ArrayList;
2
3public 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}
Expected Output
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
Keywords:IntegerDoubleNumbervalueOfparseInt
Common Exam & Coding Mistakes
  • Thinking (int) 3.99 rounds to 4 — casting ALWAYS truncates toward zero (3).
  • Writing byte c = b1 + b2; without casting the int result back to byte.
  • Unboxing a null wrapper object, causing NullPointerException at runtime.

Comparison Tables

Widening vs Narrowing Type Conversion
AspectWidening (Implicit / Upcasting)Narrowing (Explicit / Downcasting)
DirectionSmaller -> Larger (byte -> int -> double)Larger -> Smaller (double -> int -> byte)
Performed ByJava compiler automaticallyProgrammer explicitly using (type)
Data LossNo data loss (except int/long -> float/double precision)Possible truncation or overflow
Exampleint 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 allow null.

Important KTU Exam Points

  • Draw the widening chain: byte -> short -> int -> long -> float -> double (and char -> int).
  • State clearly: Byte, Short, Integer, Long, Float, Double extend Number; Character and Boolean extend Object directly.
  • Always mention the byte + byte -> int promotion 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) and short (signed -32768..32767) are incompatible for implicit widening in either direction.
  • Using == to compare two Integer wrapper 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; (yields 9 via 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?