Type Casting and Input with Scanner
Type casting is the process of converting one data type into another.
In Java, smaller types are automatically promoted to larger types when needed โ this is called implicit casting or widening.
However, converting a larger type into a smaller type requires explicit casting or narrowing, which must be done manually to prevent data loss.
Knowing when and how to cast types properly is essential for working with mixed data and for making your code reliable and clear.
Mini Lab
The Scanner class is Javaโs simple tool for reading user input.
You can use it to read different primitive types directly with methods like nextInt(), nextDouble(), and nextLine().
Scanner automatically handles simple implicit casting for you when you choose the right method for the right type.
Always import java.util.Scanner and close the scanner when done.
Mini Lab
Sometimes, you need to use explicit casting when dealing with input.
For example, when you read data as a string using nextLine(), you must convert (cast) it to the right primitive type manually using methods like Integer.parseInt() or Double.parseDouble().
This gives you more control over your input, but you must handle conversion carefully to avoid runtime errors.
Mini Lab