java integer.length code example

Example 1: how to get length of integer in java

int length = (int) (Math.log10(number) + 1);

Example 2: how to get length of integer in java

int length = 0;
long temp = 1;
while (temp <= number) {
    length++;
    temp *= 10;
}
return length;

Example 3: how to have a only number type in java

class scratch{
    public static Number haha(Number yo){
        return yo;
    }

    public static void main(String[] args) {
        System.out.println(haha( (int) 5 ));
        System.out.println(haha( (double) 5.0 ));
        System.out.println(haha( (long) 5 ));
        System.out.println(haha( (float) 5.0 ));
        //all of these classes extend the java.lang.Number class 

        System.out.println(haha("Hey"));
        //error because the java.lang.String class does not extend the java.lang.Number class
    }
}

Tags:

Java Example