Header Ads Widget

Develop Your Creative Skill with
Free Design Tutorials

Our blog helps to Provide Latest Tips and Tricks tutorials about Blogging
Business, SEO Tips, much more. this Blog and stay tuned to this
blog for further updates.

Program to reverse a string in java

 Reverse String in Java

We have given a string and we have to reverse a string in Java programming languages. There can be various approaches to reverse a string in java. The best way to Reverse string in java are as follow:


Program to reverse a string in java


      Program to reverse a String In  java


This program will reverse each word of string in java.

Input -: " This is Courpedia website ".

OutPut -: "website Courpedia is This".

Source code-:  👇👇👇

Note- Package name = MyCode


package MyCode;
import java.util.*;

public class Reverse {

public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("enter the String");
String name = sc.nextLine();
int i =name.length()-1;
        String ans="";
        while(i>=0)
        {
while(i>=0 && name.charAt(i)==' ')i--;
            int k=i;
            if(i<0)break;
while(i>=0 && name.charAt(i)!=' ')i--;
            if(ans.isEmpty())
            {
ans=ans.concat(name.substring(i+1,k+1));
            }else
            {
ans=ans.concat( " " +name.substring(i+1,k+1));
            }

        }
        
        System.out.println(ans);


    }
    

}







Program to reverse a string by each character in java


Input:-  " Reverse string in Java"
Output -: "avaJ ni gnirts esreveR"

Source Code:-  👇👇




package MyCode;

import java.util.Scanner;

public class Revera {

public static void main(String[] args) 
{
Scanner sc=new Scanner(System.in);
    String S;
System.out.println("enter string");
    String name = sc.nextLine();
    int n= name.length()-1;
    for(int i=0;i<=n;i++)
    {
System.out.print(name.charAt(i));
    }
System.out.println();
    
//reverse the string now
    
for(int j=n;j>=0;j--)
    {
System.out.print(name.charAt(j));
    }

    }

}




Reverse string in java using String Builder and StringBuffer


package MyCode;

import java.util.Scanner;

public class Revera {

public static void main(String[] args
{
Scanner sc=new Scanner(System.in);

System.out.println("enter string");

String str = sc.nextLine();

StringBuilder sb = new StringBuilder(str);
    
System.out.println(sb.reverse().toString());
    

    }

}



You can reverse a string in Java in some other ways also. You should try to do a question in different ways to learn more about the core concepts of programming languages.