0

I want to ask a Java String[] question. In the java, if a variable convents to another, it can add the (String), (int), (double),... before the variable in the left hand side. However, is there something like (String[]) in Java as I want to convent the variable into (String[]).

4 Answers 4

2

Yes, there is (String[]) which will cast into an array of String.

But to be able to cast into a String array, you must have an array of a super type of String or a super type of array (only Object, Serializable and Cloneable).

So only these casts will work :

String[] sArray = null;
Object[] oArray = null;
Serializable[] serArray = null;
Comparable[] compArray = null;
CharSequence[] charSeqArray = null;
Object object = null;
Serializable serializable = null;
Cloneable cloneable = null;

sArray = (String[]) oArray;
sArray = (String[]) serArray;
sArray = (String[]) compArray;
sArray = (String[]) charSeqArray;
sArray = (String[]) object;
sArray = (String[]) serializable;
sArray = (String[]) cloneable;
Sign up to request clarification or add additional context in comments.

1 Comment

@Carlos Heuberger, I knew I forgot something, I'll edit the answer ;)
2
  1. What you call 'convert' is actually called 'cast'.
  2. Casting variable has no effect on object itself. In other words, (String) x is not equivalent of x.toString()
  3. String[] is a perfectly normal Java class, just like any other. Try this, for example:

    System.out.println(String[].class.getName());

You can also check 'Casting Objects' section in Java tutorial:
http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html

Comments

1

What you want is probably not casting to String[], because your object is not a String[] but something else. What I think you are looking for would be something like this:

int someInt = 1;
long someLong = 2;
String[] strings = new String[] {
    Integer.toString(someInt), 
    Long.toString(someLong)};

Comments

0

Yes, ofcourse.

Example:

String s1 = "test1";
String s2 = "test2";
Object obj [] = new Object[]{s1,s2};
String s[] = (String[]) obj;
System.out.println(s1);
System.out.println(s2);

1 Comment

String s = (String[]) obj; will crash, you cannot convert String[] to String...and why are you printing s1 and s2?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.