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.
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.
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With