Home » Core Java » Array to String Java Example

About Abhinav Nath Gupta

Abhinav holds a Master degree in Computer Science and Engineering from the National Institute of Technology Karnataka. He has finished his graduation from Information Technology Department in the Anand Engineering College, Agra. During his studies he has been involved with a large number of projects ranging from Networking and Cryptography. He works as a software development engineer at a software development firm in bengaluru where he is mainly involved with projects based on Nodejs. He is interested in cryptography, data security, cryptocurrency and cloud computing, and published articles regarding these topics. He can be reached at abhi.aec89@gmail.com.

Array to String Java Example

1. Intro to Array in Java

In java, arrays are a collection of similar types where type can be a String, Integer or an instance of a user defined class.

int intArray[];    //declaring an array of integers
intArray = new int[20];  // allocating memory to array

As shown in above code snippet, we have declared intArray as an array of integers of length 20, meaning it contains 20 elements, indexed from 0 to 19. Next we will code example to populate the array and see its contents.

SimpleArray.java
public class SimpleArray {
    public static void main(String[] args) {
        int intArray[];    //declaring an array of integers
        intArray = new int[20];  // allocating memory to array
        // to fill the values in the Array
        for(int count = 0; count < 20; count++){
            intArray[count] = count;
        }
        // to print the values from the Array
        for(int count = 0; count < 20; count++){
            System.out.println(intArray[count]);
        }
    }
}

Now we know how to declare and use simple array, we will see an example of creating a ComplexArray class and create an array filled with instance of ComplexArray class objects.

ComplexArray.java
public class ComplexArray {
    int age;
    public ComplexArray(int age){
        this.age = age;
    }
    public void displayAge(){
        System.out.println(this.age);
    }
}

We will use the ComplexArray class objects to create an array. We will fill that array with instances of the ComplexArray objects and we will display the contents of that array

ComplexArrayUsage.java
public class ComplexArrayUsage {
    public static void main(String[] args) {
        // arr is the array containing instances of the ComplexArray class we defined in above snippet.
        ComplexArray arr[] = new ComplexArray[20];
        // to fill the arr with ComplexArray objects
        for(int count = 0; count < 20; count++){
            arr[count] = new ComplexArray(count);
        }
        // to print the age of individual ComplexArray object in arr
        for(int count = 0; count < 20; count++){
            arr[count].displayAge();
        }
    }
}

The result can be seen in the Fig. 1 below.

Array to String Java - ComplexArrayUsage Class
Fig.1. Output of ComplexArrayUsage Class

2. Intro to String in Java

In Java, String is a java object which represent sequence of characters. In java Strings are immutable by default.

Samplestring.java
public class Samplestring {
public static void main(String[] args) {
String str = "abc"; // represent an string object with value abc
String str1 = str + "def"; // represent a new string object containing value abcdef
System.out.println(str1);
System.out.println(str);
 }
}

Fig. 2 below will show the result of the above code snippet

Array to String Java - SampleString Class
Fig. 2. Output of SampleString Class

When s string object is created using the String class and assignment operator (=), as shown in code snippet above, it’s called String literal. As a rule of thumb, string literal must be enclosed in double quotes.

3. Converting Array to String Java Example

In this section we will look into code example illustrating the procedure of converting an Array to String. This section will be classified into 2 parts. One to cover the conversion of array of built-in datatypes and the other will cover the conversion of array of custom class objects to their respective string representations.

3.1 Conversion of Array of built-in datatypes in Java to String

In this section we will cover datatypes built into java . We will cover all built-in data types except char and String.

3.1.1 Integer types

Integer types are the types in java, which are used to store the whole numbers. Example for such datatypes are byte, int, short, long.

  1. Byte Datatype : A byte can store whole numbers from -128 to 127. following code snippet will illustrate that how to convert an array of byte types to string.
ByteTypeArrayToString.java
public class ByteTypeArrayToString {
    public static void main(String[] args) {
        byte[] bytesArray = "hello java code geeks".getBytes();
        String byteToString = new String(bytesArray);
        System.out.println(byteToString);
    }
}

snapshot below in Fig. 3 will illustrate the output of the above code snippet.

Array to String Java - ByteTypeArrayToString Class
Fig. 3. Output of ByteTypeArrayToString Class

2. Short Datatype: A short can store numbers from 32768 to 32767. following code snippet will illustrate that how to convert an array of short types to string.

ShortTypeArrayToString.java
import java.util.Arrays;

public class ShortTypeArrayToString {
    public static void main(String[] args) {
        short[] shortArr = new short[]{1989, 2018};
        System.out.println("Array of elements of short Datatype");
        for (short shortNum : shortArr) {
            System.out.println("Number of type short = " + shortNum);
        }
        System.out.println("The string representation of shortArr is:");
        System.out.println(Arrays.toString(shortArr));
    }
}

snapshot below in Fig. 4 will illustrate the output of the above code snippet.

Array to String Java - ShortTypeArrayToString Class
Fig. 4. Output of ShortTypeArrayToString Class

3. Integer Datatype: A int can store numbers from -2147483648 to 2147483647. following code snippet will illustrate that how to convert an array of int types to string.

IntTypeArrayToString.java
import java.util.Arrays;

public class IntTypeArrayToString {
    public static void main(String[] args) {
        int[] intArr = new int[]{1989, 2018};
        System.out.println("Array of elements of integer Datatype");
        for (int intNum : intArr) {
            System.out.println("Number of type integer = " + intNum);
        }
        System.out.println("The string representation of intArr is:");
        System.out.println(Arrays.toString(intArr));
    }
}

snapshot below in Fig. 5 will illustrate the output of the above code snippet.

Array to String Java - IntTypeArrayToString Class
Fig. 5. Output of IntTypeArrayToString Class

4. Long Datatype: A long can store numbers from -9223372036854775808 to 9223372036854775807. following code snippet will illustrate that how to convert an array of long types to string.

LongTypeArrayToString.java
import java.util.Arrays;

public class LongTypeArrayToString {
    public static void main(String[] args) {
        long[] longArr = new long[]{1989000000000000000L, 2018000000000000000L};
        System.out.println("Array of elements of Long Datatype");
        for (long intNum : longArr) {
            System.out.println("Number of type long = " + intNum);
        }
        System.out.println("The string representation of longArr is:");
        System.out.println(Arrays.toString(longArr));
    }
}

snapshot below in Fig. 6 will illustrate the output of the above code snippet.

Array to String Java - LongTypeArrayToString Class
Fig. 6. Output of LongTypeArrayToString Class

This sums up the Array to String conversion for Arrays containing integer type elements.

3.1.2 Floating Point types

Floating Point Types types are the types in java, which are used to store the real numbers or numbers with a decimal point. Example for such datatypes are float and double.

1. Float Datatype : A float can store real numbers from 3.4e−038 to 3.4e+038(e stands for exponent). following code snippet will illustrate that how to convert an array of float types to string.

FloatTypeArrayToString.java
import java.util.Arrays;

public class FloatTypeArrayToString {
    public static void main(String[] args) {
        float[] floatArr = new float[]{1.989f, 2.018f};
        System.out.println("Array of elements of Float Datatype");
        for (float floatNum : floatArr) {
            System.out.println("Number of type float = " + floatNum);
        }
        System.out.println("The string representation of floatArr is:");
        System.out.println(Arrays.toString(floatArr));
    }
}

snapshot below in Fig. 7 will illustrate the output of the above code snippet.

Array to String Java - FloatTypeArrayToString Class
Fig. 7. Output of FloatTypeArrayToString Class

2. Double Datatype: A float can store real numbers from 1.7e−308 to 1.7e+308(e stands for exponent). following code snippet will illustrate that how to convert an array of double types to string.

DoubleTypeArrayToString.java
import java.util.Arrays;

public class DoubleTypeArrayToString {
    public static void main(String[] args) {
        double[] doubleArr = new double[]{1.989d, 2.018d};
        System.out.println("Array of elements of Double Datatype");
        for (double doubleNum : doubleArr) {
            System.out.println("Number of type double = " + doubleNum);
        }
        System.out.println("The string representation of doubleArr is:");
        System.out.println(Arrays.toString(doubleArr));
    }
}

snapshot below in Fig. 8 will illustrate the output of the above code snippet.

Array to String Java - DoubleTypeArrayToString Class
Fig. 8. Output of DoubleTypeArrayToString Class

3.1.3 Boolean types

Boolean Types types are the types in java, which are used to store either true or false values. Mostly used in conditional branches in code flow.following code snippet will illustrate that how to convert an array of boolean types to string.

BooleanTypeArrayToString.java
import java.util.Arrays;

public class BooleanTypeArrayToString {
    public static void main(String[] args) {
        boolean[] booleanArr = new boolean[]{true, false};
        System.out.println("Array of elements of Boolean Datatype");
        for (boolean booleanItem : booleanArr) {
            System.out.println("Number of type boolean = " + booleanItem);
        }
        System.out.println("The string representation of booleanArr is:");
        System.out.println(Arrays.toString(booleanArr));
    }
}

snapshot below in Fig. 9 will illustrate the output of the above code snippet.

Fig. 9. Output of BooleanTypeArrayToString Class

This sums up the conversion of Arrays of datatypes which are not string or character. We now have a good idea on how to convert the arrays of any non-string or non-character data type to String. In the next section we will try to convert an Array of Custom Class objects to String.

3.2 Conversion of Array of Custom Class objects in Java to String

Consider the following Code Snippet,

UsersArrayToStringObject.java
import java.util.Arrays;

class User {
    int age;
    String name;

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }
}


public class UsersArrayToStringObject {
    public static void main(String[] args) {
        User users[] = new User[5];
        for (int count = 0; count < 5; count++) {
            users[count] = new User(count,"User" + count);
        }
        System.out.println(Arrays.toString(users));
    }
}

In the above code snippet we have a User class which has 2 properties, name and age. We use this User class in UsersArrayToStringObject class to create the users array and filled it with objects of User class. When we try to use Arrays.toString then it will print the internal representation of object of individual object in the users array as shown in the Fig. 10 below.

Fig. 10. Output of the UsersArrayToStringObject Class without toString() in User class

In order to make the output human readable, we have to override the toString() method in User class, as shown in Fig, 11 below.

UsersArrayToStringObject.java
import java.util.Arrays;


class User {
    int age;
    String name;

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String toString() {
        return this.name + " is " + String.valueOf(this.age) + " old";
    }
}


public class UsersArrayToStringObject {
    public static void main(String[] args) {
        User users[] = new User[4];
        for (int count = 0; count < 4; count++) {
            users[count] = new User(count,"User" + count);
        }
        System.out.println(Arrays.toString(users));
    }
}

output of the above modified code for UsersArrayToStringObject class can be seen in Fig.11 below.

Fig. 11. Output of the UsersArrayToStringObject Class with toString() in User class

Now we understood how to convert an array of custom class objects to their string representation.

4. Summary

To summarise, in this article we have covered the basics of arrays and strings. We have also covered the basics of how to convert arrays of built-in datatypes to their string representations and how to do the same in case of custom class.

5. Download the Source Code

Download
You can download the full source code of this example here: Array To String Java Example
(No Ratings Yet)
Start the discussion 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

 

Leave a Reply

avatar
  Subscribe  
Notify of