String Reverse in Java Interview Questions
A string is a collection of characters that is recognised as an object in Java. In Java, there are numerous operations that may be performed on the String object. One of the most often used operations on a string object is string reverse. Let's have a look at the various Java techniques for reversing a string. There are some fascinating details regarding the String and StringBuilder classes. They are mainly:
- String objects are immutable.
- There is no reverse() method for the String class in Java, although there is one for the StringBuilder class.
- While the toCharArray() method is present in the String class, it is absent in the StringBuilder class.
There are numerous ways to do this, and we'll go over the following ones:
- CharAt techniques are used.
- employing an iterative reverse process.
- Using the String Buffer method.
- the string is changed into bytes
- using an object from an array list.
The main ideas of reversing a string will be:
- The goal is to run the string's length.
- While navigating, extract each character.
- Add every character to the string's front.
Let’s see an example:
1)Write a program to reverse a word.
Ans:
import java.io.*;
import java.util.Scanner;
class {
public static void main (String[] args) {
String s= "iava", n="";
char c;
System.out.print("Main word: ");
System.out.println("java"); //take an example like
for (int i=0; i<s.len(); i++)
{
c= s.charAt(i); //extraction of character
ns= c+ns; //adding the new character to the already exsisted one
}
System.out.println("The word that reversed: "+ ns);
}
}
Output:
Main word: java
The word that reversed: avaj
2)Write a program by changing a String to Bytes.
Ans: To change a String to Bytes, utilise the getBytes() method[].
Method:
- Make a temporary byte[] that is the same size as the input string.
- Put the bytes (that we obtained using the getBytes() function) into the temporary byte[] in reverse order.
- Make a new String subject using the result's byte[] storage.
import java.lang.*;
import java.io.*;
import java.util.*;
class RevStr {
public static void main(String[] args)
{
Str ip = "javatpoint";
// to convert string use getBytes()
byte[] strAsByteArray = ip.getBytes();
byte[] res = new byte[strAsByteArr.len];
// Storing the result in a reverse order
//into the resbyte[]
for (int i = 0; i < strAsByteArr.len; i++)
res[i] = strAsByteArr[strAsByteArr.len- i - 1];
System.out.println(new Str(res));
}
}
Output:
tnioptavaj
3)Write a program by the stringbuilder class in reverse method.
Ans: The StringBuilder class's built-in reverse() method can be used:
Since the String class lacks a reverse() method, we must transform the input string to a StringBuilder instead. This is done by utilizing the StringBuilder's append method. Print the characters of the inverted string after that by scanning through the first through the final index.
import java.lang.*;
import java.io.*;
import java.util.*;
class RevStr {
public static void main(String[] args)
{
Str ip= "Hello world";
StringBuilder ip1 = new StringBuilder
// adding a string to the StringBuilder ip1
ip1.append(ip);
// reversing the StringBuilder ip1
ip1.rev();
// printing the String which is reversed
System.out.println(ip1);
}
}
Output:
dlrow olleH
4)Write a program so that the user entered the phrase to be inverted when converting a string to a character array.
Ans: The user entered the phrase to be inverted when converting a string to a character array.
Method:
1. First, use the Java String class's built-in toCharArray function to convert a String to a character array ().
2. After that, print each character as you scan this string from beginning to end.
import java.lang.*;
import java.io.*;
import java.util.*;
class RevStr{
public static void main(String[] args)
{
Str ip= "Javatpoint";
// converting the String into array which is a character
// use toCharArray
char[] t1 = ip.toCharArray();
for (int i = t1.len - 1; i >= 0; i--)
System.out.print(t1[i]);
}
}
Output:
tnioptavaJ
5)Write the program by utilizing the toCharArray() function to convert the supplied string into a character array.
Ans: using the toCharArray() function to create a character array from the supplied string. To turn a input word into the a character array, use the String Class's built-in toCharArray() function. The character array is then simultaneously scanned from of the start value (left) and the last index (right) on both sides.
- Set the right index to -1 for the string's length and the left index to 0.
- One by one, swap the characters from the start index scanning with the ones from the end index scanning. To move on to the following characters in the character array, increase the left index by 1 (left++) and reduce the right index by 1 (right--).
- Continue until left is equal to or less than the right.
import java.lang.*;
import java.io.*;
import java.util.*;
class RevStr {
public static void main(String[] args)
{
Str ip= "I love India";
char[] temparr = ip.toCharArray();
int l, r = 0;
r= temparr.len - 1;
for (l = 0; l < r; l++, r--) {
// Swapping values from left to right
Ch temp = temparr[l];
temparr[l] = temparr[r];
temparr[r] = temp;
}
for (char ch : temparr)
System.out.print(ch);
System.out.println();
}
}
Output:
aidni evol I
6) Write a program using the built-in toCharArray() function.
Ans: The input string can be turned into a character array by utilising the ArrayList object's built-in toCharArray() function. After that, add the characters from the array to the ArrayList object. The Collections class in Java comes with a built-in function called reverse(). We will use the ArrayList object, a type of list of characters, since the reverse() method of the Collections class requires a list object, in order to reverse the list.We copy the contents of a String to an ArrayList object.
- Using the listIterator() function on the ArrayList object, we build a ListIterator object.
- The list is iterated through using a ListIterator object.
- The ListIterator object enables us to repeatedly iterate over the inverted list and print each item one at a time to the output screen.
import java.lang.*;
import java.io.*;
import java.util.*;
class RevStr {
public static void main(String[] args)
{
Str ip = "I love my Mother";
char[] hello = ip.toCharArr();
L<Char> trial = new ArrayL<>();
for (char ch : hi)
trial.add(ch);
Collections.rev(trial);
LIterator l = trial.listIterator();
while (l.hasNext())
System.out.print(l.next());
}
}
Output:
rehtoM ym evol I
7)Write a program using StringBuffer.
Ans: Using stringbuffe. Since the String class lacks a reverse() method, we must use the StringBuffer reverse method to convert the input string to a StringBuffer.
Program:
import java.lang.*;
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args)
{
Str s = "Sahi";
StringBuffer sb = new StringBuffer(s);
// the string should be reversed
sb.rev();
System.out.println(sb);
}
}
Output:
ihaS
8)How to reverse a string using user input?
Ans: Reversing a string using user input
Program:
import java.io.*;
import java.util.Scanner;
class {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Str S = sc.nextL();
char[] array = S.toCharArr();
Str r= "";
for(int i = S.len() - 1; i >= 1; i--)
{
r = r + S.charAt(i);
}
System.out.println(r);
}
}
Output:
1
In the code above, a String is essentially read from the user before an iteration loop is started to produce a new, inverted String. The "+" operator is used to concatenate the characters into a new String after retrieving each character from the end of the original String individually using the "charAt" function of the String class.
9) How can a String be reversed?
Ans: In C, Java, Python, or any other programming language of your choice, create a programme that reverses a String. Either the recursive or iterative solution can be written. For instance, your function should return "dcba" if the input is "abcd".
10) How may a String be reversed without recursion?
Ans: Similar to the last programme, except you cannot use recursion; this time, you must use iteration or loops to solve this problem in C, Java, or Python. You can also examine the Pluralsight Algorithms and Data Structures - Part 1 and 2 courses if you are unfamiliar with recursion and repetition. One of the better courses to start with basic methods for solving problems based on algorithms.
10) How can the words in a given String statement be reversed?
Ans: Create a productive Java or C++ software that will efficiently reverse the words in a given String sentence. For instance, if the user inputs "Java is best," your software should output "Java is best." The retention of white space is not constrained.
11) Explain the difference between String and StringBuilder classes in Java.
Ans: String class is immutable, meaning once a String object is created, it cannot be modified. Any manipulation on the String object will result in a new String object being created.
StringBuilder class, on the other hand, is mutable, meaning the object can be modified without creating a new one. It has a built-in reverse() method that can be used to reverse a string.
12) What is the time complexity of each of the methods you provided for string reversal?
Ans: Using charAt(): O(n^2)
Iterative reversal: O(n)
StringBuilder reverse(): O(n)
Converting to bytes: O(n)
Using an object from ArrayList: O(n)
13) How can you optimize the charAt() method for string reversal?
Ans: By using a StringBuilder object and appending each character to it in reverse order, then calling toString() on the StringBuilder object to obtain the reversed string. This is more efficient than creating a new string object for every character appended.
14) What are some other methods you can use to reverse a string in Java?
Ans: Using recursion
Using Java 8's Stream API
Using Collections.reverse() method on a list containing the characters of the string
15) How can you reverse a string without using any built-in Java method?
Ans: By converting the string to a character array and swapping the first and last characters, then moving towards the center until the entire array is reversed. Then, converting the character array back to a string using String.valueOf().
16) Write a program to reverse a string using recursion.
Ans:
Filename: ReverseStringRecursion.java
import java.util.Scanner;
public class ReverseStringRecursion {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string to reverse: ");
String input = sc.nextLine();
String reversed = reverseString(input);
System.out.println("Reversed string: " + reversed);
}
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Input:
Enter a string to reverse: kamal
Output:
Reversed string: lamak
17) Write a program to reverse a string without using any temporary variable.
Ans:
Filename: ReverseStringNoTempVar.java
import java.util.Scanner;
public class ReverseStringNoTempVar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string to reverse: ");
String input = sc.nextLine();
char[] chars = input.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
chars[left] = (char) (chars[left] ^ chars[right]);
chars[right] = (char) (chars[left] ^ chars[right]);
chars[left] = (char) (chars[left] ^ chars[right]);
left++;
right--;
}
String reversed = new String(chars);
System.out.println("Reversed string: " + reversed);
}
}
Input:
Enter a string to reverse: kal
Output:
Reversed string: lak
18) Write a program to reverse each word in a sentence.
Ans:
Filename: ReverseWordsInSentence.java
import java.util.Scanner;
public class ReverseWordsInSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String input = sc.nextLine();
String[] words = input.split("\\s+");
StringBuilder reversed = new StringBuilder();
for (String word : words) {
reversed.append(reverseString(word)).append(" ");
}
System.out.println("Reversed sentence: " + reversed.toString().trim());
}
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Input:
Enter a sentence: lol
Output:
Reversed sentence: lol
19) Write a program to reverse a string using the StringBuffer class.
Ans:
Filename: ReverseStringStringBuffer.java
import java.util.Scanner;
public class ReverseStringStringBuffer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string to reverse: ");
String input = sc.nextLine();
StringBuffer sb = new StringBuffer(input);
String reversed = sb.reverse().toString();
System.out.println("Reversed string: " + reversed);
}
}
Input:
Enter a string to reverse: kal
Output:
Reversed string: lak
20) Write a program to reverse a sentence in Java
Ans: To reverse a sentence in Java, we can first split the sentence into words using the split() method of the String class. Then, we can reverse the array of words and join them again to form the reversed sentence.
Filename: ReverseSentence.java
import java.util.Arrays;
public class ReverseSentence {
public static void main(String[] args) {
String sentence = "Hello world, how are you?";
// Split the sentence into words using space as delimiter
String[] words = sentence.split(" ");
// Reverse the array of words
for (int i = 0, j = words.length - 1; i < j; i++, j--) {
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
// Join the reversed words to form the reversed sentence
String reversedSentence = String.join(" ", words);
System.out.println(reversedSentence);
}
}
Output:
you? are how world, Hello