TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java toCharArray: Convert String to Array

Use the toCharArray method to convert a string into a char array. Create a String from the array.
ToCharArray. Consider a string: it is immutable and cannot be changed. But an array can be changed. With toCharArray we get a char array from a string.Strings
With this method, we change a string into a mutable form. We can modify letters in the array. Then we convert it back into a String.
Example program. Here we begin with a String that contains the letters "abc." Then we call toCharArray on it. We print this array with Arrays.toString.

Then: We assign the first element of the array to the value "A" and print the modified array with Arrays.toString.

String: We convert the char array to a string with "new String." This invokes the String constructor.

Java program that uses toCharArray import java.util.Arrays; public class Program { public static void main(String[] args) { String letters = "abc"; // Convert String to a char array. char[] array = letters.toCharArray(); System.out.println(Arrays.toString(array)); // Modify the array. array[0] = 'A'; System.out.println(Arrays.toString(array)); // Get the String. String result = new String(array); System.out.println(result); } } Output [a, b, c] [A, b, c] Abc
Notes, toCharArray. Some string manipulations are not simple. We cannot just use insert() or replace() for all things. With toCharArray we can change characters.Replace
Notes, methods. Code that uses toCharArray can be hard to read. For this reason, placing it in a method can be helpful. These methods can receive a String and return a modified one.
A summary. With toCharArray we have a built-in way to get characters from a String. We do not need to get characters in a loop—we can get them all at once from a Java method.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf