1. Reversing String using charArray
`package com.string;
public class Reverse_String {
public static void main(String[] args) {
String original="example";
String reverse="";
char[] c=original.toCharArray();
for(int i=c.length-1;i>=0;i--) {
reverse+=c[i];
}
System.out.println(reverse);
}
}`
Output:
elpmaxe
Explanation:
String is converted into character by using tochaArray(). Then we are iterating the char array from reverse. New empty string is created for concatenation and display the output.
**
- Reversing string using string function** `package com.string;
public class Reverse_using_StringBuilder {
public static void main(String[] args) {
String str="hello";
StringBuilder rev=new StringBuilder(str);
System.out.println(rev.reverse());
}
}`
Output:
olleh
Explanation:
StringBuilder has predefined function reverse using that string is reversed.
3.Reversing String using Stream API
`package com.string;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Reverse_using_StreamAPI {
public static void main(String[] args) {
String string="hello java world";
String[] strarr=string.split(" ");
String reverseword=Stream.of(strarr)
.map(word->new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
System.out.println(reverseword);
}
}`
Output:
olleh avaj dlrow
Explanation:
String has couple of words. So first splitted the word using split function then the string converted as array. Stream of function accepts array. In map function using lambda expression using String Builder reverse function each word is reversed then using collect function collectors .joining joined all the words with space and finally displayed reversed string.