Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the Object[] to String[] in Java?

I have a question about Java. I have an Object[] (Java default, not the user-defined) and I want to convert it to a String[]. Can anyone help me? thank you.

like image 208
Questions Avatar asked Oct 07 '10 09:10

Questions


People also ask

What is String [] [] in java?

A Java string is a sequence of characters that exists as an object of the class java. lang. Java strings are created and manipulated through the string class. Once created, a string is immutable -- its value cannot be changed. A string is sequence of characters.

Can we convert String [] to String?

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. We can also create our own method to convert String array to String if we have some specific format requirements.

What does object [] mean java?

What Does Java Object Mean? A Java object is a member (also called an instance) of a Java class. Each object has an identity, a behavior and a state.


1 Answers

this is conversion

for(int i = 0 ; i < objectArr.length ; i ++){  
   try {
      strArr[i] = objectArr[i].toString();
   } catch (NullPointerException ex) {
       // do some default initialization
   }
}  

This is casting

String [] strArr = (String[]) objectArr;  //this will give you class cast exception

Update:

Tweak 1

 String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

Tweak2

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);

Note:That only works if the objects are all Strings; his current code works even if they are not

forTweak1 :only on Java 1.6 and above

like image 115
jmj Avatar answered Oct 05 '22 23:10

jmj