Bookmark Topic Watch Topic
  • New Topic

Question mark in Java  RSS feed

 
Charles HAN
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hi guys,

I've found a piece of interesting code like this " int i;
System.out.println(i + (i!=2 ? ", " : "")); "
just wondering what the "?" & ":" doing here? and why it can be used in Java?

Cheers
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Report post to moderator
They are what is called the "ternary operator" - the only operator that takes 3 arguments. the format is

(boolean) ? (value1) : (value2)

it's really a shortcut for


The boolean can be anything that evaluates to a boolean, such as "x==2".
[ July 23, 2004: Message edited by: fred rosenberger ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Report post to moderator
Looks like an accidental double post; I'm closing this one. Followups to the other copy .
 
It is sorta covered in the JavaRanch Style Guide.
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!