Last Updated:

How to flip a line in Java

flip a line in Java

In this article, we'll look at a few ways to flip (invert) a string.

Invert a string using StringBuilder

 

The easiest way, which does not require any additional libraries, is to use the standard StringBuilder:

 

StringBuilder sb = new StringBuilder("Hello World 1");
System. out. println(sb. reverse());

The result of inverting the row:

 

1 rome ,tevirP

Flip a line using the StringUtils library

 

If your project already has a StringUtils library, it will be convenient to use it. If you have not connected the library, you can do so by connecting a dependency in the pom file.xml:

 

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>

Now, in order to display the string in reverse order, let's use the StringUtils.reverse method:

 

String s = "Hello World 2";
System. out. println(StringUtils. reverse(s));

Result:

2 rome ,tevirP

 

By the way, in the same class there is a method StringUtils.reverseDelimited, which inverts the string not by character, but by word. He needs to specify the input string and separator between the words:

 

String s = "Hello World 2";
System. out. println(StringUtils. reverseDelimited(s, ' '));

Result:

2 World Hello,

Invert the string using the char[] array

 

The two ways to invert a string are the easiest, most readable, and most convenient. But just in case, here is another way using the char array:

 

String s = "Hello World 3";
 
char[] result = s. toCharArray();
 
int startIndex = 0;
int endIndex = result. length - 1;
char temp;
 
for (; endIndex > startIndex; startIndex++, endIndex--) {
temp = result[startIndex];
result[startIndex] = result[endIndex];
result[endIndex] = temp;
}
 
System. out. println(result);

Here, we first convert the input string to an array of characters, then sequentially swap the characters using the intermediate variable temp.

 

The result of the implementation of such a program:

3 rome ,tevirP

 

This method is more cumbersome and less convenient, so we recommend that you use the first two methods. However, this question may occur in an interview for the Junior Java Developer position.

 

Conclusion

 

There are many ways to invert a string in Java. In this article, we have shown the most convenient of them.