Conditional operator: ?

This example reads in two numbers and finds the smallest. Notice that the result of the conditional operator is assigned to small.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Find smallest
package numbers;
import java.util.*;
public class FindSmall {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int num1,num2,small;
    System.out.print("Enter a number:");
    num1=keyboard.nextInt();
    System.out.print("Enter another number:");
    num2=keyboard.nextInt();
    small=(num1<num2)? num1: num2;
    System.out.println("The smaller is "+small);
  }//main
}//class
CODE

Sample output:

Enter a number:5
Enter another number:3
The smaller is 3

Enter a number:12
Enter another number:20
The smaller is 12

Enter a number:9
Enter another number:9
The smaller is 9

NEXT: