Beginner · Getting started with Java · topic 5 of 60 · 25 min
Type conversion and reading input
Explanation
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.
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.
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 wrapchar arithmetic
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
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 timeparseInt 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
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.
int age = in.nextInt();
in.nextLine(); // consume the leftover newline
String city = in.nextLine(); // now reads the real next lineNeed 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
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.
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));
}
}Practice (0/3 done)
What does this print? double d = 7.89; int i = (int) d; System.out.println(i + Math.round(d));
A user types 25 and presses Enter, then types Pune and presses Enter. int age = in.nextInt(); String city = in.nextLine(); What is city?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Installing the JDK and your first programGetting started with Java · same module
- Type conversion and castingC Programming (from zero to systems) · Operators and control flow
- Operators, conversions and parsing inputC# and .NET · Getting started with C# and .NET
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
- Numbers and mathsSQL and Databases · Functions, CASE and NULL
- Mini project: reading input from the userRust Programming · Types, control flow and functions
Questions people ask about this
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
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.
What is static_cast<int>(9.99)?Related
Answer: 9
Converting a double to an int cuts off the fraction; it does not round.
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
- This is the last topic of “Getting started with Java”. The module exam comes next.
- Module 1 exam: Getting started with Java · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Control flow and methods. 60 topics left in the course before the final exam.