Digit Extraction in JavaIn the world of programming, dealing with numbers is a fundamental task. Often, we need to manipulate individual digits within a number for various applications like cryptography, data validation, or mathematical operations. The process is known as digit extraction. In this section we will explore different methods to extract digits from a number using Java. Approach 1: Using Modulo and Division OperationsOne of the most straightforward ways to extract digits from a number is by using modulo (%) and division (/) operations. Filename: DigitExtractionExample.java Output: 5 4 3 2 1 In this example, we start with the number 12345. The while loop continues until number becomes zero. In each iteration, we use the modulo operation (number % 10) to extract the last digit. We then print the digit and update number by integer division (number /= 10) to remove the last digit. Approach 2: Using String ConversionAnother approach is to convert the number into a string and then extract each character. Filename: DigitExtractionExample.java Output: 6 7 8 9 0 In this method, we first convert the integer number into a string using Integer.toString(). Then, we use a for-each loop to iterate over each character in the string. The Character.getNumericValue() method converts the character back to its numeric value. Approach 3: Recursive ApproachA recursive approach can also be used to extract digits from a number. In this approach, we define a recursive function extractDigits(). It takes an integer number as input. If number is greater than zero, it extracts the last digit using modulo and recursively calls itself with the updated number (number / 10). Finally, it prints the extracted digit. Filename: DigitExtractionExample.java Output: 5 4 3 2 1 In this method, we define a recursive function extractDigits(). It takes an integer number as input. If number is greater than zero, it extracts the last digit using modulo and recursively calls itself with the updated number (number / 10). Finally, it prints the extracted digit. ConclusionDigit extraction is a common task in programming, and Java provides various methods to achieve this. Depending on the specific requirements of our application, we can choose the method that best suits our needs. Whether it's using modulo and division operations, converting to a string, or employing a recursive approach, these techniques provide us with the tools to efficiently extract digits from numbers in Java. Next TopicDynamic Method Dispatch Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India