Skip to content

Beginner · Getting started with Java · topic 5 of 60 · 25 min

Type conversion and reading input

Explanation

Java converts smaller types to bigger ones automatically (widening), but going the other way (narrowing) needs an explicit cast like (int) 9.99, which cuts off the decimals. Text is turned into numbers with Integer.parseInt and Double.parseDouble. Scanner reads keyboard input; watch out for the leftover newline after nextInt().

Widening: automatic and safe

Assigning a smaller type to a bigger one cannot lose information, so Java does it automatically: byte → short → int → long → float → double, and char → int.

java
int marks = 92;
double asDouble = marks;     // 92.0, automatic
long asLong = marks;         // 92
char c = 'A';
int code = c;                // 65 (the character's number)

Narrowing: you must cast

Going from a bigger type to a smaller one may lose information, so Java insists you write a cast: the target type in brackets. A cast from double to int cuts off (truncates) the decimal part; it does not round.

java
double price = 9.99;
int rupees = (int) price;              // 9 (truncated, not rounded)
long rounded = Math.round(price);      // 10 (Math.round(double) returns long)
int big = 300;
byte small = (byte) big;               // 44 (300 - 256): out-of-range values wrap
Careful: Casting cannot convert between unrelated types. (int) "42" does not compile; a String is not a number. Use Integer.parseInt("42"). And int-to-byte or long-to-int casts silently wrap when the value is too large, so check ranges first.

char arithmetic

java
char c = 'A';
System.out.println(c + 1);          // 66 (char + int → int)
System.out.println((char) (c + 1)); // B
c++;                                // ++ keeps the type
System.out.println(c);              // B
System.out.println('7' - '0');      // 7 (digit character to its number)

Strings to numbers and back

java
int qty = Integer.parseInt("12");          // 12
double rate = Double.parseDouble("7.25");   // 7.25
String s1 = String.valueOf(450);            // "450"
String s2 = "" + 450;                       // "450" (also works)
// Integer.parseInt("12 kg") → NumberFormatException at run time

parseInt throws NumberFormatException when the text is not a valid whole number (letters, spaces, decimals). Module 6 shows how to catch it; for now, make sure input is clean.

Reading keyboard input with Scanner

java
import java.util.Scanner;

public class Ages {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Your name: ");
        String name = in.nextLine();        // reads a whole line
        System.out.print("Your age: ");
        int age = in.nextInt();             // reads one int
        System.out.println(name + " will be " + (age + 1) + " next year");
    }
}

The leftover newline trap

nextInt() reads the number but leaves the Enter key (a newline character) in the input. A following nextLine() then reads that empty rest of the line immediately and returns "". The fix: call in.nextLine() once after nextInt() to consume the newline, or read every line with nextLine() and parse it with Integer.parseInt.

java
int age = in.nextInt();
in.nextLine();                      // consume the leftover newline
String city = in.nextLine();        // now reads the real next line
Tip: For fast input in competitive programming, people use BufferedReader instead of Scanner, because Scanner is slow for very large inputs. For everyday programs, Scanner is fine.
Think of it like this: Widening is like pouring a glass of water into a bucket: nothing spills. Narrowing is pouring a bucket into a glass: Java makes you say "(glass) I know some may spill" before it lets you.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Type conversion and reading input · 1/6

Casting and input

In this lesson you will convert between types and read input from the keyboard.

Prefer a video by a teacher? Find free videos on “java type casting scanner nextint nextline problem” on YouTube ↗

In real life: An electricity bill estimator

A small program for a housing society reads a flat number and the units used, calculates the bill at ₹6.75 per unit, and shows it rounded to the rupee. It reads lines and parses them, which avoids the Scanner newline trap.

java
import java.util.Scanner;

public class Bill {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Flat: ");
        String flat = in.nextLine();
        System.out.print("Units: ");
        int units = Integer.parseInt(in.nextLine().trim());
        double amount = units * 6.75;
        System.out.println("Flat " + flat + ": Rs " + Math.round(amount));
    }
}
Input B-204 and 230 prints Flat B-204: Rs 1553 (230 × 6.75 = 1552.5, rounded up).

Practice (0/3 done)

Task 1 · Question

What does this print? double d = 7.89; int i = (int) d; System.out.println(i + Math.round(d));

Task 2 · Question

A user types 25 and presses Enter, then types Pune and presses Enter. int age = in.nextInt(); String city = in.nextLine(); What is city?

Task 3 · Practice

Write Average.java that asks for three marks (whole numbers) using Scanner and prints their average with decimals (for 70, 85 and 90 it must print 81.66666666666667, not 81). Then print it rounded to the nearest whole number.

Quick quiz

Question 1

1.Which conversion needs an explicit cast?

Question 2

2.What is (char) 66?

Question 3

3.What does Integer.parseInt("4.5") do?

Question 4

4.What type does Math.round(2.5) return?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which conversion needs an explicit cast?

Answer: double to int

double to int may lose information (narrowing).

What is (char) 66?

Answer: 'B'

66 is the code for B.

What does Integer.parseInt("4.5") do?

Answer: Throws NumberFormatException

"4.5" is not a valid whole number.

What type does Math.round(2.5) return?

Answer: long

Math.round(double) returns a long (Math.round(float) returns int).

In char a = 100, b = 100; int c = a + b; what is c?Related

Answer: 200

Promotion to int prevents overflow in the addition.

From Type conversion and casting

int a = 10, b = 4; double r = a / b; What is r?Related

Answer: 2

a / b is integer division (2) before the result is stored in the double, so r is 2.

From Operators, conversions and parsing input

What is static_cast<int>(9.99)?Related

Answer: 9

Converting a double to an int cuts off the fraction; it does not round.

From Variables, types and constants

What does CAST(9.99 AS INTEGER) return?Related

Answer: 9

CAST cuts off the fraction; it does not round. Use ROUND(9.99) for 10.

From Numbers and maths

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Getting started with Java”. The module exam comes next.
  2. Module 1 exam: Getting started with Java · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Control flow and methods. 60 topics left in the course before the final exam.

← Previous: Operators and expressions