The ? operator enables you to embed expressions that are conditional on the value of a boolean expression. The format is
boolean expression ? expression1 : expression2
expression1 is executed if the boolean expression is true; expression2 is executed if boolean expression is false. The following code uses the ? operator:
public static void main(String[] args)
{
System.out.println(args.length +
(args.length == 1 ? " argument has been provided" :
" arguments have been provided") );
}
The preceding code could be rewritten replacing the ? With the if else construct, as follows:
Public static void main(String[] args)
{
if (args.length == 1)
{
System.out.println(args.length + " argument has been provided");
}
Else
{
System.out.println(args.length + " arguments have been provided");
}
}
boolean expression ? expression1 : expression2
expression1 is executed if the boolean expression is true; expression2 is executed if boolean expression is false. The following code uses the ? operator:
public static void main(String[] args)
{
System.out.println(args.length +
(args.length == 1 ? " argument has been provided" :
" arguments have been provided") );
}
The preceding code could be rewritten replacing the ? With the if else construct, as follows:
Public static void main(String[] args)
{
if (args.length == 1)
{
System.out.println(args.length + " argument has been provided");
}
Else
{
System.out.println(args.length + " arguments have been provided");
}
}
No comments:
Post a Comment