×

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer.

These are the approaches for finding the length of an integer in Java:

  • By using the while loop
  • By using the String
  • By using the Continuous Multiplication
  • By using the Logarithm
  • By using the Recursion method

1. By using the while loop

The variable n contains the user-inputted integer. Once the test phrase n!= 0 is converted to 0, the while loop iterates until it returns 0. (false).

  • The count is increased by one after the initial iteration, bringing the value of n to 354.
  • The number n would be 35 in the second iteration, and the count will have increased by 2.
  • The number n will be 3 just after the third iteration, and the count is increased by 3.
  • The loop is ended when n reaches 0 at the beginning of the fourth iteration.
  • The loop then ends when the test expression is determined to be false.

The application of the abovementioned strategy is seen below:

IntegerExample.java

//this program is for finding the number of digits in a given integer
//import section
import Java.io.*;
import Java.util.*;
public class IntegerExample  
{  
// method for finding the number of digits in the given integer
public int countDigits(int number)  
{  
int c = 0;  
while(number!= 0)  
{  
//the last of the given integer is removed for counting the digits
number = number/ 10;  
// the value of count(c) is updated to +1 
c = c + 1;  
}  
return c;  
}  
// main section of the program   
public static void main(String argvs[])  
{  
// the array consisting of integers as an input  
int array[] = {780, 19, 22345, 899009, 981, 4214, 3894, 1, 9};  
//finding the length of the array   
int length = array.length;  
// an object (object) is created for the class IntegerExample  
IntegerExample object = new IntegerExample();  
for(int i = 0; i < length; i++)  
{  
int c = object.countDigits(array[i]);  
System.out.println("The number of digits in the given number "+array[i]+" is--"+c);  
}  
}  


}  

Output:

How to find length of integer in Java

2. By using the String

Another method is making the integer into a string after calculating its length. The string's size determines the size of the string. The very same is seen in the program which follows.

IntegerStringExample.java

//this program is for finding the number of digits in a given integer
//import section
import Java.io.*;
import Java.util.*;
public class IntegerStringExample  
{  
//method for finding the number of digits in the given integer
public int countDigits(int n)  
{  
// the given integer is converted to a string
String s = Integer.toString(n);  
// computing the size of the string  
int len = s.length();  
return len;  
}  
// main section of the program 
public static void main(String argvs[])  
{  
// the array consisting of integers as an input  
int array[] = {780, 19, 22345, 899009, 981, 4214, 3894, 1, 90};  
//finding the length of the array   
int length = array.length;  
// an object (object) is created for the class IntegerExample  
IntegerStringExample object = new IntegerStringExample();  
for(int i = 0; i < length; i++)  
{  
int c = object.countDigits(array[i]);  
System.out.println("The number of digits in the given number "+array[i]+" is:  "+c);  
}  
}  
}  

Output:

How to find length of integer in Java

3. By using the Continuous Multiplication

A number 1 can be multiplied by 10 until it exceeds the value of n. When multiplying by 10, we add one to a variable, counting for each time. The count's final value indicates the length of the integer num. Now let us study it with the support of the following Java program.

IntegerMultiplicationExample.java

//This program is for finding the length of the integer in Java
//by using the continuous multiplication method
//import section
//class IntegerMultiplicationExample is created
public class IntegerMultiplicationExample  
{  
//method for determining the length of the integer  
public int countDigits(int num)
{  
int temporary = 1;  
int c = 0;  
while(temporary <= num)
{  
//the temporary variable is multiplied to 10
temporary = temporary * 10;  
//  the value of c is then incremented to 1
c = c+ 1;  
}  
// the value of c will contain the total number 
//of the digits in the given integer  number
return c;  
}
// main section of the program  
public static void main(String argvs[])  
{  
// user input array 
int array[] = {7833, 869, 2345, 9, 1, 401495, 364, 1006, 279};  
// the total elements of the array can be calculated using the length function  
int len = array.length;  
// 
IntegerMultiplicationExample obj = new IntegerMultiplicationExample();  
for(int i = 0; i < len; i++)  
{
int c = obj.countDigits(array[i]);  
System.out.println("The number digits in " + array[i] + " is " + c);  
}  
}  
}  

Output:

How to find length of integer in Java

4. By using the Logarithm

Log can also be used to find the integer's length in Java. The program below can be used to understand how can find the integer's length using the log function.

IntegerLogExample3.java

//This program is for finding the length of the integer in Java
//by using the log function in the math module method
//import section
public class IntegerLogExample3  
{  
//  
public int countDigits(int number)  
{  
// method for determining the length of the integer  
int length = (int) (Math.log10(number) + 1);  
// the length of the integer can be returned
return length;  
}  
// main section
public static void main(String argvs[])  
{  
//the array given by the user as user input 
int array[] = {7889, 929, 345, 989, 11, 4074, 7825, 109800, 73627};  
// the  length of the user input array can be calculated using the length
int len = array.length;  
//an object ob for the class IntegerLogExample3 is created 
IntegerLogExample3 ob = new IntegerLogExample3();  
for(int i = 0; i < len; i++)  
{  
int c = ob.countDigits(array[i]);  
System.out.println("The number of digits in  " + array[i] + " is " + c);  
}  
}  
}  

Output

How to find length of integer in Java

5. By using the Recursion method

Recursion is the process in which a function can be called by itself until it has reached a certain condition. For every function call, the allocation of the memory can be done. The concept of recursion in Java can determine the number of the digits in the given integer.

IntegerLengthRecursionExample4.java

//This program is for finding the length of the integer in Java
//by using the concept of recursion
//import section
public class IntegerLengthRecursionExample4  
{  
// the method count can be used as the Digits in the given integer
public int countDigits(int number)  
{  
// the base case is checked using the if the condition
if(number/ 10 == 0)  
{  
return 1;  
}  
// by the process of recursion, the method can be called
// from the opposite direction, increment the length
return 1 + countDigits(number/ 10);  
}  
// main section of the program 
public static void main(String argvs[])  
{  
//   
int array[] = {498, 967, 345, 9009, 619, 4984, 3874, 7600, 8749};  
// the length of the integer can be calculated using the length function
int len = array.length;  
// an object ob is created for the class
IntegerLengthRecursionExample4  ob = new IntegerLengthRecursionExample4 ();  
for(int i = 0; i < len; i++)  
{  
int c = ob.countDigits(array[i]);  
System.out.println("The number of digits in  " + array[i] + " is " + c);  
}  
}  
}    

Output:

How to find length of integer in Java

Related Topics

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.