Java 8 – How to convert a String into char[] Arrays ?

In this article, we will understand with a Java program on how to convert a String into char[] Arrays in Java 1.8 version

Already in one of the previous article, we discussed how to convert a String into char[] Arrays using earlier versions of Java like 5 or 7, etc.

Convert String into char[] Arrays :

  • toCharArray() method of String
    • Returns equivalent char[] Arrays for the invoking String
    • If invoking string is null, then java.lang.NullPointerException is thrown

ConvertStringToCharArrays.java

package in.bench.resources.java8.string.methods;

import java.util.Arrays;
import java.util.stream.Stream;

public class ConvertStringToCharArrays {

	public static void main(String[] args) {

		// 1. string
		String url = "BenchResourcesNet";


		// 1.1 convert String into char[] Arrays
		char[] urlArray = Stream.of(url).map(String::toCharArray).findFirst().get();
		System.out.println("Converted Arrays for String (" + url + ") is :- \n" 
				+ Arrays.toString(urlArray));


		// 2. Empty string
		String str1 = "";


		// 2.1 checking string is empty
		char[] array1 = Stream.of(str1).map(String::toCharArray).findFirst().get();
		System.out.println("\nConverted Arrays for empty String (" + str1 + ") is :- \n" 
				+ Arrays.toString(array1) + "\n\n");


		// 3. null string
		String str2 = null;


		// 3.1 checking empty on null string
		char[] array2 = Stream.of(str2).map(String::toCharArray).findFirst().get();
		System.out.println("Converted Arrays for String (" + str2 + ") is :- \n" 
				+ Arrays.toString(array2));
	}
}

Output:

Converted Arrays for String (BenchResourcesNet) is :- 
[B, e, n, c, h, R, e, s, o, u, r, c, e, s, N, e, t]

Converted Arrays for empty String () is :- 
[]


Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
	at java.base/java.util.stream.Streams$StreamBuilderImpl.tryAdvance(Streams.java:397)
	at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129)
	at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
	at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647)
	at in.bench.resources.java8.string.methods.ConvertStringToCharArrays
.main(ConvertStringToCharArrays.java:35)

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to convert a String into UpperCase String ?
Java 8 - How to get length of a String ?