Introduction

     In this blog post, we will explore how to create a Java program to find the sum of digits and the reverse of a given number using classes and objects. This is a fundamental exercise that helps in understanding basic operations on numbers and the use of classes in Java.

Code

    
     
    import java.util.*;
    import java.io.*;
    
    public class rev {
        public static void main(String args[]) throws IOException {
            DataInputStream s = new DataInputStream(System.in);
            int n;
            System.out.println("Enter the number:");
            n = Integer.parseInt(s.readLine());
            sum a = new sum();
            a.getresult(n);
        }
    }
    
    class sum {
        int d, num = 0, sum = 0, r = 0;
        
        void getresult(int num) {
            while (num > 0) {
                d = num % 10;
                sum += d;
                r = (r * 10) + d;
                num = num / 10;
            }
            System.out.println("Sum = " + sum);
            System.out.println("Reverse = " + r);
        }
    }        
    
     


Output


    Enter the number:
    123
    Sum = 6
    Reverse = 321


  

Explanation

1. Input Handling:
    The DataInputStream class is used to read the input from the console. The number (n) is read from the user and passed to an instance of the sum class for processing.
2. Class and Method:
    The sum class contains instance variables to store the current digit (d), the sum of digits (sum), and the reversed number (r). The getresult method is responsible for the main logic. It processes the number digit by digit until all digits have been processed.
3. Processing Logic:
    Inside the getresult method, a while loop runs as long as num is greater than zero. In each iteration, the last digit is extracted using the modulus operator (%), added to the sum, and used to build the reversed number. The number is then divided by 10 to remove the last digit, and the process repeats.
4. Output: 
    After the loop completes, the sum of the digits and the reversed number are printed to the console.

Conclusion

     This Java program demonstrates how to use classes and methods to perform operations on numbers, such as calculating the sum of digits and reversing the number. Understanding these basic concepts is crucial for learning more advanced programming techniques and object-oriented principles. This exercise also highlights the importance of breaking down problems into smaller, manageable parts and using classes to organize and encapsulate functionality in Java