Posts

Showing posts from April, 2017

Different ways to reverse a string in java program

There are multiple ways to reverse a string in java progarm 1. Using for loop: import java.util.Scanner; public class JavaReverseString{ public static void main( String [] args) { Scanner sc= new Scanner ( System . in ); System . out .println("Enter the string to reverse: "); String str = sc.nextLine(); System . out .println("String after reverse: "); for ( int i = str.length()-1; i >=0; i--) { System . out .print(str.charAt(i)); } } } 2. Using StringBuffer import java.util.Scanner; public class JavaReverseString{ public static void main( String [] args) { Scanner sc = new Scanner ( System . in ); System . out .println("Enter the string to reverse: "); String str = sc.nextLine(); String reverse = new StringBuffer (str).reverse().toString(); System . out .println("String after reverse:" + reverse); } } ...