method(b ? "hello" : "hi", "whats", "going", "on");
When b == true what I get is is: "hello", "whats", "going", "on";
However what I actually want is:
method(b ? "hello" : ((((("hi", "whats", "going", "on"))))));
Thank you in advance.
The trenary operator must return the same type for both clauses (in your case, the "true" clause is a String, and it's unclear what is the "false" clause - but you probably want String[]).
You can partially solve it by always returning a String[]:
method(b?new String[] {"hello"}:new String[] {"hi", "whats", "going", "on"});
The first thing I did was to blindly give it a shot in Eclipse, but obviously I could not get anything close to what you're asking for, so instead of just going with try/fail, I took a look at the Java BNF grammar to see what is the shortest syntactically correct way to declare a collection without assignment to a variable.
Assuming that you are trying to avoid declaring extra variables but want the parameters created straight away, I would use the following, which in my humble opinion is the shortest and closest syntactically correct way to get what you want :
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
boolean b = false;
methodSample(b ? new String[]{"Hello"} : new String[]{"hi", "whats", "going", "on"});
}
public static void methodSample(String[] args)
{
System.out.println(Arrays.toString(args));
}
}
However, a cleaner way to do it would probably be :
public static void main(String[] args) {
boolean b = false;
String[] val1 = {"hello"};
String[] val2 = {"hi", "whats", "going", "on"};
methodSample(b ? val1 : val2);
}
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