You can use built-in methods:
1 2 3 4 |
String s = "123"; Integer x = Integer.valueOf(s); // or int y = Integer.parseInt(s); |
or you can implement custom method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public static void main(String[] args) { System.out.println(Integer.parseInt("456")); System.out.println(Integer.valueOf("789")); System.out.println(strToInt("-123")); } public static int strToInt(String str) { int i = 0; int number = 0; boolean negativeNumber = false; //Check for negative sign; if it's there, set the negativeNumber mark if (str.charAt(0) == '-') { negativeNumber = true; i = 1; } //Process each symbol of the string; while (i < str.length()) { number *= 10; number += str.charAt(i++) - '0'; } if (negativeNumber) { number = -number; } return number; } |