Reverse String
Ramya K

Ramya K @ramya_kamalasekaran

About: Having 2.5 years of Experience in Software field. After a career gap planning to start my career again

Joined:
Jan 26, 2025

Reverse String

Publish Date: May 23
1 0

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);
}
Enter fullscreen mode Exit fullscreen mode

}`
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.

**

  1. 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());
}
Enter fullscreen mode Exit fullscreen mode

}`

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);
}
Enter fullscreen mode Exit fullscreen mode

}`
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.

Comments 0 total

    Add comment