-1

I was reading through a Java program that my professor recommended we look at and think about how each line would work when I ran into this line of programming. The program deals with fractions and this line came up in a method used to determine the greatest common divisor. The part that confuses me is the coding within the parentheses because I'm not sure what the "?" would do in addition to the "top : bottom". If anyone could explain what this does, I would greatly appreciate it!

5 Answers5

2
int min;
if (top < bottom)
  min = top;
else
  min = bottom;

same as above codes

Kent
  • 189,393
  • 32
  • 233
  • 301
1

That's called a ternary operator and basically it's a shorthand for

if (top < bottom) {
    min = top;
} else {
    min = bottom;
}
Warlord
  • 2,798
  • 16
  • 21
0
if (top<bottom)min=top
else min=bottom
SteveL
  • 3,331
  • 4
  • 32
  • 57
0

That is a ternary operator performing an inline if then statement

Popo
  • 2,402
  • 5
  • 33
  • 55
0

It's the ternary operator (not necessarily specific to Java; it is also used in other programming languages).

In Java, it is the only operator that accepts 3 operands. What it actually does, is:

-- given a ? b : c

-- evaluates a, which should be a boolean expression

-- if a is true, then the whole operator returns b

-- otherwise, it returns c

Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
  • 1
    Note it's **a** ternary operator, not **the** ternary operator. Its real name is the [conditional operator](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25). – Oliver Charlesworth Feb 23 '14 at 21:38