nelt22
nelt22

Reputation: 410

How to determine if contents of String is Integer, Boolean or Double?

I am currently reading a .properties file in my java project and I noticed every line is read as String (not matter if I use .get() or .getProperty()). So, I was wondering how can I determine, from the contents of a String, if that value is boolean or Integer or double or even a String.

"asavvvav" --> String
"12345678" --> Integer
"false"    --> Boolean

Upvotes: 2

Views: 346

Answers (1)

Vince
Vince

Reputation: 15146

You could use regex:

String booleanRegex = false|true;
String numberRegex = \\d+;

if(input.matches(booleanRegex)) {

} else if(input.matches(numberRegex)) {

} else {
   //is String
}

Or you could attempt to parse and catch the exception:

boolean isNumber = false;
try {
    Integer.parseInt(input);
    isNumber = true;
} catch(NumberFormatException e) {
    e.printStackTrace();
}

To check if it's an enum value:

try {
    Enum.valueOf(YourEnumType.class, "VALUE");
} catch(IllegalStateException e) {
    e.printStackTrace();
    //was not enum
}

Upvotes: 3

Related Questions