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 trial

Java Java Objects (Retired) Meet Objects Welcome Back

why do we use the Integer.parseInt?

I don't understand why we need to use this,

2 Answers

Sometimes 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");
}
Eric Greer
Eric Greer
4,997 Points

I 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.

Thanks everyone. Knowledge is power.