I met a problem, code like this:
public class Test {
public static void main(String[] args) {
String str1 = "1";
String str2 = "2";
String str3 = "3";
boolean flag = true;
// way 1
test(flag? str1, str2, str3: str1);
// way 2
test(flag? (str1, str2, str3): str1);
// way 3
test(flag? new String[]{str1, str2, str3}: str1);
// way 4
test(flag? new String[]{str1, str2, str3}: new String[]{str1});
// way 5
test(flag? str1: str2);
}
private static void test(String... args) {
for(String arg: args) {
System.out.println(arg);
}
}
}
I used five ways to call method test():
way 1 called failed. I thought I missed the parentheses.
way 2 failed. I thought it's the problem of (str1, str2, str3), Java compiler didn't understand it.
way 3 failed. new String[]{} is a String[] object, why Java compiler still didn't understand it?
way 4 successfully. the left and right parameter of colon is the same type. So, I called it in way 5.
way 5 called successfully.
I guessed:
?(1):(2), the parameters in place 1 and 2 must be the same type?
Can anyone who have a good understanding of operator :? solve my confusion? Thank you.