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 Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala