how to reverse string in java code example
Example 1: reverse string java
String string="whatever";
String reverse = new StringBuilder(string).reverse().toString();
System.out.println(reverse);
Example 2: Reverse a string in java without using reverse function
import java.util.Scanner;
public class ReverseWithoutFunction
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string: ");
String strInput = sc.nextLine();
int len = strInput.length();
String strReverse = "";
System.out.println("Reverse a string without using reverse function: ");
for(int a = len - 1; a >= 0; a--)
{
strReverse = strReverse + strInput.charAt(a);
}
System.out.println(strReverse);
sc.close();
}
}
Example 3: how to reverse a string in java
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
Example 4: java string reverse
String str = "Reverse this strings";
for (int i = str.length() - 1; i >= 0; i--) {
System.out.print(str.charAt(i));
}
StringBuffer sb = new StringBuffer();
sb.append(str);
System.out.print(sb.reverse().toString());
StringBuilder sb = new StringBuilder();
sb.append(str);
System.out.print(sb.reverse().toString());
Example 5: java reverse a string
public static String solution(String str) {
return new StringBuffer(str).reverse().toString();
}
public static String solution(String str) {
char[] chars = str.toCharArray();
for(int i = 0, j = str.length() - 1; i < j; i++, j--) {
char ch = chars[i];
chars[i] = chars[j];
chars[j] = ch;
}
return new String(chars);
}
Example 6: java string reverse
String rev = new StringBuilder("Your String").reverse().toString();