Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDaniel Hernandez-Zuleta
1,478 Pointswhy do we use the Integer.parseInt?
I don't understand why we need to use this,
2 Answers
miguelcastro2
Courses Plus Student 6,573 PointsSometimes we may have a number that is represented as a String, for example:
"1" "22" "3"
If we want to see if "1" is less than "22" we cannot, because Java just sees those numbers as strings. To Java, "22", is no different than saying "twenty-two". If we want to compare numbers then we would require Integers to do so. In some cases our programs may receive a string that contains an integer and in order for us to use the value in the string as an Integer we need to parse the integer from the string to obtain a valid Integer.
String numOneStr = "1";
String numTwentyTwoStr = "22";
int numOne = Integer.parseInt(numOneStr);
int numTwentyTwo = Integer.parseInt(numTwentyTwoStr);
if (numOne < numTwentyTwo) {
System.out.println("1 is less than 22");
}
Daniel Hernandez-Zuleta
1,478 PointsThanks everyone. Knowledge is power.
Eric Greer
4,997 PointsEric Greer
4,997 PointsI was a little confused by why he did that in the examples too, but I think it was just to remind you that sometimes numbers need converted to strings.
He could have done the age comparison using only ints, I'm sure.