Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Java code Question?

  • 02-01-2014 01:30PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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, Registered Users 2 Posts: 1,110 ✭✭✭Skrynesaver


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


  • Registered Users, Registered Users 2 Posts: 6,505 ✭✭✭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, Registered Users 2 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