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?
You can return only one value in Java. If needed you can return multiple values using array or an object.
The correct syntax would be
return new String[]{ ans1, ans2 };
Even though you've created two String
s (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.
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.
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