Java Java Basics Perfecting the Prototype Parsing Integers

Parsing Int

Why can't we just use int age = console.readLine("Enter you're age: "); Instead of: String ageAsString = console.readLine("How old are you? "); int age = Integer.parseInt(ageAsString);

2 Answers

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

Hi there! It's because any data coming in from the prompt is coming in as a string (and this is also true of other languages besides Java). And you would be trying to assign that string to an integer variable which would cause an error. So we read in the age which looks like a number to the person writing it, but is actually a string. Then we convert that number into an integer.

Hope this helps! :sparkles:

Great. So, in order to go from one data type to another, parsing is required?

Sandy Woods : Yep, parsing is a way (most likely not the only way) to move data from one type to another as needed.