Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java code Question?

Options
  • 02-01-2014 1:30pm
    #1
    Registered Users Posts: 474 ✭✭


    Hi there,
    I have encountered a piece of code in a sample exam question and I am unsure as to what it means.
    This is the code:
    class Test{
    public static void main(String[] args){
    for(int i = 0; i < args.length; i++){
    System.out.print(i == 0 ? args : " " + args);
    }
    }
    }

    The question asked is "What will be the output when it's run using the following command: java Test good bye friend!"

    The output is good bye friend! But the part I cannot understand is the part within the brackets in the System.out.print statement. Can anyone help me?

    TL:DR
    What's going on in line 4 of my code?
    Thanks!


Comments

  • Closed Accounts Posts: 909 ✭✭✭camel jockey


    It is a 'shortcut' for an if else statement.

    If i equals 0 output the argument, otherwise output a space and the argument, the space being a separator. Just a quick way of adding the spacer where needed.


  • Registered Users Posts: 474 ✭✭Umekichi


    It is a 'shortcut' for an if else statement.

    If i equals 0 output the argument, otherwise output a space and the argument, the space being a separator. Just a quick way of adding the spacer where needed.

    Oh ok, I get it now Thanks!


  • Closed Accounts Posts: 909 ✭✭✭camel jockey




  • Registered Users Posts: 1,109 ✭✭✭Skrynesaver


    The
    value=condition?value1:value2
    
    construct is known as the ternary operator, it's a bugger to google ;)


  • Registered Users Posts: 6,398 ✭✭✭run_Forrest_run


    The
    value=condition?value1:value2
    
    construct is known as the ternary operator, it's a bugger to google ;)

    I always forget the name of the operator, googling is indeed fun, 'question mark in Java statement' is my common search term:D


  • Advertisement
  • Registered Users Posts: 3,945 ✭✭✭Anima


    Bit pedantic but it is "a" ternary operator, not "the". I made this mistake myself.
    http://en.wikipedia.org/wiki/%3F:
    In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if.


Advertisement