How to Interconvert Between String and Array in Java


In this example, we will learn how to interconvert between String and Array.

Source Code

1) String To Array

package com.beginner.examples;

import java.util.*;

public class String2ArrayExample1 {

	public static void main(String[] args) {

		String str = "1,2,3";
		String[] arr = str.split(",");
		System.out.println(Arrays.toString(arr)); 
    }
}

Output:

[1, 2, 3]

2) Array To String

package com.beginner.examples;

import java.util.*;

public class Array2StringExample {

	public static void main(String[] args) {

		String[] arr = new String[]{"1", "2", "3"};
		
		String str = Arrays.toString(arr);
		String s = str.substring(1, str.length()-1);
		System.out.println(s); 
    }
}

Output:

1, 2, 3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments