image Post Your Answer


image

Reverse a string in JAVA

5 years ago in Machine Learning By Prithvi Patel


I have used following code to reverse a string in JAVA. But the string is not reversed at the output. Please help!

All Answers (2 Answers In All)

By Renu Answered 5 years ago

There is an error in your code. That is why you aren’t getting an output. The integer ‘i’ is not incremented, instead it is decremented and the length is also decremented. import java.util.*; class ReverseString { public static void main(String args[]) { String original, reverse = “”; Scanner in = new Scanner(System.in); System.out.println(“Enter a string to reverse”); original = in.nextLine(); int length = original.length(); for (int i = length – 1 ; i >= 0 ; i–) reverse = reverse + original.charAt(i); System.out.println(“Reverse of the string: ” + reverse); } }


By Riya N Answered 5 years ago

You can reverse the string using stringbuilder as well public class Main { public static void main(String args[]) { String number = “1234”; System.out.println(“original String: ” + number); String reversed = inPlaceReverse(number); System.out.println(“reversed String: ” + reversed); }


Your Answer


View Related Questions