-1
long AccountNumber = 1234567890;
public void setAccNum(long Number)
    try(the size of the account number is lesser than equal to 10){
        this.Accountnumber = Number;
    }
    catch(Exception e){
        System.out.println("Error: Invalid account number");
    }

In the above code, to validate the length of the account number, is there any function to find the length of the value in AccountNumber variable in Java?

Monisha Mohan
  • 23
  • 1
  • 2

3 Answers3

2

There are many ways to do this, some are

1. String.valueOf(AccountNumber).length()

2. (Long.toString(AccountNumber)).length()

jack jay
  • 2,493
  • 1
  • 14
  • 27
0

To get the length convert to a string first:

int len = String.valueOf(this.AccountNumber).length();
GavinF
  • 387
  • 2
  • 15
-1

length is a method of String, so you can for example do

if (stringVar.length != 10)
{
        ...
}

But I'd recommend the usage of Apache Commons Lang3 StringUtils, because it's methods are always null-aware.

For example

if (StringUtils.length(stringVar) != 10)
{
    ...
}

edit: sorry, it's a number, so like others mentioned it must be converted to String first.

Gunnar
  • 383
  • 4
  • 18