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
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
Now Reading
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Sorting a string is a common task in programming, and Java provides powerful tools and techniques to accomplish this efficiently. Whether you need to arrange characters in ascending or descending order, Java's extensive library offers various methods and algorithms to sort strings easily.
Sorting a string can be useful in a wide range of applications, from organizing data for efficient searching to solving complex algorithms.
In this tutorial, we will explore different ways to sort a string in Java, exploring the built-in methods provided by the Java standard library and custom implementations to understand the underlying principles better.
There are two main ways to sort a string in Java. We can either use the arrays.sort() method, or we can use Collections.sort() method. Let us explore both these methods.
The Arrays.sort() method is a convenient way to sort an array in Java. It takes an array as input and sorts its elements in ascending order using the elements' natural order. This method directly modifies the original array, sorting its elements in place. It is a simple and efficient way to sort arrays of primitive types or objects that implement the Comparable interface.
Example:
import java.util.Arrays;
public class upGradTutorials {
public static void main(String[] args) {
String[] fruits = {"Apple", "Orange", "Banana", "Grape"};
System.out.println("Before sorting:");
System.out.println(Arrays.toString(fruits));
Arrays.sort(fruits);
System.out.println("After sorting:");
System.out.println(Arrays.toString(fruits));
}
}
The Collections.sort() method is used to sort a collection in Java. It takes a collection as input and sorts its elements in ascending order using the elements' natural order.
Unlike the Arrays.sort() method, which works directly on arrays, the Collections.sort() method applies to any type of collection, including lists, sets, and queues. It uses the Comparable interface to determine the order of the elements. This method modifies the original collection, sorting its elements in place. It provides a flexible way to sort collections of objects.
Example:
import java.util.ArrayList;
import java.util.Collections;
public class upGradTutorials {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
fruits.add("Grape");
System.out.println("Before sorting:");
System.out.println(fruits);
Collections.sort(fruits);
System.out.println("After sorting:");
System.out.println(fruits);
}
}
3 important methods allow us to sort strings. Let us explore each of them with examples.
import java.util.Arrays;
public class upGradTutorials {
public static void main(String[] args) {
String[] YO = {"Aritra", "Manisha", "Sritama", "Supratik", "Atriya"};
System.out.println("Before sorting:");
System.out.println(Arrays.toString(YO));
Arrays.sort(YO);
System.out.println("After sorting:");
System.out.println(Arrays.toString(YO));
}
}
First, the program initializes a string array named YO with five elements: "Aritra", "Manisha", "Sritama", "Supratik", and "Atriya".
Next, the program prints the elements of the YO array before sorting using System.out.println and Arrays.toString(). This allows us to see the initial order of the elements.
Then, the Arrays.sort() method is called, passing the YO array as an argument. This method sorts the elements of the array in ascending order based on their natural order, which is lexicographically for strings.
After sorting, the program prints the elements of the YO array again using System.out.println and Arrays.toString(). This time, the array will display the sorted elements, showing the result of the sorting operation.
import java.util.Arrays;
public class upGradTutorials {
public static void main(String[] args) {
String[] Courses = {"Data Science", "Web Development", "Analytics", "Java"};
System.out.println("Before sorting:");
System.out.println(Arrays.toString(Courses));
Arrays.stream(Courses)
.sorted()
.toArray(String[]::new);
System.out.println("After sorting:");
System.out.println(Arrays.toString(Courses));
}
}
In this method, the program initializes a string array named Courses with four elements: "Data Science", "Web Development", "Analytics", and "Java". Before sorting, the program prints the elements of the Courses array using Arrays.toString() and System.out.println.
The Arrays.stream() method converts the Courses array into a stream of strings. Then, the sorted() method is applied to the stream to sort the elements in ascending order using the elements' natural order. However, it's important to note that this method does not assign the sorted elements back to the Courses array. Therefore, when the program prints the Courses array after sorting, it will display the original unsorted elements.
import java.util.Arrays;
import java.util.Comparator;
public class upGradTutorials {
public static void main(String[] args) {
String[] YO = {"Aritra", "Manisha", "Sritama", "Supratik", "Atriya"};
System.out.println("Before sorting:");
System.out.println(Arrays.toString(YO));
Arrays.sort(YO, Comparator.reverseOrder());
System.out.println("After sorting:");
System.out.println(Arrays.toString(YO));
}
}
In this program, the Comparator.reverseOrder() method is used as the comparator to sort the elements of the YO array in descending order. First, the program initializes a string array named YO with five elements: "Aritra", "Manisha", "Sritama", "Supratik", and "Atriya".
Next, the program prints the elements of the YO array before sorting using System.out.println and Arrays.toString(). This allows us to see the initial order of the elements. The Arrays.sort() method is called, passing the array and the custom comparator as arguments. This results in sorting the elements in descending order based on their natural order. The program then prints the elements of the YO array before and after sorting to verify the sorting operation.
To sort string array in Java in alphabetical or ascending order, you can use the Arrays.sort() method from the Java standard library. This method provides a convenient way to sort an array in its natural order. Here's an example code snippet demonstrating how to sort a string array in ascending order:
import java.util.Arrays;
public class upGradTutorials {
public static void main(String[] args) {
String[] strings = {"apple", "banana", "cherry", "date"};
System.out.println("Before sorting:");
System.out.println(Arrays.toString(strings));
Arrays.sort(strings);
System.out.println("After sorting in ascending order:");
System.out.println(Arrays.toString(strings));
}
}
In this program, we have a string array strings containing four elements: "apple", "banana", "cherry", and "date". First, the program prints the elements of the strings array before sorting using System.out.println and Arrays.toString().
Then, the Arrays.sort() method is used to sort the elements of the array in ascending order. This method arranges the strings in lexicographic order, where "apple" comes before "banana", and so on. After sorting, the program prints the elements of the strings array again, this time displaying them in the sorted order.
To sort a string in Java in descending order or reverse natural order in Java, you can use the Arrays.sort() method and a custom Comparator. The Comparator interface allows you to define a custom comparison logic for sorting objects.
Here's an example code snippet demonstrating how to sort a string array in descending order:
import java.util.Arrays;
import java.util.Collections;
public class upGradTutorials {
public static void main(String[] args) {
String[] strings = {"apple", "banana", "cherry", "date"};
System.out.println("Before sorting:");
System.out.println(Arrays.toString(strings));
Arrays.sort(strings, Collections.reverseOrder());
System.out.println("After sorting in descending order:");
System.out.println(Arrays.toString(strings));
}
}
In this program, we have the same string array strings as in the previous example. First, the program prints the elements of the strings array before sorting.
We use the Collections.reverseOrder() method to sort the array in descending order as the comparator for the Arrays.sort() method. This instructs the sort operation to arrange the strings in the reverse natural order, where "date" comes before "cherry", and so on.
After sorting, the program prints the elements of the strings array again, displaying them in descending order. Using the Arrays.sort() method with Collections.reverseOrder(), the program successfully sorts the strings in the array in descending or reverse natural order.
Sorting a string in Java is a fundamental operation that programmers often encounter in various scenarios. By understanding these techniques, you now have the tools to manipulate and order strings according to your specific requirements efficiently.
Sorting strings can be a powerful tool in data organization, search optimization, and algorithmic problem-solving. To enhance your programming skills and expand your ability to tackle diverse challenges, consider taking up a professional course offered by upGrad.
To sort a string in Java using an inbuilt function, you can utilize the Arrays.sort() method, passing in the string array as the argument, which will sort the elements in ascending order based on their natural order.
Without using an inbuilt function, you can implement a custom sorting algorithm, such as quicksort or insertion sort, to sort a string array in Java by comparing and rearranging the elements based on your desired sorting logic.
In Python, you can sort strings by using the sorted() function, which returns a new sorted list of strings, or by invoking the sort() method on a list of strings, which sorts the list in place, both by default in ascending order based on the strings' lexicographic order.
Sorting techniques in C++ include bubble, insertion, and quick sort. Hashing and using the inbuilt library function <algorithm> are other sorting methods in C++.
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...