![]() ![]() If you're interested in converting a String to an Integer object, use the valueOf() method of the Integer class instead of the parseInt() method.Integer.toString(int i) is used to convert in the other direction, from an int to a Java String.While I’m in this neighborhood, here are a few related notes about the String and Integer classes: In this example, I don’t really need to use the String class trim() method, but in a real-world program you should use it, so that's why I’ve shown it here. If the conversion attempt fails - for instance, if you try to convert the Java String fred to an int - the Integer parseInt method will throw a NumberFormatException, which you should handle in a try/catch block. ("NumberFormatException: " + nfe.getMessage()) Īs you can see from this example, the Integer.parseInt(s.trim()) method is used to convert from the string s to the integer i in this line of code: print out the value after the conversion the String to int conversion happens here String s = "fred" // use this if you want to test the exception below Here’s the source code for a complete example program that demonstrates the Java String to int conversion process, handling for a possible NumberFormatException: Example 2: A complete “String to int” example ![]() If it fails for any reason, the conversion will throw a NumberFormatException, so your code should be a little bit longer to account for this, as shown in the next example. If the String represented by the variable myString is a valid integer like “1”, “200”, and so on, it will be converted to a Java int. Ignoring the exception it can throw, all you need to convert a String to int is this one line of code: Example 1: A basic Java “String to int” conversion example For more information, see the following two examples. ParseInt converts the String to an int, and throws a NumberFormatException if the string can’t be converted to an int type. The most direct solution to convert a Java string to an integer is to use the parseInt method of the Integer class: Java String/int FAQ: How do I convert a Java String to an int? Solution
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |