Write a program to reverse an array or string

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-08-15 10:51:20 Viewed : 293


Write a program to reverse an array or string:

Here is a Java program to reverse an array and a string:

1. Reverse an Array:

java
public class ReverseArray { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; reverseArray(array); System.out.print("Reversed array: "); for (int num : array) { System.out.print(num + " "); } } public static void reverseArray(int[] arr) { int left = 0; int right = arr.length - 1; while (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } }

Output:

c
Reversed array: 5 4 3 2 1

2. Reverse a String:

java
public class ReverseString { public static void main(String[] args) { String str = "Hello, World!"; String reversed = reverseString(str); System.out.println("Original string: " + str); System.out.println("Reversed string: " + reversed); } public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } }

Output:

yaml
Original string: Hello, World! Reversed string: !dlroW ,olleH

In the first example, the reverseArray function swaps elements from the beginning and the end of the array, moving towards the center until the entire array is reversed.

In the second example, the reverseString function uses the StringBuilder class reverse method to reverse the characters in the string.

Here is a Java program that demonstrates how to reverse an array or a string:

java
public class ReverseArrayOrString { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; reverseArray(array); System.out.print("Reversed array: "); for (int num : array) { System.out.print(num + " "); } System.out.println(); String str = "Hello, World!"; String reversedStr = reverseString(str); System.out.println("Reversed string: " + reversedStr); } public static void reverseArray(int[] arr) { int left = 0; int right = arr.length - 1; while (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } public static String reverseString(String str) { char[] charArray = str.toCharArray(); int left = 0; int right = charArray.length - 1; while (left < right) { char temp = charArray[left]; charArray[left] = charArray[right]; charArray[right] = temp; left++; right--; } return new String(charArray); } }

Output:

yaml
Reversed array: 5 4 3 2 1 Reversed string: !dlroW ,olleH

In this program, the reverseArray function takes an integer array as input and reverses it using two pointers (left and right) that move towards each other.

The reverseString function takes a string as input, converts it to a character array, and then reverses the character array using the same two-pointer approach.

Both reversed arrays and strings are displayed as output.

Search
Related Articles

Leave a Comment: