-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?

user3289218
  • 87
  • 1
  • 5

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
  • 7,148
  • 8
  • 29
  • 48
0

The ternary operator.

a ? b : c

means: b if a is true, otherwise c

khelwood
  • 55,782
  • 14
  • 81
  • 108
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,457
  • 3
  • 22
  • 28