Android
String Conversion
Integer Parsing
Android Development
Java Programming

Converting a string to an integer on Android

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting a string to an integer on Android uses standard Java/Kotlin methods since Android runs on the JVM. The primary methods are Integer.parseInt() (returns a primitive int) and Integer.valueOf() (returns an Integer object). Both throw NumberFormatException if the string is not a valid integer, so you must handle this exception when parsing user input from EditText, intent extras, or API responses. In Kotlin, use toIntOrNull() for a null-safe conversion that avoids try/catch blocks entirely.

Java: Integer.parseInt()

java
1// Basic conversion
2String numberStr = "42";
3int number = Integer.parseInt(numberStr);
4System.out.println(number);  // 42
5
6// From EditText
7EditText editText = findViewById(R.id.editTextNumber);
8String input = editText.getText().toString().trim();
9int value = Integer.parseInt(input);
10
11// With radix (base)
12int hex = Integer.parseInt("FF", 16);    // 255
13int binary = Integer.parseInt("1010", 2); // 10
14int octal = Integer.parseInt("17", 8);    // 15

Handling NumberFormatException

java
1public int parseIntSafe(String str, int defaultValue) {
2    try {
3        return Integer.parseInt(str.trim());
4    } catch (NumberFormatException e) {
5        return defaultValue;
6    }
7}
8
9// Usage
10int age = parseIntSafe(editText.getText().toString(), 0);
11int quantity = parseIntSafe("not a number", -1);  // Returns -1
12int count = parseIntSafe("", 0);                  // Returns 0
13int valid = parseIntSafe("123", 0);               // Returns 123

Java: Integer.valueOf()

java
1// Returns Integer object (boxed)
2Integer boxed = Integer.valueOf("42");
3
4// Auto-unboxing to int
5int number = Integer.valueOf("42");
6
7// Difference from parseInt:
8// parseInt returns primitive int
9// valueOf returns cached Integer object (caches -128 to 127)
10Integer a = Integer.valueOf("100");
11Integer b = Integer.valueOf("100");
12System.out.println(a == b);  // true (cached)
13
14Integer c = Integer.valueOf("200");
15Integer d = Integer.valueOf("200");
16System.out.println(c == d);  // false (not cached, use .equals())

Kotlin: toInt() and toIntOrNull()

kotlin
1// Direct conversion (throws NumberFormatException)
2val number: Int = "42".toInt()
3
4// Null-safe conversion (returns null on failure)
5val safe: Int? = "42".toIntOrNull()       // 42
6val invalid: Int? = "abc".toIntOrNull()   // null
7val empty: Int? = "".toIntOrNull()        // null
8val overflow: Int? = "99999999999".toIntOrNull()  // null (exceeds Int range)
9
10// With default value using Elvis operator
11val age: Int = editText.text.toString().toIntOrNull() ?: 0
12val quantity: Int = "not a number".toIntOrNull() ?: -1
13
14// With radix
15val hex: Int = "FF".toInt(16)             // 255
16val hexSafe: Int? = "GG".toIntOrNull(16)  // null (invalid hex)

Common Android Use Cases

From EditText

kotlin
1// Kotlin
2val editText: EditText = findViewById(R.id.editTextAge)
3val ageStr = editText.text.toString().trim()
4val age = ageStr.toIntOrNull()
5
6if (age == null || age < 0 || age > 150) {
7    editText.error = "Please enter a valid age"
8} else {
9    processAge(age)
10}
java
1// Java
2EditText editText = findViewById(R.id.editTextAge);
3String ageStr = editText.getText().toString().trim();
4
5try {
6    int age = Integer.parseInt(ageStr);
7    if (age < 0 || age > 150) {
8        editText.setError("Age must be between 0 and 150");
9    } else {
10        processAge(age);
11    }
12} catch (NumberFormatException e) {
13    editText.setError("Please enter a valid number");
14}

From Intent Extras

kotlin
1// Sending
2val intent = Intent(this, DetailActivity::class.java)
3intent.putExtra("item_id", 42)  // Send as int directly
4intent.putExtra("item_id_str", "42")  // Or as string
5
6// Receiving
7val id = intent.getIntExtra("item_id", -1)  // Returns int directly
8val idStr = intent.getStringExtra("item_id_str")
9val idParsed = idStr?.toIntOrNull() ?: -1

From SharedPreferences

kotlin
1val prefs = getSharedPreferences("settings", MODE_PRIVATE)
2
3// Store as int
4prefs.edit().putInt("count", 42).apply()
5val count = prefs.getInt("count", 0)
6
7// Store as string (from older code)
8prefs.edit().putString("count", "42").apply()
9val countStr = prefs.getString("count", "0")
10val countParsed = countStr?.toIntOrNull() ?: 0

From JSON/API Responses

kotlin
1import org.json.JSONObject
2
3val json = JSONObject("""{"id": "123", "count": 42}""")
4
5// String field that should be int
6val id = json.getString("id").toIntOrNull() ?: 0
7
8// Int field (already an int in JSON)
9val count = json.getInt("count")
10
11// Optional field
12val optionalCount = if (json.has("views")) json.getInt("views") else 0

Other Numeric Conversions

kotlin
1// Long
2val longVal: Long = "9999999999".toLongOrNull() ?: 0L
3
4// Double
5val doubleVal: Double = "3.14".toDoubleOrNull() ?: 0.0
6
7// Float
8val floatVal: Float = "2.5".toFloatOrNull() ?: 0f
9
10// Java equivalents
11long l = Long.parseLong("9999999999");
12double d = Double.parseDouble("3.14");
13float f = Float.parseFloat("2.5");

Common Pitfalls

  • Not trimming whitespace before parsing: Integer.parseInt(" 42 ") throws NumberFormatException because of leading/trailing spaces. Always call .trim() on the string before parsing, especially when reading from EditText.
  • Forgetting to handle NumberFormatException: User input is unpredictable. Parsing without try/catch or toIntOrNull() crashes the app when the user enters non-numeric text. Always validate or catch exceptions on user-provided strings.
  • Comparing Integer.valueOf() results with ==: Integer.valueOf() caches values from -128 to 127. Beyond that range, == compares object references and returns false even for equal values. Use .equals() for Integer object comparison.
  • Parsing strings with decimal points as integers: Integer.parseInt("3.14") throws NumberFormatException. To handle decimals, parse as Double.parseDouble() first, then cast to int if truncation is acceptable: (int) Double.parseDouble("3.14").
  • Not setting inputType="number" on EditText: Without android:inputType="number" in XML, the soft keyboard shows letters, making non-numeric input easy. Setting the input type restricts the keyboard to digits, reducing (but not eliminating) the need for parsing validation.

Summary

  • Use Integer.parseInt() in Java or .toInt() in Kotlin for basic string-to-integer conversion
  • Use .toIntOrNull() in Kotlin for null-safe parsing that avoids try/catch blocks
  • Always handle NumberFormatException when parsing user input or external data
  • Trim whitespace before parsing and set inputType="number" on EditText to reduce invalid input
  • For intent extras and SharedPreferences, prefer storing integers directly (putInt) instead of converting from strings

Course illustration
Course illustration

All Rights Reserved.