Converting character array to string in java

Continue

Converting character array to string in java

There are two ways to convert a char array (char[]) to String in Java: 1) Creating String object by passing array name to the constructor 2) Using valueOf() method of String class. James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tutorials, and he frequently contributes to publications like Codecademy, Treehouse, Repl.it, Afrotech, and others. He also serves as a researcher at Career Karma, publishing comprehensive reports on the bootcamp market and income share agreements. Read more by James Gallagher Comments (0) While strings are the preferred way of dealing with characters, character arrays (char [])often make sense as buffers or in cases where working with arrays is more convenient. Side note: Read my warning about using the char data type. Converting char arrays to strings is a pretty common use case. In this tutorial, we'll look at how to convert character arrays to strngs using two different techniques. Using String.valueOf(...) method Using String class Constructor 1. Using String.valueOf(...) method This is my preferred approach. It's easy to remember because valueOf(...) method is widely used to convert between types. In this case, String.valueOf(char [] data) takes a char [] array as an argument and returns its string representation. The returned string is "safe": it can be modified and won't affect the character array. Let's look at an example. package com.codeahoy.ex; public class Main { public static void main(String[] args) { char[] charArray = { 'G', 'o', 'o', 'g', 'l', 'e' }; // Convert char [] to String using valueOf String str = String.valueOf(charArray); System.out.println(str); } } Output There's also another method called copyValueOf(char [] data) which is equivalent to valueOf(...). I think it's there for backwards compatibility reasons and will advice that you prefer valueOf(...) over it. 2. Using String class Constructor String class in Java has a overloaded constructor which takes char [] array as argument. The String is created using the char [] array and is "safe", that is, subsequent modification of the string or char [] array doesn't affect each other. Let's look at an example. package com.codeahoy.ex; public class Main { public static void main(String[] args) { char[] charArray = { 'C', 'o', 'd', 'e', 'A', 'h', 'o', 'y' }; // Convert char [] to String String str = new String(charArray); System.out.println(str); } } Output There are other ways of converting character array to string in Java but these two are the ones that are most commonly used in practice. Until next time. If you like this post, please share using the buttons above. It will help CodeAhoy grow and add new content. Thank you! In this quick tutorial, we're going to look at different ways to convert an array to String in Java. We often need to convert an array or a list of strings into one single String to meet some basic programming needs. For example, sometimes, we may want to join multiple strings separated by a comma to create a CSV String. Feel free to check our article on how to convert a string into an array to learn how to do the opposite. Converting Array to String in Java Basically, converting an array of elements to a string is very easy and can be done using multiple strategies and methods. However, unfortunately, there is no direct way to achieve that in Java. Now you may be wondering, why we can't just use the toString() method, since arrays are considered objects in Java. Well, if you try to invoke toString() on an array, you will get something like [C@15db9742 as output. Not cool right? It's not even a human-understandable result. Using String.join() Method join() belongs to String class and it can be used to join string array to produce one single String instance. This method returns a new String composed of CharSequence elements joined together with the help of the specified delimiter. In this example, we are going to use the join() method to create a new string object from an array. public class ArrayToStringJoin { public ArrayToStringJoin() { } public static void main(String[] args) { String[] data = {"Turn","Array", "Into", "String","In", "Java", "Example"}; String joinedstr = String.join(" ", data); System.out.println(joinedstr); CharSequence[] vowels = {"a", "e", "i", "o", "u"}; String joinedvowels = String.join(",", vowels); System.out.println(joinedvowels); List strList = Arrays.asList("dev", "with", "us", "blog"); String joinedString = String.join(", ", strList); System.out.println(joinedString); } } Turn Array Into String In Java Example a,e,i,o,u dev, with, us, blog Using Arrays.toString() Arrays.toString() is a built-in method of Arrays utility class and it provides the simplest way to turn an Array into a String. It simply returns the string representation of the specified array. All array's elements will be separated by "," and enclosed in square brackets "[]". Let's see how we can use Arrays.toString() method to produce a single string from an array of strings: public class ArrayToStringToString { public ArrayToStringToString() { } public static void main(String[] args) { String[] data2 = {"Hello","Array", "String", "Conversion", "Example"}; String joinedstr2 = Arrays.toString(data2); System.out.println(joinedstr2); } } [Hello, Array, String, Conversion, Example] Using StringBuilder append() Method StringBuilder class can be used to create mutable string objects. It offers the append(String str) method to append a given string to the sequence. StringBuilder.toString() returns the string representation of the data encapsulated in the StringBuilder object. In order to use StringBuilder to convert an array to string in Java, we need to follow the following steps: Create your array - of strings for example Create a StringBuilder object Iterate over the array Use append() method to append every element - string - of the array Use toString() method to return a string instance from the stringBuilder object. public class ArrayToStringStringBuilder { public ArrayToStringStringBuilder() { } public static void main(String[] args) { String[] data3 = {"Use","StringBuilder", "to", "turn", "Array","into","String","object"}; StringBuilder stringb = new StringBuilder(); for (int i = 0; i < data3.length; i++) { stringb.append(data3[i]+" "); } String joinedstr3 = stringb.toString(); System.out.println(joinedstr3); } } Use StringBuilder to turn Array into String object Using StringJoiner class StringJoiner is a new class introduced in Java 8, it belongs to the java.util package. It provides methods for joining multiple Strings into one single string object using a specified delimiter. StringJoiner offers a fluent way to join strings, we can chain the calls and write code in one line. For example, we can use it to join multiple strings separated by "/" to create a full path for a directory in Centos: public class ArrayToStringStringJoiner { public ArrayToStringStringJoiner() { } public static void main(String[] args) { String[] data4 = {"path", "to", "", "blog"}; StringJoiner joiner = new StringJoiner(""); for (int i = 0; i < data4.length; i++) { joiner.add(data4[i]+"/"); } String joinedstr4 = joiner.toString(); System.out.println("/"+joinedstr4); String newstr = new StringJoiner("/").add("home").add("user").add("file").toString(); System.out.println(newstr); } } /path/to/blog/ home/user/file Java 8 Stream API The joining() method is defined in Collectors class, it is mainly used to convert multiple strings to a string object. We can use a delimiter - prefix and suffix too - of our choice to concatenate the input elements in order to construct the string instance. In general, Collectors class provides 3 overloaded static methods to perform string joining operations. Let's see with an example how we can use Collectors.joining() to concatenate multiple strings to form one string: public class ArrayToStringJava8 { public ArrayToStringJava8() { } public static void main(String[] args) { List data5 = Arrays.asList("PHP", "Java", "GoLang", "Kotlin", "Perl"); String joinedstr5 = data5.stream() .collect(Collectors.joining(", ","[","]")); System.out.println(joinedstr5); } } [PHP, Java, GoLang, Kotlin, Perl] Using StringUtils (Apache Commons) StringUtils class from Apache Commons Lang library, offers multiple handy methods for handling string related operations. It provides multiple join() methods that we can use to convert an array of strings to a single string in Java. In order to use this class, we will need to add commons-lang3 dependency to our dependency management tool file (pom.xml in case of Maven): org.mons commons-lang3 latest-version The following example shows how to create a new string from an array using StringUtils.join(): public class ArrayToStringStringUtils { public ArrayToStringStringUtils() { } public static void main(String[] args) { String[] data6 = { "John", "Karin", "Charles", "Lucas", "Diana" }; String joinedstr6 = StringUtils.join(data6,"|"); System.out.println(joinedstr6); } } John|Karin|Charles|Lucas|Diana Using Guava Joiner Class Joiner (a class provided by Guava library) provides clean and concise syntax to handle string concatenation. It takes multiple strings and concatenates them together using delimiters. Like the Splitter class, Joiner comes with interesting built-in utility methods such as skipNulls which can be used to skip and ignore null values. To demonstrate this, let's use the Joiner class to produce a comma separated string from an array: public class ArrayToStringJoiner { public ArrayToStringJoiner() { } public static void main(String[] args) { List data7 = Arrays.asList("MOSCOW", "PARIS", "LONDON", "MADRID"); String joinedstr7 = Joiner.on(":").join(data7); System.out.println(joinedstr7); } } MOSCOW:PARIS:LONDON:MADRID Using Own Implementation In case you don't want to use all the above methods for some reason or another, we can always create our own implementation. Here is an example that shows how to define a customized implementation for converting an array to string in Java. public class CustomArrayToString { public CustomArrayToString() { } private static String arrayTostring(String[] strs) { String str = "["; for (int i = 0; i < strs.length; i++) { if (i > 0) { str = str + ","; } String item = strs[i]; str = str + item; } str = str + "]"; return str; } public static void main(String[] args) { String[] arr = { "United states", "Canada", "France", "United Kingdom" }; String joinedstr8 = ArrayToString.arrayTostring(arr); System.out.println(joinedstr8); } } [United states,Canada,France,United Kingdom] How to Convert char Array to String in Java? There are multiple ways to convert a char array (char[]) to a String in Java. Below, are the list of methods for converting char[] array to a string object. Using String Constructor String class provides an overloaded constructor that accepts a char array as an argument. Using a constructor is the most logical and easiest way to create a string from a char array. All we need to do is passing the array as a parameter to the String constructor and we are done. public class StringConstructor { public StringConstructor() { } public static void main(String[] args) { char[] chars = { 'h', 'd', 'k', 'l', 'f', 'p', 'o', 'i' }; String mystring = new String(chars); System.out.println(mystring); } } Using StringBuilder StringBuilder is yet another simple way to produce a new string from a char[] array. It provides the append() method which can be used to construct a single string from every character of the array. The conversion logic is very simple: Create a new StringBuilder instance. Iterate over the array of characters. Use append() method to add every character. Use toString() method to get String object. public class StringBuilderExample { public StringBuilderExample() { } public static void main(String[] args) { char[] chararray = { 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r','l','d' }; StringBuilder strb = new StringBuilder(); for (char mychar : chararray) { strb.append(mychar); } System.out.println(strb.toString()); } } Using Arrays.stream() Java 8 provides another pretty good solution to create a new string from a character array. We can use Arrays.stream() method to create a stream over an array of characters. Then, we can use the joining() method of the Collectors class to create the String. Let's look at the following example: public class Java8StreamAPI { public Java8StreamAPI() { } public static void main(String[] args) { Character[] charArray = { 'd', 'e', 'v', 'w', 'i', 't', 'h', 'u','s','.','c','o','m' }; Stream charStream = Arrays.stream(charArray); String mystr = charStream.map(String::valueOf).collect(Collectors.joining()); System.out.println(mystr); } } Using valueOf(char[] data) and copyValueOf(char[] data) The valueOf() method returns the string representation of the passed argument. The String class has an overloaded static method: String.valueOf(char [] chars), which takes a char[] as an argument and returns a new string containing all the characters of the passed array. copyValueOf(char[] data) method serves the same purpose as valueOf(). The two methods are equivalent according to javadocs. public class valueOfAndCopyValueOf { public valueOfAndCopyValueOf() { } public static void main(String[] args) { char[] charsarray = { 't', 'k', 'z', 'v', 'y', 'b', 'x', 'n' }; String mystr1 = String.valueOf(charsarray); System.out.println(mystr1); String mystr2 = String.copyValueOf(charsarray); System.out.println(mystr2); } } Conclusion That's all folks! In this article, we have explored possible ways to convert an array to a String in Java. Happy Learning! If you have any questions, please leave a note in the comments section.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download