Nearby lessons
13 of 125Java - Type Casting
- 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):
Type Casting
Type Casting
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.
Expression Promotion — X + Y = Z
When two values are added in an expression, the result type is decided by these rules:
Type Casting — The Complete Rules
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;
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.
Type Casting — The Complete Rules
Chained Casting
Type Casting — The Complete Rules
- 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.