Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two strings in one return statement?

Tags:

java

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?

like image 576
higherDefender Avatar asked Feb 20 '10 05:02

higherDefender


People also ask

Can you return 2 values in Java?

You can return only one value in Java. If needed you can return multiple values using array or an object.


2 Answers

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.

like image 112
Mark Elliot Avatar answered Oct 11 '22 03:10

Mark Elliot


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.

like image 43
Corey Sunwold Avatar answered Oct 11 '22 03:10

Corey Sunwold