Java Tutorial
This java program accepts the string entered by user and reverses the string using for loop and prints the reversed string.
length method is used to get the number of characters in the string.
charAt method is used to get the character of the specified index in the string.
import java.util.*; public class ReverseString { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Reverse String"); System.out.println("-----------------"); System.out.println("Enter String: "); String str = sc.nextLine(); String reverse = ""; for(int i=str.length()-1;i>=0;i--){ reverse = reverse + str.charAt(i); } System.out.println("Reverse String: "+reverse); } }Output:
D:\Java_Programs>javac ReverseString.java D:\Java_Programs>java ReverseString Reverse String ----------------- Enter String: testing program Reverse String: margorp gnitset
import java.util.*; public class ReverseString { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Reverse String"); System.out.println("-----------------"); System.out.println("Enter String: "); String str = sc.nextLine(); String reverse = ""; int i=str.length()-1; while(i>=0){ reverse = reverse + str.charAt(i); i--; } System.out.println("Reverse String: "+reverse); } }Output:
D:\Java_Programs>javac ReverseString.java D:\Java_Programs>java ReverseString Reverse String ----------------- Enter String: codingpointer! Reverse String: !retniopgnidoc
import java.util.*; public class ReverseString { public static String reverse(String original, String rev, int index){ if(index>=0) { return original.charAt(index)+reverse(original, rev, index-1); } return ""; } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Reverse String"); System.out.println("-----------------"); System.out.println("Enter String: "); String str = sc.nextLine(); String rev = ""; int i=str.length()-1; rev = reverse(str, rev, i); System.out.println("Reverse String: "+rev); } }Output:
D:\Java_Programs>javac ReverseString.java D:\Java_Programs>java ReverseString Reverse String ----------------- Enter String: codingpointer! Reverse String: !retniopgnido
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page