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

why get an int from a string in java

why get an int from a string in java

1 Answer

Do you want to know how to do it or why? The answers for why are likely numerous, but the biggest is probably that you can't perform math operations on numbers that are stored in strings. For example:

console.println("5" - 2);
// This will cause a crash.

And if you use an ambiguous operator like + (which works on both strings and numbers) then you will get an incorrect result as the number will be converted to a string and then get concatenated instead of being added together like intended. For example:

console.println("5" + 2);
// This will print out "52"

In order to manipulate and get correct results from various number operations they have to be stored as ints, Strings should only contain text or combinations of text and numbers, they should not be used to store pure number values.

If what you meant to ask was how you convert strings to int then there are varius answer to that question, the simplest is probably to use the Integer.parseInt() method. Here is an example:

String intAsString = "52";
int intFromString = Integer.parseInt(intAsString)
// This will result in "intFromString" containing 52 as an int.