Deepak Deepak - 3 months ago 11
Java Question

How to check if a string is a number

I have conversion to Map problem in Core Java.

Below is requirement:

Given a String array below

String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"};

Convert it into a Map such that the resultant output is below


======      ======         
key Value
====== ======
abc true
123 false
def true
456 false

The above should be printed for each element in the array. I have written the code but it's not working and I'm stuck. Please let me know how it can be resolved. Thanks in advance.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class CoversionToMap {

* @param args
public static void main(String[] args) {
String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"};
Map m = new HashMap();
for(int i=0;i<str.length;i++){
if(Integer.parseInt(str[i]) < 0){
//Print the map values finally

public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry);
System.out.println(pairs.getKey() + " = " + pairs.getValue());


Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at CoversionToMap.main(


Everyone is suggesting using exception handling for this, there is nothing exceptional here to warrant using exceptions like this, you don't try turning left in your car and if you crash go right do you? Something like this should do it

Map<String, Boolean> m = new HashMap<String, Boolean>();
for (String str: strs) {
    m.put(str, isInteger(str));

public boolean isInteger(String str) {
    int size = str.length();

    for (int i = 0; i < size; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;

    return size > 0;

Much clearer and more efficient that catching throwing exception, even when there are 99% integers as the integer value is not even needed so no conversion required.