chrisTina
chrisTina

Reputation: 2368

Java, detect whether a String beyond Long type value boundary

Given following Java codes:

String columnValue = "188237574385834583453453635";
columnValue =(Long.parseLong(columnValue)>Long.MAX_VALUE?"0":columnValue);

It throws java.lang.NumberFormatException since the input value is beyond Long's maximum value. However, it there an easy way to detect whether a number in a 'string' type get out of Long's maximum value with out using try catch solution?

Upvotes: 2

Views: 517

Answers (4)

Orace
Orace

Reputation: 8359

A lazy way can be to use BigInteger.

BigInteger a = new BigInteger("188237574385834583453453635");
BigInteger b = BigInteger.valueOf(Long.MAX_VALUE);

System.out.println("a > Long.MAX_VALUE is : " + (a.compareTo(b) > 0 ? "true" : "false"));

If performance is important, you will have to test more solutions.

@SotiriosDelimanolis idea is also a good one :

Extract the source code of parseLong and instead of throwing an exception, return a boolean.

Also there are many throw in the code, some are for the format, other are for the overflow, you will have to choose the right ones.

Upvotes: 8

Necreaux
Necreaux

Reputation: 9776

A really cheesy way:

columnValue.length() > ("" + Long.MAX_VALUE).length()

Of course this does NOT cover values greater than Long.MAX_VALUE but the same number of digits, only values with more digits.

Upvotes: 0

Ofer Lando
Ofer Lando

Reputation: 824

You can create a utility method that wraps the try/catch and returns a boolean, something like:

import java.util.*;
import java.lang.*;
import java.io.*;

class TestClass
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(TestClass.isLongString("188237574385834583453453635"));
    }

    public static boolean isLongString(final String longNumber)
    {
        boolean isLong = false;
        try
        {
            Long.parseLong(longNumber);
            isLong = true;
        }
        catch(Exception e)
        {
            // do nothing - return default false
        }

        return isLong;
    }
}

Upvotes: -1

Crazyjavahacking
Crazyjavahacking

Reputation: 9697

Not really.

The only naive partial solution is to compare the length of the String, but that would not work always.

Upvotes: -1

Related Questions