A string is a chain of characters that behave like an object in Java. The string is among the maximum commonplace and used knowledge buildings after arrays. It’s an object that retail outlets the information in a personality array.
For higher readability, simply believe a string as a personality array in which you’ll be able to resolve many string-based issues.
To create a string object, you wish to have the java.lang.String magnificence. Java programming makes use of UTF -16 to constitute a string. Strings are immutable in order that their interior state stays consistent after the thing is solely created. The string object plays quite a lot of operations, however opposite strings in Java are probably the most extensively used serve as.
Find out how to Opposite a String in Java?
Because the strings are immutable items, you wish to have to create every other string to opposite them. The string magnificence does not have a opposite option to opposite the string. It has a toCharArray() option to do the opposite.
By way of The use of toCharArray()
The code underneath will mean you can know the way to opposite a string. By way of the use of toCharArray() way is one method to opposite a string in Java.
The code additionally makes use of the period, which provides the overall period of the string variable.
The for loop iterates until the tip of the string index 0.
Code
//ReverseString the use of CharcterArray.
public static void primary(String[] arg) {
// pointing out variable
String stringinput = “Unbiased”;
// convert String to personality array
// through the use of toCharArray
char[] resultarray = stringinput.toCharArray();
//iteration
for (int i = resultarray.period – 1; i >= 0; i–)
// print reversed String
Gadget.out.print(resultarray[i]);
}
Output
![ReverseAStringInJava_1](https://www.simplilearn.com/ice9/free_resources_article_thumb/ReverseAStringInJava_1.png)
By way of The use of StringBuilder
Allow us to see opposite a string the use of the StringBuilder magnificence. StringBuilder or StringBuffer magnificence has an in-build way opposite() to opposite the characters within the string. This system replaces the series of the characters in opposite order. The opposite way is the static way that has the good judgment to opposite a string in Java.
Within the code discussed underneath, the thing for the StringBuilder magnificence is used.
The StringBuilder items are mutable, reminiscence environment friendly, and fast in execution. But it surely additionally considers those items as no longer thread-safe.
The thing calls the built in opposite() option to get your required output.
This can be a most well-liked way and regularly used to opposite a string in Java.
Code:
//ReverseString the use of StringBuilder.
public static void primary(String[] arg) {
// pointing out variable
String enter = “Unbiased”;
// developing StringBuilder object
StringBuilder stringBuildervarible = new StringBuilder();
// append a string into StringBuilder stringBuildervarible
//append is in-built option to append the information
stringBuildervarible.append(enter);
// opposite is in-built way in StringBuilder to make use of opposite the string
stringBuildervarible.opposite();
// print reversed String
Gadget.out.println( “Reversed String : ” +stringBuildervarible);
}
Output:
On the other hand, you’ll be able to additionally use the StringBuffer magnificence opposite() way very similar to the StringBuilder. Each the StringBuilder magnificence and StringBuffer magnificence, paintings in the similar option to opposite a string in Java. Taking into account opposite, each have the similar more or less way. Despite the fact that, StringBuilder magnificence is majorly favored and most well-liked when in comparison to StringBuffer magnificence. The StringBuilder magnificence is quicker and no longer synchronized. Those StringBuilder and StringBuffer categories create a mutable series of characters. To succeed in the specified output, the opposite() way will mean you can.
In Java, it’ll create new string items while you deal with string manipulation for the reason that String magnificence is immutable. The StringBuilder and StringBuffer categories are two software categories in java that deal with useful resource sharing of string manipulations.
By way of The use of Whilst Loop or For Loop
Merely deal with the string inside the whilst loop or the for loop. Get the period of the string with the assistance of a cursor transfer or iterate in the course of the index of the string and terminate the loop.
The loop prints the nature of the string the place the index (i-1).
The loop begins and iterates the period of the string and reaches index 0.
Code The use of Whilst Loop
// Java program to opposite a string the use of Whilst loop
import java.lang.*;
import java.io.*;
import java.util.*;
public magnificence strReverse {
public static void primary(String[] args)
{
String stringInput = “My String Output”;
//Get the String period
int iStrLength=stringInput.period();
//The use of Whilst loop
whilst(iStrLength >0)
{
Gadget.out.print(stringInput.charAt(iStrLength -1));
iStrLength–;
}
}
}
Output:
Code The use of For Loop
// Java program to opposite a string the use of For loop
import java.lang.*;
import java.io.*;
import java.util.*;
public magnificence strReverse {
public static void primary(String[] args)
{
String stringInput = “My New String”;
//Get the String period
int iStrLength=stringInput.period();
//The use of For loop
for(iStrLength=stringInput.period();iStrLength >0;– iStrLength)
{
Gadget.out.print(stringInput.charAt(iStrLength -1));
}
}
}
Output:
By way of Changing a String to Bytes
The getBytes() way will break up or convert the given string into bytes. The brief byte array period shall be equivalent to the period of the given string. Get the bytes in opposite order and retailer them in every other byte array.
Within the code underneath, a byte array is quickly created to deal with the string. The getBytes() could also be an built in option to convert the string into bytes. There are two byte arrays created, one to retailer the transformed bytes and the opposite to retailer the end result within the opposite order.
Code
//ReverseString the use of ByteArray.
public static void primary(String[] arg) {
// pointing out variable
String inputvalue = “Unbiased”;
// getBytes() is in-built way to transform string
// into bytes[].
byte[] strAsByteArray = inputvalue.getBytes();
byte[] resultoutput = new byte[strAsByteArray.length];
// Retailer lead to opposite order into the
// outcome byte[]
for (int i = 0; i < strAsByteArray.period; i++)
resultoutput[i] = strAsByteArray[strAsByteArray.length – i – 1];
Gadget.out.println( “Reversed String : ” +new String(resultoutput));
}
Output:
By way of The use of ArrayList Object
The use of the integrated way toCharArray(), convert the enter string into a personality array. Then, within the ArrayList object, upload the array’s characters. The Collections magnificence in Java additionally has a integrated opposite() serve as. Because the opposite() way of the Collections magnificence takes a listing object, use the ArrayList object, which is a listing of characters, to opposite the checklist.
Reproduction the String contents to an ArrayList object within the code underneath. Then, the use of the listIterator() way at the ArrayList object, assemble a ListIterator object. To iterate over the array, use the ListIterator object. It additionally is helping iterate in the course of the reversed checklist and printing each and every object to the output display screen one-by-one.
Additionally Learn: What’s Java API, its Benefits and Want for it
Code
// Java program to Opposite a String the use of ListIterator
import java.lang.*;
import java.io.*;
import java.util.*;
// Elegance of ReverseString
magnificence ReverseString {
public static void primary(String[] args)
{
String enter = “Opposite a String”;
char[] str = enter.toCharArray();
Listing<Personality> revString = new ArrayList<>();
for (char c : str)
revString.upload(c);
Collections.opposite(revString);
ListIterator li = revString.listIterator();
whilst (li.hasNext())
Gadget.out.print(li.subsequent());
}
}
Output:
By way of The use of StringBuffer
The String magnificence calls for a opposite() serve as, therefore first convert the enter string to a StringBuffer, the use of the StringBuffer way. Then use the opposite() option to opposite the string.
Code
// Java program to transform String to StringBuffer and opposite of string
import java.lang.*;
import java.io.*;
import java.util.*;
public magnificence strReverse {
public static void primary(String[] args)
{
String str = “String”;
// conversion from String object to StringBuffer
StringBuffer sbfr = new StringBuffer(str);
// To opposite the string
sbfr.opposite();
Gadget.out.println(sbfr);
}
}
Output:
The use of Stack
You’ll be able to use the Stack knowledge construction to opposite a Java string the use of those steps:
- Create a stack that’s empty of characters.
- Convert a given string into a personality array through the use of the String.toCharArray() way, then push each and every personality into the stack.
- Take characters out of the stack till it’s empty, then assign the characters again into a personality array. The characters will input in opposite order.
- Then convert the nature array right into a string through the use of String.copyValueOf(char[]) after which go back the shaped string.
Code
import java.util.Stack; magnificence Primary { // Technique to opposite a string in Java the use of a stack and personality array public static String opposite(String str) { // base case: if the string is null or empty if (str == null || str.equals(“”)) { go back str; } // create an empty stack of characters Stack<Personality> stack = new Stack<Personality>(); // push each and every personality of the given string into the stack char[] ch = str.toCharArray(); for (int i = 0; i < str.period(); i++) { stack.push(ch[i]); } // get started from index 0 int ok = 0;
|
supply: www.simplilearn.com