Write a program to convert an array to String in Java?

Java 8Object Oriented ProgrammingProgramming

The Arrays class of the java.util package provides a method named toString() this method accepts an array value (of any type) and returns a String.

Example

Following Java program accepts various arrays from the user, converts them into String values and prints the results.

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      //Integer array to String
      System.out.println("Enter 5 integer values: ");
      int intArray[] = new int[5];
      for(int i=0; i<5; i++){
         intArray[i] = sc.nextInt();
      }
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
      //float array to String
      System.out.println("Enter 5 float values: ");
      float floatArray[] = new float[5];
      for(int i=0; i<5; i++){
         floatArray[i] = sc.nextFloat();
      }
      System.out.println("Contents of the float array: "+Arrays.toString(floatArray));
      //double array to String
      System.out.println("Enter 5 double values: ");
      double doubleArray[] = new double[5];
      for(int i=0; i<5; i++){
         doubleArray[i] = sc.nextDouble();
      }
      System.out.println("Contents of the double array: "+Arrays.toString(doubleArray));
      //byte array to String
      System.out.println("Enter 5 byte values: ");
      byte byteArray[] = new byte[5];
      for(int i=0; i<5; i++){
         byteArray[i] = sc.nextByte();
      }
      System.out.println("Contents of the byte array: "+Arrays.toString(byteArray));
      //char array to String
      System.out.println("Enter 5 character values: ");
      char charArray[] = new char[5];
      for(int i=0; i<5; i++){
         charArray[i] = sc.next().toCharArray()[0];
      }
      System.out.println("Contents of the char array: "+Arrays.toString(charArray));
      //object array to String
      System.out.println("Enter 5 String values: ");
      Object objArray[] = new Object[5];
      for(int i=0; i<5; i++){
         objArray[i] = sc.next();
      }
      System.out.println("Contents of the object array: "+Arrays.toString(objArray));
   }
}

Output

Enter 5 integer values:
14
12
63
78
96
Contents of the integer array: [14, 12, 63, 78, 96]
Enter 5 float values:
2.1
3.2
14.3
6.1
3.2
Contents of the float array: [2.1, 3.2, 14.3, 6.1, 3.2]
Enter 5 double values:
1254.3256
1458.2354
1478.24
14587.325
1457.325
Contents of the double array: [1254.3256, 1458.2354, 1478.24, 14587.325, 1457.325]
Enter 5 byte values:
1
25
61
11
24
Contents of the byte array: [1, 25, 61, 11, 24]
Enter 5 character values:
a
b
c
d
e
Contents of the char array: [a, b, c, d, e]
Enter 5 String values:
hello
hi
bye
welcome
thankyou
Contents of the object array: [hello, hi, bye, welcome, thank you]
raja
Published on 15-Jul-2019 11:49:26
Advertisements