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

Time Complexity, Space Complexity, Asymptotic Notations - The Coding Shala

Graph Representation using Adjacency Matrix - The Coding Shala

LeetCode - Crawler Log Folder Solution - The Coding Shala

Java Method Overloading - The Coding Shala

Client-Server Java Program (Socket Programming) - The Coding Shala