allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œI can do all things through him who gives me strength.โ€
[Philippians 4:13]


Type Casting and Input with Scanner


2.2.1 Understanding Type Casting

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

java
public class TypeCasting { public static void main(String[] args) { int number = 42; double result = number; // implicit cast (widening) System.out.println("Implicit casting (int to double): " + result); double price = 19.99; int roundedPrice = (int) price; // explicit cast (narrowing) System.out.println("Explicit casting (double to int): " + roundedPrice); } }

2.2.2 Using Scanner for User Input

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

java
import java.util.Scanner; public class ScannerInput { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); System.out.print("Enter your name: "); scanner.nextLine(); // clear leftover newline String name = scanner.nextLine(); System.out.println("Hello, " + name + "! You entered: " + number); scanner.close(); } }

2.2.3 Combining Scanner with Type Casting

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

java
import java.util.Scanner; public class ScannerCasting { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a whole number as text: "); String input = scanner.nextLine(); int number = Integer.parseInt(input); // explicit cast from String to int System.out.println("Casted number: " + number); System.out.print("Enter a decimal as text: "); String decimalInput = scanner.nextLine(); double decimalNumber = Double.parseDouble(decimalInput); // explicit cast from String to double System.out.println("Casted decimal: " + decimalNumber); scanner.close(); } }