top

Search

Java Tutorial

.

UpGrad

Java Tutorial

String to Array in Java

Java is a high-level, robust, general-purpose, object-oriented programming language. Java programming is used in developing applications for laptops, mobiles, scientific computers, cloud computing, internet things, etc. This is a simple language that is easy to understand.

In Java, strings are widely used. Strings are objects that represent a sequence of characters. In Java string class is used in creating and manipulating strings. They are used for storing text or characters. The string is a special data type that belongs to a non-primitive data type. But in Java string data type is predefined. A string variable is defined as a collection of characters surrounded by double quotes. An array of characters can also be denoted as a Java string. All strings are objects which belong to a predefined class named “String”.

Example of string in Java: 

String S = “Good Morning”

The process of string to array in Java is conducted either by using a simple for loop or by using toCharArray() technique. An array of strings in Java is called a string array which is of a fixed length. The string-to-array conversion is executed by various ways like  String.split(), Pattern.split(), String[] {}, toArray().

Overview

This article covers different techniques used in converting string to array in Javascript. It also includes the conversion of string to the array by using two methods such as an array in naive approach and Using the toCharArray() Method. This article also contains four different techniques to convert string to string array in Java without split and also includes String.split() method, Pattern.split() method, String[] approach, and toArray() approach.

Convert a String to a Character 

In Java basically, there are two techniques to convert a string object into a character array.

1. Array in Naive Approach

2. Using toCharArray() Method

1. Array in Naive Approach

This method implements a for loop to convert a string to a character. First, it reads every character in the string then every character is assigned individually to the character array.

Example: A Java program to show the implementation of the Navie approach.

import java.util.*;
class StringtoCharcterArray 
{
  public static void main(String args[])
 {
    String str = "Present"; 
    char[] arr = new char[str.length()];
    for (int j = 0; j< str.length(); j )
 {
      arr[j] = str.charAt(j);
    }
    for (char x : arr)
 {
      System.out.println(x);
    }
  }
}

Output:

P
r
e
s
e
n
t

Explanation: 

1. Required class is imported.

2. Public class is defined with the name StringtoCharcterArray.

3. First a string is inserted.

4. An array is created by using the length () method whose length is the same as the length of the string.

5. Next step includes a for loop to do the traversing of the string. In this process, the jth character of the string is copied into the jth index of the array.

6. The elements of the array are printed using a for loop.

2. Using toCharArray() Method

In this method the toCharArray() function is implemented to convert string to char array in Java.

Example: A Java program to show the implementation of the toCharArray() approach in the string-to-character array conversion procedure.

import java.util.*;
public class StringtoCharacterArray 
{


      public static void main(String args[])
      {
                  String str = "Example";
                  char[] arr = str.toCharArray();
                  for (char x : arr)
                  {
                              System.out.println(x);
                  }
      }
}

Output:

E
x
a
m
p
l
e

Explanation:

1. Required class is imported.

2. Public class is defined.

3. A string is inserted.

4. Call toCharArray() function.

5. Create a char array and store the result returned by toCharArray().

6. An operation is performed on the toCharArray() function to print the result.

Example: A Java Program to Show the conversion of a String to a Character Array by using toCharArray().

import java.util.*;
public class Fruits
 {
      public static void main(String args[])
      {
                  String str = "appleandmango";
                  char[] ch = str.toCharArray();
                  for (char c : ch) 
{
                              System.out.println(c);
                  }
      }
}

Output:

a
p
p
l
e
a
n
d
m
a
n
g
o

Converting String to String Array in Java 

The conversion of string to string array in Java example is executed in four methods which are listed below.

1. Using String.split() Method 

2. Using Pattern.split() Method 

3. Using String[ ] Approach 

4. Using toArray() Method

  • Using String.split() Method 

In this method String.split() function is employed to split a string into separate strings. This method allows storing objects in a string array directly.

Example: A Java program to show the implementation of String.split() method.

class Main 

{
  public static void main(String[] args) 
{
    String str =  "The sky is beautiful";
    String[] arr = null;
    arr = str.split(" ");
    for (int j = 0; j < arr.length; j )
 {
      System.out.println(arr[j]);
    }
  }
}

Output:

The
sky
is
beautiful

Explanation:

1. First a string is declared and initialized.

2. Next an empty string array is declared.

3. String.split() function is used to split a string into separate strings.

4. For loop is used to print the converted string array.

Example: Another Java program to show the implementation of String.split() method.

import java.io.*;
public class GFG 
{
      public static void main(String[] args)
      {
                  String str = "You are welcome";
                  String strArray[] = str.split(" ");
                  System.out.println("String : " str);
                  System.out.println("String array : [ ");
                  for (int j = 0; j < strArray.length; j ) {
                              System.out.print(strArray[j] ", ");
                  }
                  System.out.print("]");
      }
}

Output:

You
are
Welcome
  • Using Pattern.split() Method

The Pattern.split() method is used to break a string into an array according to a specific pattern. This method applies an expression ‘pattern’ as the delimiter to separate a string into an array of strings. To execute this technique first a pattern class is imported into the program.

Example: A Java program to show the application of Pattern.split() method.

import java.util.regex.Pattern;
public class PatternSpiltMethod 
{
  public static void main(String[] args) 
{
    String str = "Look at the sky";
    String[] arr = null;
    Pattern ptr = Pattern.compile(" ");
    arr = ptr.split(str);
    for (int j = 0; j < arr.length; j )
 {
      System.out.println(arr[j]);
    }
  }
}

Output:

Look
at
the
Sky

 Explanation: 

1. First a pattern class is imported.

2. A string is declared and initialized.

3. An empty string array is declared.

4. White space is inserted as a parameter.

5. Splitting of the string is done by using pattern.split() method.

6. String elements are stored in an array. 

7. The converted string is printed.

Example: Another Java program to show the application of Pattern.split() method.

import java.io.*;
import java.util.regex.Pattern;
public class GFG
 {
      public static void main(String[] args)
      {
                  String str = "Once in a blue moon";
                  String my_pattern = "\\s";
                  Pattern pattern = Pattern.compile(my_pattern);


                  String[] string_array = pattern.split(str);
                  System.out.print("String : " str);
                  System.out.print("\nString array : [ ");
                  for (int j= 0; j < string_array.length; j ) 
{
                              System.out.print(string_array[j] " ");
                  }
                  System.out.print("]");
      }
}

Output:

Once
in
a 
blue
moon
  • Using String[ ] Approach 

String-to-string array conversion is also executed by simply passing the strings in the curly brackets of String[ ] { }. The string array can be developed by using the input string.

Example: A Java program to show the application of String[ ] method.

import java.util.Arrays;
public class StringConversion 
{
  public static void main(String[] args) 
{
    String str = "A piece of cake";
    String[] arr = new String[] {str};
    for(String ch : arr) 
{
        System.out.println(ch);
    }
  }
}

Output:

A piece of cake

Explanation:

1. A string is declared and initialized first.

2. Then the string is passed to the String[ ]{ } function.

3. A for loop is created to print the string array.

  • Using toArray() Method 

In Java, the toArray() function is also used to convert string to array c#. To execute this method a list of type strings is considered as input and each object is converted to an element in a string array.

Example: A Java program to show the application of toArray() method.

import java.util.ArrayList;
import java.util.List;
public class ListToStringArray 
{
  public static void main(String[] args)
 {
    List<String> list = new ArrayList<String>();
    list.add(“A");
    list.add("Blessings ");
    list.add("in");
    list.add("disguise”);
    int list_size = list.size();
    String[] arr = new String[list_size];
    list.toArray(arr);
    for (int j = 0; j < arr.length; j ) {
      System.out.println(arr[j]);
    }
  }
}  

Output:

A
blessing
in
disguise

Explanation: 

1. Array list and list class is imported first.

2. A list of type strings is created.

3. Elements are added to the string.

4. Size of the list is declared.

5. Next a string array is created.

6. Then the string is converted to a string array by using the toArray() function.

7. Output is printed.

Conclusion

In Java, a string can be defined as an object containing a sequence of character values. An array of strings in Java is called a string array. The string-to-array conversion is executed by various techniques such as String.split(), Pattern.split(), String[] {}, toArray(). In Java two techniques that are an array in naive approach and tochararray() method are used to convert a string object into a character array. Various examples are presented to give a clear idea about the conversion of string to string() array by using methods such as String.split(), Pattern.split(), String[ ], toArray().

FAQs

1. What is a string in Java?

Strings are objects that represent a sequence of characters. They are used for storing text or characters.

2. What is a string array?

An array of strings in Java is called a string array which is of a fixed length. The string-to-array conversion is executed in various ways including  String.split(), Pattern.split(), String[] {}, toArray().

3. What is the string.split() method?

In this method String.split() function is employed to split a string into separate strings. This method allows storing objects in a string array directly.

4. What is the pattern.split() method?

The Pattern.split() method is used to break a string into an array according to a specific pattern.

5. What is String[ ] Approach ?

String-to-string array conversion is also executed by simply passing the strings in the curly brackets of String[ ] { }. 

6. What is toArray() Method?

In Java, the toArray() function is used to convert a string to a string array. To execute this method a list of type strings is considered as input and each object is converted to an element in a string array.

Leave a Reply

Your email address will not be published. Required fields are marked *