How to Reverse a String in Java - The Coding Shala

Home >> Java Programs >> Reverse a String

In this post, we will learn how to Reverse a String in Java.

Reverse a String in Java

Given a string S as input. You have to reverse the given string.

Example:
Input:
3
Geeks
GeeksforGeeks
GeeksQuiz

Output:
skeeG
skeeGrofskeeG
ziuQskeeG

Approach 1
Using StringBuilder.

Java Program:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
	public static void main (String[] args)
	 {
	 //code
	 Scanner sc = new Scanner(System.in);
	 int tc = sc.nextInt();
	 while(tc-- > 0) {
	     String str = sc.next();
	     StringBuilder sb = new StringBuilder(str);
	     sb.reverse();
	     System.out.println(sb.toString());
	 }
	 }
}

Approach 2
By using for loop from end to start.

Java Program:

import java.lang.*;
import java.io.*;
class GFG
 {
	public static void main (String[] args)
	 {
	 //code
	 Scanner sc = new Scanner(System.in);
	 int tc = sc.nextInt();
	 while (tc-- > 0) {
	     String str = sc.next();
	     for(int i=str.length()-1; i>=0; i--){
	         System.out.print(str.charAt(i));
	     }
	     System.out.println();
	 }
	 }
}

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

Anti Diagonals - The Coding Shala

Java Method Overloading - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala