13
public String[] decode(String message)
{
     String ans1 = "hey"; 
     String ans2 = "hi";  
     return {ans1 , ans2};  // Is it correct?
}

This above example does not work properly. I am getting a error.

How can I achieve the initial question?

5 Answers 5

28

The correct syntax would be

 return new String[]{ ans1, ans2 };

Even though you've created two Strings (ans1 and ans2) you haven't created the String array (or String[]) you're trying to return. The syntax shown above is shorthand for the slightly more verbose yet equivalent code:

String[] arr = new String[2];
arr[0] = ans1;
arr[1] = ans2;
return arr;

where we create a length 2 String array, assign the first value to ans1 and the second to ans2 and then return that array.

Sign up to request clarification or add additional context in comments.

2 Comments

Why is it so? Ive alderly created a string .. if I create a new string like ans1 = new String[] then will it work?
@D.J. because even though you have created String objects you haven't yet created a String array (see my edited answer for more details)
10
return new String[] { ans1, ans2 };

The reason you have to do do this is just saying { ans1, ans2} doesn't actually create the object you are trying to return. All it does is add two elements to an array, but without "new String[]" you haven't actually created an array to add the elements to.

2 Comments

Why is it so? Ive alderly created a string .. if I create a new string like ans1 = new String[] then will it work?
@D.J Updated my answer with further explanation.
4
return new String[] {ans1 , ans2};

1 Comment

Why is it so? Ive alderly created a string .. if I create a new string like ans1 = new String[] then will it work?
2
return new String[]{ans1,ans2};

This should work. To your other question in the comments. Since Java is strongly typed language, all the variables/results should be instantiated. Since you are not instantiating the result you want to return anywhere, we are doing the instantiation in the return statement itself.

Comments

-1

I'm only a high school student at the moment, but an easy solution that I got from a friend of mine should work. It goes like this (this is part of a project in my AP class):

public String firstMiddleLast()
{
   //returns first, middle, and last names
    return (first + " " + middle + " " + last);
}

1 Comment

And then? The caller has to saperate them again...?

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.