In this tutorial, you will learn how to find length of an Integer in Java. There are several ways you can achieve this. One of the easiest way you can do this is by converting the `Integer`

to a string and then get the length of that string. This approach handles both positive and negative numbers correctly.

### 1. Using String Conversion

In this code, we are converting given number to string using `toString()`

method and then returning the length of the String using `length()`

method.

public class IntegerLength {

public static void main(String[] args) {

Integer number = 12345;

int length = getIntegerLength(number);

System.out.println("Number of digits: " + length);

}

public static int getIntegerLength(Integer number) {

if (number == null) {

return 0; // or throw an exception, depending on your needs

}

// converting number to String and then returning length

return number.toString().length();

}

}

### 2. Using String Conversion for Negative Numbers

In case of negative numbers, the above program would count the – sign as a digit, to rectify this, we can modify the above program like this, Here we are using replace() method of String class to replace negative sign with nothing, ultimately removing the sign from number.

public class IntegerLength {

public static void main(String[] args) {

Integer number = -12345;

int length = getIntegerLength(number);

System.out.println("Number of digits: " + length);

}

public static int getIntegerLength(Integer number) {

if (number == null) {

return 0; // or throw an exception, depending on your needs

}

return number.toString().replace("-", "").length();

}

}

### 3. Using Logarithms

Another way to count number of digits in an Integer is by using logarithms. You can use Math.abs() and Math.log10() method to do this.

`Math.abs(number)`

handles negative numbers as it converts them into positive numbers.`Math.log10(number)`

returns the base 10 logarithm of the number.- Adding 1 to the result gives the number of digits in the given Integer.

public class IntegerLength {

public static void main(String[] args) {

Integer number = -12345;

int length = getIntegerLength(number);

System.out.println("Number of digits: " + length);

}

public static int getIntegerLength(Integer number) {

if (number == null) {

return 0;

}

if (number == 0) {

return 1;

}

return (int) Math.log10(Math.abs(number)) + 1;

}

}

## Leave a Reply