Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
Now Reading
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
When working with strings in Java, it’s necessary to reverse their order. Java provides an in-built reverse function to make the task simple. So whether you’re a professional or a novice, read on to learn how to reverse a string in Java word by word and more.
Reversing a string in Java is a general operation, and Java offers various methods for the task. The in-built reverse function in Java is one of the most direct ways to reverse a string.
However, instead of relying on Java utilities, you can reverse a string in Java using your logic. Let’s explore how to reverse a string in Java.
String originalString = "Good Morning!";
StringBuilder reversedString = new StringBuilder(originalString).reverse();
String finalString = reversedString.toString();
System.out.println(finalString);
We need to follow the steps below to use the reverse function in Java:
1. Create a StringBuilder object and give its constructor the initial String as an argument.
2. Use the StringBuilder object's reverse() function to reverse the string's character order.
3. Use the toString() method to convert the inverted StringBuilder object back to a String before assigning it to a new variable.
4. Print the reversed String to the console using the System.out.println() method.
String originalString = "Good Morning!";
StringBuilder reversedString = new StringBuilder();
int i = originalString.length() - 1;
while (i >= 0) {
reversedString.append(originalString.charAt(i));
i--;
}
System.out.println(reversedString.toString());
We need to follow the steps below to reverse a string in Java using a while loop
1. Create a StringBuilder object and pass the original String to its constructor.
2. Initialize an integer variable to the length of the String minus 1.
3. Begin a while loop that continues as long as the index is greater than or equal to zero.
4. In each repetition, add the character at the current index to the StringBuilder object using the append() method.
5. Decrease the index by one.
6. After the loop completes, turn the StringBuilder object into a String using the toString() method.
7. Print the reversed String to the console using System.out.println().
Reversing a string using a For Loop:
String originalString = "Good Morning!";
StringBuilder reversedString = new StringBuilder();
for (int i = originalString.length() - 1; i >= 0; i--) {
reversedString.append(originalString.charAt(i));
}
System.out.println(reversedString.toString());
To reverse a string in Java using for loop, you can follow the steps below:
1. Make a StringBuilder object.
2. Initialize an integer variable to the length of the String minus 1.
3. Start a for loop that beings from the last character in the String and ends at the first character.
4. Get the character at the current position in the for loop, and add it to the StringBuilder object using the append() method.
5. Change the StringBuilder object into a String using the toString() method after the for loop completes.
6. Print the reversed String to the console using System.out.println().
A while loop and a for loop can reverse a string in Java, producing the same result.
String originalString = "Good Morning!";
byte[] byteArray = originalString.getBytes();
byte[] reversedByteArray = new byte[byteArray.length];
for (int i = 0; i < byteArray.length; i++) {
reversedByteArray[i] = byteArray[byteArray.length - 1 - i];
}
String reversedString = new String(reversedByteArray);
System.out.println(reversedString);
1. Make a String variable and initialize it with a string value.
2. Use the String class’ getBytes() method to convert the original string into a byte array.
3. Make a new byte array called reversedByteArray with the same length as the byteArray.
4. Use a for loop to repeat over the byteArray from right to left and copy each byte into the corresponding index in the reversedByteArray
5. Change the reversedByteArray back into a String using the String constructor that takes a byte array as an argument.
6. Print the reversedString to the console using the println() method.
String originalString = "Good Morning!";
ArrayList<Character> charList = new ArrayList<>();
for (char c : originalString.toCharArray()) {
charList.add(c);
}
Collections.reverse(charList);
StringBuilder reversedStringBuilder = new StringBuilder(charList.size());
for (Character c : charList) {
reversedStringBuilder.append(c);
}
String reversedString = reversedStringBuilder.toString();
System.out.println(reversedString);
1. Create a String variable called originalString and set its value to the desired string.
2. Make an empty ArrayList object called charList to store the string characters.
3. Utilize a for loop to repeat over each character in the originalString and add it to the charList using the add() method of the ArrayList class.
4. Use the reverse() method of the Collections class to reverse the order of the elements in the charList.
5. Create a StringBuilder object called reversedStringBuilder with an initial capacity equal to the size of the charList.
6. Create a for-each loop to repeat over every character in the charList and add it to the reversedStringBuilder utilizing the append() function of the StringBuilder class.
7. Convert the reversedStringBuilder object to a String using the StringBuilder class's toString() method, then assign it to a new String variable called reversedString.
8. Print the reversedString to the console using the println() method.
String originalString = "Good Morning!";
StringBuffer reversedStringBuffer = new StringBuffer(originalString);
reversedStringBuffer.reverse();
String reversedString = reversedStringBuffer.toString();
System.out.println(reversedString);
1. Make a String variable and assign a string value to it.
2. Make a StringBuffer object by passing the originalString to its constructor.
3. Call the reverse() method on the StringBuffer object. This method will reverse the contents of the StringBuffer object.
4. Use the toString() method to convert the reversedStringBuffer to a String.
5. Print the reversed String to the console using the println() method.
import java.util.Stack;
public class ReverseStringUsingStack {
public static void main(String[] args) {
String originalString = "Good Morning!";
Stack<Character> stack = new Stack<>();
for (char c : originalString.toCharArray()) {
stack.push(c);
}
StringBuilder reversedStringBuilder = new StringBuilder();
while (!stack.empty()) {
reversedStringBuilder.append(stack.pop());
}
String reversedString = reversedStringBuilder.toString();
System.out.println(reversedString);
}
}
1. Create a Stack object called stack.
2. Make a String variable called originalString and set its value to the string you want to reverse.
3. Use a for-each loop to repeat over each character in the originalString string.
4. Push each character onto the stack within the loop using the push() method.
5. Create a StringBuilder object called reversedStringBuilder.
6. Make a while loop that runs as long as the stack is not empty.
7. Use the pop() method within the loop to retrieve the topmost element off the stack and add it to the reversedStringBuilder.
8. After the loop completes, convert the reversedStringBuilderb to a String using the toString() method.
9. Compile the reversed string to the console using the System.out.println() method.
public class ReverseStringUsingCharArray {
public static void main(String[] args) {
String originalString = "Good Morning!";
char[] originalArray = originalString.toCharArray();
int left = 0;
int right = originalArray.length - 1;
while (left < right) {
char temp = originalArray[left];
originalArray[left] = originalArray[right];
originalArray[right] = temp;
left++;
right--;
}
String reversedString = new String(originalArray);
System.out.println(reversedString);
}
}
1. Create a String variable called originalString with a desired value.
2. Convert the originalString to a char array using the toCharArray() method.
3. Initialize left and right integer variables to 0 and the length of the char array minus 1, respectively.
4. Enter a while loop while left is less than right.
5. Inside the while loop, swap the characters at originalArray[left] and originalArray[right].
6. Increment left and decrement right.
7. Convert the char array back to a String using the String constructor that takes a char array as a parameter.
8. Print the reversedString to the console using the println() method.
public class ReverseStringUsingRecursion {
public static void main(String[] args) {
String originalString = "Good Morning!";
String reversedString = reverse(originalString);
System.out.println(reversedString);
}
public static String reverse(String str) {
if (str.length() == 0) {
return "";
}
return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
}
}
1. Create a String variable called originalString and assign it "Good Morning!".
2. Call the reverse() method and pass the originalString as an argument.
3. Check if the input string is 0 inside the reverse() method.
4. If the length is not 0, use recursion to reverse the string subset and add the last character.
5. Return the reversed string to the calling method.
public class ReverseStringUsingSubstring {
public static void main(String[] args) {
String originalString = "Good Morning!";
String reversedString = "";
for (int i = originalString.length() - 1; i >= 0; i--) {
reversedString += originalString.substring(i, i + 1);
}
System.out.println(reversedString);
}
}
1. Create a String variable named originalString and assign it the value "Good Morning!".
2. Create an empty String variable named reversedString.
3. Use a for loop to iterate over the characters of the originalString variable in reverse order:
4. Print the reversedString variable to the console using the println() method.
public class ReverseStringUsingCharArray {
public static void main(String[] args) {
String originalString = "Good Morning!";
char[] charArray = originalString.toCharArray();
int left = 0;
int right = charArray.length - 1;
while (left < right) {
swap(charArray, left, right);
left++;
right--;
}
String reversedString = new String(charArray);
System.out.println(reversedString);
}
public static void swap(char[] charArray, int i, int j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
}
1. Create and initialize a String variable with a value.
2. Convert the string to a char array using toCharArray().
3. Initialize leftIndex to 0 and rightIndex to length of the char array minus 1.
4. While leftIndex is less than rightIndex, swap characters at charArray[leftIndex] and charArray[rightIndex].
1. Increase leftIndex and decrease rightIndex.
2. Convert the char array back to a String using the String constructor.
3. Print the reversed String to the console.
import java.util.*;
public class ReverseStringUsingCollections {
public static void main(String[] args) {
String originalString = "Good Morning!";
List<Character> charList = new ArrayList<Character>();
for (char c : originalString.toCharArray()) {
charList.add(c);
}
Collections.reverse(charList);
String reversedString = "";
for (char c : charList) {
reversedString += c;
}
System.out.println(reversedString);
}
}
1. Create a String variable called originalString and set it to a desired value.
2. Create an ArrayList of characters called charList.
3. Iterate over the characters of the originalString using a for-each loop and add each character to the charList.
4. Use the reverse() method from the Collections class to reverse the order of the elements in the charList.
5. Create an empty String variable called reversedString.
6. Iterate over the reversed charList using a for-each loop and add each character to the reversedString.
7. Print the reversedString to the console.
The getBytes() method under the String class turns a String into a byte array. It can be helpful in many operations.
However, the encoding process used during conversion should be carefully chosen as it can impact the resulting byte array.
StringBuilder includes a reverse() method that alters the object in place and reverses the character order.
This is perhaps more efficient than generating a new object. reverse() can quickly reverse a string for display or processing.
The String class offers a method called toCharArray(), which can convert a String to a char array.
It can be helpful when altering individual characters in the String, such as reversing the order of the characters.
We can follow these steps to reverse a string in Java using Scanner to get user input:
1. Create a Scanner object to read user input.
2. Get the user to enter a String and store the input in a String variable.
3. Change the String to a char array using the toCharArray() method.
4. Reuse the method as before to reverse the character order.
5. Change the reversed char array back to a String using the String constructor that takes a char array as an argument.
6. Print the reversed String to the console.
Java provides many methods for reversing strings, including turning the string to a character array, using the StringBuilder class, or converting the string to a byte array.
Each method has advantages and can be used based on the demands of the current task. Java code can be written more effectively and efficiently by understanding these several programming problem-solving approaches.
1. What is the simplest way in Java to reverse a string?
The in-built reverse function is the simplest way to reverse a string in Java.
2. How can a for loop in Java reverse a string?
You can first turn a string into a character array in Java, iterate over the array in reverse order, and then add each character to a fresh string.
3. How can a for loop in Java reverse a string?
You can first turn a string into a character array in Java, iterate over the array in reverse order, and then add each character to a fresh string.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...