Reverse String using Java Program

In this tutorial, We will show you about How to Reverse String using Java Program Example. In Java you can reverse the String using no of ways. Here I have attached some of Example program snippet. That will give you idea about reversing string with different methodologies using Java. The below all programs was tested and output is shared in the same post.

Note: since all example going to have the same outcome. So the output of the programs are shared in the below of the same article.

Example1.java

In this example, We are using the predefined method such as reverse(). which belongs to StringBuffer class in Java. In order to reverse the given string.

package com.dineshkrish.example;
public class Example1 {
public static void main(String[] args) {
// Original String
String strValue = "Java Programmer";
StringBuffer sb = new StringBuffer(strValue);
// Reversed String
String revStrValue = String.valueOf(sb.reverse());
// Printing both accordingly
System.out.println("Orginal String : " + strValue);
System.out.println("Reversed String : " + revStrValue);
}
}

Example2.java

In this example, We are converting the string into character array by using predefined method such as toCharArray(), Which is belongs to String class itself. Then we are Iterating the character array using for loop and appending the each elements to String variable. In the reverse order.

package com.dineshkrish.example;
public class Example2 {
public static void main(String[] args) {
// Original String
String strValue = "Java Programmer";
char[] charArray = strValue.toCharArray();
// Reversed String
String revStrVal = "";
for (int i = (strValue.length() - 1); i >= 0; i--) {
revStrVal += charArray[i];
}
// Printing both accordingly
System.out.println("Orginal String : " + strValue);
System.out.println("Reversed String : " + revStrVal);
}
}

Example3.java

In this example, We are converting the string object to character array using toCharArray(). Then we are reversing the array using the below logic mentioned. In order to reverse the string.

package com.dineshkrish.example;
public class Example3 {
public static void main(String[] args) {
// Original String
String strValue = "Java Programmer";
char[] charArray = strValue.toCharArray();
// Reversing the char array
for (int i = 0; i < charArray.length / 2; i++) {
char temp = charArray[i];
charArray[i] = charArray[charArray.length - 1 - i];
charArray[charArray.length - 1 - i] = temp;
}
// Printing both accordingly
System.out.println("Orginal String : " + strValue);
System.out.println("Reversed String : " + String.valueOf(charArray));
}
}

Output

——————-
Orginal String : Java Programmer
Reversed String : remmargorP avaJ

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *