Nearby lessons

13 of 125

Java - Type Casting

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

Type Casting is a core concept of the Java language. This lesson explains Type Casting and Type Casting — The Complete Rules with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Type Casting

Type casting means converting a value from one type to another type. There are two kinds:

  • Implicit (automatic / widening) — small type to big type. Java does it by itself. Safe, no data loss. Example: int to long, long to float.
  • Explicit (manual / narrowing) — big type to small type. We must write the target type in brackets. Risk of data loss. Example: double to int.

Widening order (safe direction, automatic):

Example01
JCode Cell
1int i = 100;
2long l = i; // implicit widening: OK, automatic
3 
4double d = 99.99;
5int x = (int) d; // explicit narrowing: we must write (int)
6System.out.println(x); // 99 (decimal part lost)

Type Casting

Trainer's Note: Memory trick: in widening, no data is lost — so Java allows it freely. In narrowing, data may be lost — so Java forces you to write the cast bracket, which is like signing your name: 'I know what I am doing'.
Example02
JCode Cell
1byte -> short -> int -> long -> float -> double
2 |
3 char (char goes to int and above)

Type Casting

In simple words: Widening is automatic and safe; narrowing needs brackets and may lose data. Going from a small type to a big type like int to long is free, but going back means writing (int) and accepting the risk.
Example03
JCode Cell
1class CastDemo {
2 public static void main(String[] args) {
3 int a = 257;
4 byte b = (byte) a; // narrowing: 257 -> 1
5 System.out.println(b); // 1 (257 % 256 = 1)
6 
7 char ch = 'A';
8 int code = ch; // widening: char -> int
9 System.out.println(code); // 65 (UNICODE of 'A')
10 }
11}
Output
1 65

Type Casting — The Complete Rules

The Implicit Casting Chart (with char)

Implicit (automatic) conversion flows only from lower to higher types, following this chart:

So these are automatic (no error): byte -> int, char -> int, long -> float. But these are errors without a cast: int -> byte, byte -> char, char -> short.

Trainer's Note: The surprising one: `long` (8 bytes) to `float` (4 bytes) is allowed automatically! Reason: float can hold larger magnitude numbers than long due to its internal arrangement (the classic material uses a classroom-bench analogy). But float to long is NOT automatic — it needs an explicit cast.

Expression Promotion — X + Y = Z

When two values are added in an expression, the result type is decided by these rules:

Example04
JCode Cell
1byte -> short -> int -> long -> float -> double
2 ^
3 | (char goes UP to int and beyond)
4 char

Type Casting — The Complete Rules

Example05
JCode Cell
1If both are byte, short or int -> result is int
2If either is long -> result is long
3If either is float -> result is float
4If either is double -> result is double
5 
6byte + byte = int
7byte + short = int
8short + int = int
9byte + long = long
10long + float = float
11float + double= double

Type Casting — The Complete Rules

Also remember: assigning a literal like byte b = 128; is an error, because 128 is out of byte range and is treated as an int.

Explicit Casting — The Cast Operator ( )

Explicit (narrowing) casting forces a higher type into a lower type. Data may be lost. Format: P a = (Q) b;

Example06
JCode Cell
1class Promotion {
2 public static void main(String[] args) {
3 byte b1 = 30, b2 = 30;
4 // byte b = b1 + b2; // ERROR! b1+b2 is int, cannot go to byte
5 byte b = (byte) (b1 + b2); // cast the whole sum
6 System.out.println(b); // 60
7 }
8}

Type Casting — The Complete Rules

Explicit casting also allows conversions that implicit casting forbids: char to byte/short and back are possible only with a cast.

Example07
JCode Cell
1int i = 10; byte b = (byte) i; // 10 -> 10
2char c = 'A'; int n = c; // A -> 65 (implicit)
3int x = 65; char ch = (char) x; // 65 -> A (explicit)

Type Casting — The Complete Rules

Chained Casting

Example08
JCode Cell
1byte b = 65;
2char c = (char) b; // 65 -> 'A' (explicit, allowed)
3short s = (short) c; // 'A' -> 65 (explicit, allowed)

Type Casting — The Complete Rules

Trainer's Note: Golden rule of thumb: widening = automatic and safe; narrowing = needs brackets and may lose data. And one placement trap: (byte)(b1 + b2) casts the sum (correct), but (byte)b1 + b2 casts only b1 and then the result is still int (error).
Example09
JCode Cell
1double d = 22.22;
2byte b = (byte)(short)(int)(long)(float) d; // narrowing step by step
3System.out.println(b); // 22 (decimal part lost)
📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1