DEV Community

vimala jeyakumar
vimala jeyakumar

Posted on

Reverse in java

Definition:

->In Java, "reverse" refers to the process of changing the order of elements in a data structure so that they appear in the opposite sequence.

1.Strings – Changing the order of characters (e.g., "hello" → "olleh").
2.Arrays – Changing the order of elements in an array
(e.g., {1, 2, 3} → {3, 2, 1}).
3.Lists – Reversing the order of elements in an ArrayList, LinkedList, etc.
4.Numbers – Reversing the digits of an integer (e.g., 123 → 321).

Reverse Number:

->In Java, reversing a number means that the digit at the first position should be swapped with the last digit, the second digit will be swapped with the second last digit, and so on till the middle element.

Algorithm for Reversing a Number in Java
->Take the number’s modulo by 10.
->Multiply the reverse number by 10 and add modulo value into the reverse number.
->Divide the number by 10.
->Repeat above steps until number becomes zero.
Example Program:

package programs;

public class Reverse 
{

    public static void main(String[] args) 
    {
                int num = 2910;
                int reversed = 0;

                while (num != 0) 
                {
                    int digit = num % 10;
                    reversed = reversed * 10 + digit;
                    num /= 10;
                    System.out.println("Reversed: " + reversed);
                }
//              System.out.println("Reversed: " + reversed);
            }       
    }



Enter fullscreen mode Exit fullscreen mode

output:
Reversed: 0
Reversed: 1
Reversed: 19
Reversed: 192

Reverse String:

package programs;

public class ReverseString {

    public static void main(String[] args) 
    {
        String str = "Hello";
        String reversed = "";
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed += str.charAt(i);
        }
        System.out.println("Reversed: " + reversed);

    }

}

Enter fullscreen mode Exit fullscreen mode

output:
Reversed: olleH

Reference:
--> https://www.geeksforgeeks.org/java-reverse-number-program/
--> https://www.tpointtech.com/how-to-reverse-string-in-java
--> https://chatgpt.com/c/67ab758b-6c98-800f-8b8f-b39e0d01b060

Top comments (0)