4 Replies - 185 Views - Last Post: 18 June 2011 - 11:07 AM Rate Topic: -----

#1 metric  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 183
  • Joined: 22-May 10

Syntax clarification

Posted 18 June 2011 - 08:19 AM

Hi guys,

I came across this line and I do not understand what it means:

return t == null ? null : t.element;



Thanks
Metric
Is This A Good Question/Topic? 0
  • +

Replies To: Syntax clarification

#2 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 559
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: Syntax clarification

Posted 18 June 2011 - 08:28 AM

Its just using different operators. In java, there is a lot of situtations where people use if else loops. Its commonly if something is true, return something, else, return something else. What you have showed is a shortcut to perform everything in one statement. The way it works is that it checks everything before the ? So, t == null. If this is true, it will return null. If it is false, it will return t.element. So if you look at it, you can say check this (everything before ?) and return one of these (the two values either side of the :)
Was This Post Helpful? 1
  • +
  • -

#3 immeraufdemhund  Icon User is offline

  • D.I.C Regular

Reputation: 79
  • View blog
  • Posts: 494
  • Joined: 29-March 10

Re: Syntax clarification

Posted 18 June 2011 - 08:31 AM

and you seperate the if it's true and if it's false with a :
Was This Post Helpful? 1
  • +
  • -

#4 metric  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 183
  • Joined: 22-May 10

Re: Syntax clarification

Posted 18 June 2011 - 08:46 AM

Ah!

Nifty!! Thanks guys =D +1 for you guys

metric
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8016
  • View blog
  • Posts: 31,118
  • Joined: 06-March 08

Re: Syntax clarification

Posted 18 June 2011 - 11:07 AM

View Postmetric, on 18 June 2011 - 11:19 AM, said:

I came across this line and I do not understand what it means:

return t == null ? null : t.element;

I barely use that syntax, I really prefer
if(t == null)
   return null;
else
   return t.element;



However in a method call it is usefull, it avoids to create temporary variables.

boolean answer;

System.out.printf("The answer was: %s", answer ? "Yes: : "True");


rather than
String yesNo;
if(answer)
   yesNo = "Yes";
else
   yesNo = "No";
System.out.printf("The answer was: %s", yesNo);


This post has been edited by pbl: 18 June 2011 - 11:08 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1