Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality test for numeric value input parameter received as String data type

Tags:

java

I am receiving a numeric value input parameter that is a String data type (something that I cannot change) and I need to check that this value received is of a certain number. I.e. Check if the value is 5.

Knowing that the received value of String data type, but at all times it will should contain only numbers. I would first convert the value into an integer data type, and then perform the equality test. I.e. Case B illustrated below.

Case A:

String expected = "3"; 

if(expected.equals(actual)) //...

Case B:

int expected = 3;

int actualInt = Integer.parseInt(actual);

if(expected == actualInt) //...

I would like to find out if there will be any cons in performing the equality test using Case B as I am more inclined to do it that way as a correct way out.

like image 224
Oh Chin Boon Avatar asked Dec 30 '25 00:12

Oh Chin Boon


2 Answers

Use Try-Catch:

int expected = 3;
int actualInt;
try
{
    actualInt = Integer.parseInt(actual);

    if(expected == actualInt) //...
}
catch(NumberFormatException ex)
{
    // You will reach here when a bad input is given to the parseInt method
    // Handle the failure
}
catch(Exception e)
{
    // All other exceptions here
}

Even though you know that the string is always going to have a "numeric" value, it is still a good practice to implement exception handling. Better safe than worry :)

like image 131
Vaibhav Desai Avatar answered Jan 01 '26 12:01

Vaibhav Desai


If you are only going to do equality check then I think case A is fine, since you are not doing any operations that will require you the number instead of a string.

Only cons I could see with case B, is that you would have to parse the number out of the string for the equality check.

But the advantage of case B is that if you needed to make sure that the string is actually an integer, in which case, you would have to go with case B.

like image 27
Bhesh Gurung Avatar answered Jan 01 '26 14:01

Bhesh Gurung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!