How to convert String to String array in Java?In Java, a String is an object that represents the sequence of characters. In order to use Strings, we need to import the String class defined in java.lang package. The String array is an array of strings with a fixed length. In this section, we will learn how to convert String into String array. Note: Java strings are immutable objects, i.e., the string value cannot be changed once it is created.Converting String to String arrayThere are four ways to convert a String into String array in Java:
Using String.split() MethodThe String.split() method is used to split the string into individual strings entities based on the given delimiter (whitespace or other symbols). We can store these entities directly in a string array. Let's consider the following example where we use String.split() method to convert a string into a string array. TestSplitMethod.java Output: Example 2: In the following example, we have converted the string to a string array based on the delimiter that is a , (comma). TestSplitMethod2.java Output: Using Pattern.split() MethodThe Pattern.split() method is used to split the string into an array of strings with the help of regular expression (pattern) as the delimiter. In order to use the method, we need to import the Pattern class in our Java code as: Let's consider the following example where we split a string into an array by using the delimiter as whitespace. SplitMethodOfPatternClass.java Output: Example 2: We can also split a string into an array by using any string or pattern as a delimiter. Here, we have used the delimiter #a1. SplitMethodOfPatternClass2.java Output: The above example splits the single string into five separate strings based on the delimiter #a1. The parts of the string that matched the delimiter are not included in the array. Using String[ ] ApproachWe can simply convert string to string array by using the string index [ ]. Here, we pass the string to String [ ] {}. Consider the following example where we have used the String[] to convert a string into a string array. StrToStrArray.java Output: Using toArray() MethodWe can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array. Consider the following example where we have converted the list of strings into a string array. StringListtoArray.java Output: Next TopicHow to Encrypt Password in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India