Home » Core Java » Java 8 Convert String to Char Array Example

About Mary Zheng

Mary Zheng
Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.

Java 8 Convert String to Char Array Example

1. Introduction

The Java String class represents character strings. An array is a data structure which holds a fixed number of values of a single type. The char type is a primitive type which represents a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65535 inclusive). The Character class wraps thechar type as a value in an object. An object of theCharacter type contains a single field whose type is the chartype. A Char Array is an array which holds a constant number of characters.

Java 8 provides IntStream class which is useful to convert a String to an array of characters. In this example, I will demonstrate how to convert a String object into an array of characters.

Want to be a Java 8 Ninja ?

Subscribe to our newsletter and download the Java 8 Features Ultimate Guide right now!

In order to get you up to speed with the major Java 8 release, we have compiled a kick-ass guide with all the major Java 8 features and goodies! Besides studying them online you may download the eBook in PDF format!

2. Technologies used

The example code in this article was built and run using:

  • Java 1.8.101
  • Maven 3.3.9
  • Eclipse Oxygen
  • JUnit 4.12

3. Maven Project

3.1 Dependency

Add Junit to the pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>zheng.jcg.demo</groupId>
	<artifactId>java8-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

3.2 Convert String to Char Array

JDK String class provides two methods:

  • charAt(int index) – return the char value at the specified index.
  • toCharArray() – return a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.

In this step, I will show you how to use the methods above to convert a String into an array of characters.

StringToCharArray.java

package com.zheng.demo;

public class StringToCharArray {
	private String testMessage;

	public StringToCharArray(String message) {
		super();
		testMessage = message;
	}

	public char[] toCharArray() {
		return testMessage.toCharArray();
	}

	public char[] toCharsBycharat2() {
		char[] chars = new char[testMessage.length()];
		for (int i = 0; i < testMessage.length(); i++) {
			chars[i] = testMessage.charAt(i);
		}
		return chars;
	}

	public Character[] toCharsBycharat() {
		Character[] chars = new Character[testMessage.length()];
		for (int i = 0; i < testMessage.length(); i++) {
			chars[i] = testMessage.charAt(i);
		}
		return chars;
	}

}

3.3 Convert String to Char Array with Java 8

Java 8 IntStream interface is a sequence of int-valued elements. Java CharSequence interface provides the toChars method to return a stream of int values from the char sequence. Java String class implements the CharSequence interface and implements toChars .

In this step, I will show you how to convert a String object into an array of characters via IntStream.

StringToCharArray_Java8.java

package com.zheng.demo;

import java.util.stream.IntStream;
import java.util.stream.Stream;

public class StringToCharArray_Java8 {
	private String testMessage;

	public StringToCharArray_Java8(String message) {
		super();
		testMessage = message;
	}

	public Character[] toCharsByStream() {
		IntStream is = testMessage.chars();
		Stream characterStream = is.mapToObj(c -> (char) c);
		return characterStream.toArray(Character[]::new);
	}

	public Character[] toCharsBycodePointsStream() {
		IntStream is = testMessage.codePoints();
		Stream characterStream = is.mapToObj(c -> (char) c);
		return characterStream.toArray(Character[]::new);
	}

}

4. JUnit Tests

4.1 Convert String to Char Array Test

In this step, I will create three JUnit tests to convert a String into an array of characters.

StringToCharArrayTest.java

package com.zheng.demo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class StringToCharArrayTest {

	private StringToCharArray sv = new StringToCharArray("Test");

	@Test
	public void via_toCharArray() {
		char[] chars = sv.toCharArray();
		assertTrue('T'== chars[0]);
		assertTrue('e'== chars[1]);
		assertTrue('s'== chars[2]);
		assertTrue('t'== chars[3]);
	}
	
	@Test
	public void  via_charat_2() {
		char[] chars = sv.toCharsBycharat2();
		assertTrue('T'== chars[0]);
		assertTrue('e'== chars[1]);
		assertTrue('s'== chars[2]);
		assertTrue('t'== chars[3]);
	}
	
	
	@Test
	public void  via_charat() {
		Character[] chars = sv.toCharsBycharat();
		assertEquals(new Character('T'), chars[0]);
		assertEquals(new Character('e'), chars[1]);
		assertEquals(new Character('s'), chars[2]);
		assertEquals(new Character('t'), chars[3]);
	}


}

4.2 Convert String to Char Array Java 8 Test

In this step, I will create two JUnit tests to convert a String into an array of characters.

StringToCharArray_Java8Test.java

package com.zheng.demo;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class StringToCharArray_Java8Test {

	private StringToCharArray_Java8 sv = new StringToCharArray_Java8("Test");

	@Test
	public void via_chars_Stream_map() {
		Character[] chars = sv.toCharsByStream();
		assertEquals(new Character('T'), chars[0]);
		assertEquals(new Character('e'), chars[1]);
		assertEquals(new Character('s'), chars[2]);
		assertEquals(new Character('t'), chars[3]);
	}

	@Test
	public void via_codePoints_Stream_map() {
		Character[] chars = sv.toCharsBycodePointsStream();
		assertEquals(new Character('T'), chars[0]);
		assertEquals(new Character('e'), chars[1]);
		assertEquals(new Character('s'), chars[2]);
		assertEquals(new Character('t'), chars[3]);
	}

}

5. Demo

Execute mvn clean install and capture the output:

Tests Output

Build output

C:\gitworkspace\java8-demo>mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< zheng.jcg.demo:java8-demo >----------------------
[INFO] Building java8-demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ java8-demo ---
[INFO] Deleting C:\gitworkspace\java8-demo\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java8-demo
 ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ java8-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 2 source files to C:\gitworkspace\java8-demo\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java8-demo ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ java8-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 2 source files to C:\gitworkspace\java8-demo\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java8-demo ---
[INFO] Surefire report directory: C:\gitworkspace\java8-demo\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.zheng.demo.StringToCharArrayTest
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.078 sec
Running com.zheng.demo.StringToCharArray_Java8Test
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.033 sec

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ java8-demo ---
[INFO] Building jar: C:\gitworkspace\java8-demo\target\java8-demo-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ java8-demo ---
[INFO] Installing C:\gitworkspace\java8-demo\target\java8-demo-0.0.1-SNAPSHOT.jar to C:\repo\zheng\jcg\demo\java8-demo\0.0.1-SNAPSHOT\java8-demo-0.0.1-SNAPSHOT.jar
[INFO] Installing C:\gitworkspace\java8-demo\pom.xml to C:\repo\zheng\jcg\demo\java8-demo\0.0.1-SNAPSHOT\java8-demo-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.601 s
[INFO] Finished at: 2018-10-31T15:48:38-05:00
[INFO] ------------------------------------------------------------------------

C:\gitworkspace\java8-demo>

6. Summary

In this example, we demonstrated how to convert a String into a char array using Java 8 IntStream interface as well as the String class’s toCharArray method.

7. Download the Source Code

This example consists of a Maven project to convert a String object into a char array using Java 8 IntStream API.

Download
You can download the full source code of this example here: Java 8 Convert String to Char Array Example
(No Ratings Yet)
5 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

5
Leave a Reply

avatar
3 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
jamesMary ZhengjeffGregory P Patnude Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Gregory P Patnude
Guest

This exercise is an anti-pattern.

This entire ‘tutorial’ is redundant and unnecessary — toCharArray() has been part of Java since 1.5. Exercises like this show a complete disregard for the core features of the language and encourage people to do things the hard way.

String str = “This string can be viewed as an array of chars.”;
char[] ch = str.toCharArray();

jeff
Guest
jeff

This is a neat exercise in not only different ways to perform simple things like String -> char[], but also maven and junit tests :)

This article could include some related interesting things, like how using a Stream compares to using a String class method. How does memory usage, runtime, etc compare, and why? Under what certain situations might one want to use Streams over String class methods, both for String->char[] as well as any other use cases?

Thanks for the quick read!

james
Guest

This no need to be a maven project right? A normal eclipse or even gradle project is ok?