Java util array to string

How to Convert or Print Array to String in Java? Example Tutorial

Array and String are very closely related, not just because String is a character array in most of the programming language but also with popularity — they are two of the most important data structure for programmers. Many times we need to convert an array to String or create an array from String, but unfortunately, there is no direct way of doing this in Java. Though you can convert an array to String by simply calling their toString() method, you will not get any meaningful value. If you convert an Integer array to a String, you will get something like I @4fee225 due to the default implementation of the toString() method from the java.lang.Object class. Here, I show the type of the array and content after @ is hash code value in hexadecimal.

How valuable is that? This is not what we wanted to see, I was interested in content rather than hashcode. Fortunately, Java provides a utility class called java.util.Arrays , which provides several static utility methods for arrays in Java.

For example, here we have a method to sort an array, search elements using binary search, fill the array, methods to check if two arrays are equal or not, copy a range of values from one array to another, and much-needed toString() and deepToString() method to convert both one-dimensional and multi-dimensional array to String.

Читайте также:  Test automation using selenium webdriver with java step by step guide

This method provides the content view of the array, for example, when you convert an integer array < 1 , 2 , 3 , 4 , 5 , 6 , 7 >to String, you will get [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] instead of [ I @2ab6994f , which is what most of us want to see in most of the cases.

In this article, we will see examples to convert different types of the array to String like int , char , byte , double , float , Object, and String array itself. We will also learn how to convert a two-dimensional array to String in Java.

Btw, if you are new to Java, I suggest you first go through The Complete Java MasterClass course on Udemy. That will help you to learn fundamentals faster and you will understand this article any other article on the web better.

Array to String in Java — Example

Here is our sample Java program to convert an array to String in Java. If you want to run this program in Eclipse all you have to do is, create a Java project in Eclipse, copy this code, right-click on the src folder on your Java project in Eclipse, and the rest will be taken care of by IDE.

It will take care of creating a proper package and Java source file. You don’t have to manually create the package and then Java file on your own.

In these examples, I have first shown what will happen if you call the toString() method directly or indirectly (by passing an array to System.out.print() methods) and then the right way to convert array to String by passing an array to Arrays.toString() method.

Btw, care should be taken while printing multi-dimensional arrays or converting them to String. It’s not an error when you pass a multi-dimensional array to Arrays.toString() but it will not print it correctly.

You must use the deepToString() method to convert an array that has more than one dimension, as shown in the last couple of examples of printing two and three-dimensional arrays in Java.

Btw, if you are not familiar with an array in Java, then you should also check Java Fundamentals Part 1 and Part 2 courses on Pluralsight, two of the best courses to learn fundamental concepts in Java, like array and String.

Sample Program to Print Array as String in Java

Now, let’s see our Java program which prints the different kinds of the array as String in Java, like int, char, byte, short, long, float, and Object arrays:

import java.util.Arrays; /** * Java Program to convert array to String in Java. In this tutorial you will * learn how to convert integer array, char array, double array, byte array, * multi-dimensional array to String in Java. * * @author Javin Paul */ public class ArrayToString < public static void main(String args[]) < // Converting int array to String in Java int[] numbers = 1, 2, 3, 4, 5, 6, 7>; System.out.println(numbers.toString()); String str = Arrays.toString(numbers); System.out.println("int array as String in Java : " + str); // Converting char array to String in Java char[] vowels = 'a', 'e', 'i', 'o', 'u'>; System.out.println(vowels.toString()); String charArrayAsString = Arrays.toString(vowels); System.out.println("char array as String in Java : " + str); // Converting byte array to String in Java byte[] bytes = <(byte) 0x12, (byte) 0x14, (byte) 0x16, (byte) 0x20>; System.out.println(bytes.toString()); String byteArrayAsString = Arrays.toString(bytes); System.out.println("byte array as String in Java : " + byteArrayAsString); // Converting float array to String in Java float[] floats = 0.01f, 0.02f, 0.03f, 0.04f>; System.out.println(floats.toString()); String floatString = Arrays.toString(floats); System.out.println("float array as String in Java : " + floatString); // Converting double array to String in Java double[] values = 0.5, 1.0, 1.5, 2.0, 2.5>; System.out.println(values.toString()); String doubleString = Arrays.toString(values); System.out.println("double array as String in Java : " + doubleString); // Converting object array to String in Java Object[] objects = "abc", "cdf", "deg", "england", "india">; System.out.println(objects.toString()); String objectAsString = Arrays.toString(objects); System.out.println("object array as String in Java : " + objectAsString); // Convert two dimensional array to String in Java int[][] twoD = < 100, 200, 300, 400, 500>, 300, 600, 900, 700, 800>,>; System.out.println(twoD.toString()); String twoDimensions = Arrays.deepToString(twoD); System.out.println("Two dimensional array as String in Java : " + twoDimensions); // Convert three dimensional array to String in Java int[][][] threeD = < < 11, 22, 33, 44, 55>, 32, 42, 52, 62, 72>,>, < 1111, 2222, 3333, 4444, 5555>, 1001, 2001, 3001, 4001, 5001>,> >; System.out.println(threeD.toString()); String threeDString = Arrays.deepToString(threeD); System.out.println("3 dimensional array as String in Java : " + threeDString); > > Output [I@2ab6994f int array as String in Java : [1, 2, 3, 4, 5, 6, 7] [C@3a0b2771 char array as String in Java : [1, 2, 3, 4, 5, 6, 7] [B@324a897c byte array as String in Java : [18, 20, 22, 32] [F@3b8845af float array as String in Java : [0.01, 0.02, 0.03, 0.04] [D@5bfd9b49 double array as String in Java : [0.5, 1.0, 1.5, 2.0, 2.5] [Ljava.lang.Object;@66de04cd object array as String in Java : [abc, cdf, deg, england, india] [[I@4fee225 Two dimensional array as String in Java : [[100, 200, 300, 400, 500], [300, 600, 900, 700, 800]] [[[I@cde6570 3 dimensional array as String in Java : [[[11, 22, 33, 44, 55], [32, 42, 52, 62, 72]], [[1111, 2222, 3333, 4444, 5555], [1001, 2001, 3001, 4001, 5001]]]

You can see from the output that now instead of some memory address and type of array, you have printed the actual contents of the array in Java. This is also a good lesson on how you can print an array in readable format and you should always do this when you are logging array content or printing them.

Even Java debuggers like what is available in Eclipse, Netbeans, and IntelliJ IDEA print array like that. Currently, if you try to watch an array in Eclipse, you will see its proper content, instead of default type@hashcode values, as seen in the following screenshot.

Array to String in Java with Example

That’s all about how to convert an Array to String in Java. As you have learned, even though the array is treated as an object in Java, it doesn’t override the toString() method in a meaningful way which means you print an array into the console using System.out.println() or via any logging libraries like Log4J or SLF4j, only memory address, and type of array is printed instead of actual content, which is not helpful in most of the cases.

But, JDK does provide methods like Arrays.toString() and Arrays.deepToString() which you can use to print elements of a single-dimensional array and multi-dimensional array in Java.

Whenever you print an array, use those methods depending upon which kind of array you are printing because passing a multi-dimensional array to Arrays.toString() will only print top-level array which is again memory address and type of nested array, means not useful at all.

  • How to create an array from ArrayList of String in Java
  • How to count the number of Vowels and Consonants in Java String
  • How to replace characters on String in Java
  • How to use the substring method in Java
  • 10 Data Structure Courses to Crack Programming Interviews
  • How to use Regular Expression to Search in String
  • How to Split String in Java
  • 7 Best Courses to learn Data Structure and Algorithms
  • How to convert String to Integer in Java
  • Best way to Convert Numbers to String in Java
  • How to search a character in Java String
  • 50+ Data Structure and Algorithms Interview Questions

P. S. — If you are looking to learn Data Structure and Algorithms from scratch or want to fill gaps in your understanding and looking for some free courses, then you can check out this list of Free Algorithms Courses to start with.

Источник

Java String Array to String

Java String Array to String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into how to convert Java String array to String. Sometimes we have to convert String array to String for specific requirements. For example; we want to log the array contents or we need to convert values of the String array to String and invoke other methods.

Java String Array to String

Most of the time we invoke toString() method of an Object to get the String representation. Let’s see what happens when we invoke toString() method on String array in java.

package com.journaldev.util; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] ; String str = strArr.toString(); System.out.println("Java String array to String = "+str); > > 

java string array to string toString method call output

Below image shows the output produced by the above program. The reason for the above output is because toString() call on the array is going to Object superclass where it’s implemented as below.

Java String Array to String Example

So how to convert String array to String in java. We can use Arrays.toString method that invoke the toString() method on individual elements and use StringBuilder to create String.

public static String toString(Object[] a) < if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) < b.append(String.valueOf(a[i])); if (i == iMax) return b.append(']').toString(); b.append(", "); >> 

We can also create our own method to convert String array to String if we have some specific format requirements. Below is a simple program showing these methods in action and output produced.

package com.journaldev.util; import java.util.Arrays; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] < "1", "2", "3" >; String str = Arrays.toString(strArr); System.out.println("Java String array to String = " + str); str = convertStringArrayToString(strArr, ","); System.out.println("Convert Java String array to String = " + str); > private static String convertStringArrayToString(String[] strArr, String delimiter) < StringBuilder sb = new StringBuilder(); for (String str : strArr) sb.append(str).append(delimiter); return sb.substring(0, sb.length() - 1); >> 

convert string array to string in java

So if we use array toString() method, it returns useless data. Java Arrays class provide toString(Object[] objArr) that iterates over the elements of the array and use their toString() implementation to return the String representation of the array. That’s why when we use this function, we can see that it’s printing the array contents and it can be used for logging purposes. If you want to combine all the String elements in the String array with some specific delimiter, then you can use convertStringArrayToString(String[] strArr, String delimiter) method that returns the String after combining them.

Java Array to String Example

Now let’s extend our String array to String example to use with any other custom classes, here is the implementation.

package com.journaldev.util; import java.util.Arrays; public class JavaArrayToString < public static void main(String[] args) < A[] arr = < new A("1"), new A("2"), new A("3") >; // default toString() method System.out.println(arr.toString()); // using Arrays.toString() for printing object array contents System.out.println(Arrays.toString(arr)); // converting Object Array to String System.out.println(convertObjectArrayToString(arr, ",")); > private static String convertObjectArrayToString(Object[] arr, String delimiter) < StringBuilder sb = new StringBuilder(); for (Object obj : arr) sb.append(obj.toString()).append(delimiter); return sb.substring(0, sb.length() - 1); >> class A < private String name; public A(String name) < this.name = name; >@Override public String toString() < System.out.println("A toString() method called!!"); return this.name; >> 
[Lcom.journaldev.util.A;@7852e922 A toString() method called!! A toString() method called!! A toString() method called!! [1, 2, 3] A toString() method called!! A toString() method called!! A toString() method called!! 1,2,3 

So we looked at how to convert Java String array to String and then extended it to use with custom objects. That’s all for converting java array to String. You can checkout more core java examples from our GitHub Repository. Reference: Java Arrays toString API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью