Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement inside the print statement?

How can I write an if statement inside the print statement?

public boolean checkEmpty()
{
    if(array.isEmpty)
    {
        Sytem.out.println("The List is empty");
    }
    else
    {
        System.out.println("The list has: " +  if(array.size() > 1)) {"Items"} + else {"item"} );
    }
}
like image 486
mohamed ghassar Avatar asked Oct 25 '13 21:10

mohamed ghassar


1 Answers

You can't write an if statement inside an expression like that.

However, you can use Java's ternary operator ?: (scroll down about half way in the linked page) to embed a conditional expression:

System.out.println("The list has: " +  ((array.size() > 1) ? "items" : "item"));

The format is:

booleanCondition ? valueIfTrue : valueIfFalse
like image 102
rgettman Avatar answered Oct 05 '22 03:10

rgettman