How do I convert a String to an int in Java?

String myString = “1234”; int foo = Integer.parseInt(myString); If you look at the Java documentation you’ll notice the “catch” is that this function can throw a NumberFormatException, which of course you have to handle: int foo; try { foo = Integer.parseInt(myString); } catch (NumberFormatException e) { foo = 0; } (This treatment defaults a malformed number to 0, but … Read more

How to convert a char to a String?

You can use Character.toString(char). Note that this method simply returns a call to String.valueOf(char), which also works. As others have noted, string concatenation works as a shortcut as well: But this compiles down to: String s = new StringBuilder().append(“”).append(‘s’).toString(); which is less efficient because the StringBuilder is backed by a char[] (over-allocated by StringBuilder() to 16), only for that array to be defensively copied … Read more

Converting characters to integers in Java

Character.getNumericValue(c) The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character ‘\u216C’ (the roman numeral fifty) will return an int with a value of 50. The letters A-Z in their uppercase (‘\u0041’ through ‘\u005A’), lowercase (‘\u0061’ through ‘\u007A’), and full width variant (‘\uFF21’ through ‘\uFF3A’ and ‘\uFF41’ through ‘\uFF5A’) forms have numeric values from 10 through 35. This … Read more