-3

In the code below:

public static void main(String[] args) {
    String echo = (args.length == 1) ?  "Your name is "+args[0]: "Wrong number of arguments!";
    System.out.println(echo);
}

It will print your name if you give only one argument, otherwise it will warn you with wrong number of arguments, which is pretty clear, but how does ?: operator work here?

3 Answers3

2

The ?: operator is called Ternary operator, it is used as follows:

condition ? value_if_true : value_if_false

Your code can be written as:

public static void main(String[] args) {

    String echo = null;
    if(args.length == 1){
        echo = "Your name is " + args[0];
    }else{
        echo = "Wrong number of arguments!";
    }

    System.out.println(echo);

}   
betteroutthanin
  • 6,578
  • 8
  • 27
  • 47
0

The ternary operator.

a ? b : c

means: b if a is true, otherwise c

khelwood
  • 52,115
  • 13
  • 74
  • 94
0

It is sort of like an if clause. The first part of this ternary operator is the test statement, and if it evaluates to true it executes the code after ? and if it's not, then it executes after :

Franko Leon Tokalić
  • 1,437
  • 2
  • 22
  • 27