how to convert Object array to String array in java

By Saruque Ahamed Mollick

In this Java tutorial, I will show you how to convert object array to string array in Java. I have read many articles on this object array to string array conversion. But in this tutorial, I will convert an object array to a string array in the easiest way.

In order to do that we can use this below logic:

  • list.toArray() returns an object.
  • If we pass String[] array to it as a parameter, it will be converted easily.

I am going to make it understandable with an easy example.

How to create an object of a Java class?



Convert object array to string array in Java with an example

Here I am going to create an ArrayList first. Then I will add some elements to it.

import java.util.ArrayList;
public class Myclass {
    public static void main(String args[]){
        List<String> list=new ArrayList<String>();
        list.add("CodeSpeedy");
        list.add("ArrayList");
        list.add("Java");
        String[] myobjects = list.toArray(new String[0]);
        for(String string_array: myobjects) {
        System.out.println(string_array);
      }
 } 
}

Output:

CodeSpeedy
ArrayList
Java

String[] myobjects = list.toArray(new String[0]);
here list.toArray returns the objects. And we have passed String[] as parameter. Thus it has been converted easily.

So, the output we got is now a string array.

In this way, you can achieve your goal.

If you wish you can use other methods too. If you like to share your code you are always welcome.
Share your idea with us in the below comment section.

How to convert an image to byte array in Java

Guess The Number Game Using Java with Source Code

2 responses to “how to convert Object array to String array in java”

  1. some guy says:

    shouldn’t strObjects be myobjects?

  2. Saruque Ahamed Mollick says:

    Thanks. Was just an error. As I was writing my codes on sublime, and while copying I forget to change this object name. Now it is fixed

Leave a Reply

Your email address will not be published. Required fields are marked *