Site Search:

Create if and if/else and ternary constructs

Back OCAJP


Let's study them with examples, while reviewing the operators learned before.

===if/else if/else===

OCAJP>cat test.java 
class test{
  public static void main(String...args) {
    int x;
    int y = (x = 5) + 2;
    if(y > x) {
      y -= 6L; //y = int(y - 6L);
      int a = y + 1;  //compile
      System.out.println(y+=x--/3 + y++); //3,4,3
      //System.out.println(y+=(x--/3 + y++));  //3,4,3
      //System.out.println(y= (int)(y + (x--/3 + y++)));  //3,4,3
      //x--;System.out.println(y= (int)(1 + (1 + 1)));  //3,4,3

      //System.out.println((y+=x--/3) + (y++));//4,4,3
      System.out.println(x);  
      System.out.println(y);
      System.out.println(y>x);//false
    } else if (y == x) {
      System.out.println(y == x);
    } else {
      System.out.println();
    }
  }
}
OCAJP>javac test.java 
OCAJP>java test
3
4
3
false


ternary constructs or the ternary operator (? :) is the only opeator that takes three operands:
booleanExpression ? expression1 : expression2



OCAJP>cat test.java 
class test{
  public static void main(String...args) {
    boolean x = true;
    boolean y = false;
    short i = 4;

    if(x) i = 4; else i = -1000;
    i = x?(short)4:(short)-1000;  //equivalent to above
    //i = x?4:-1000; //possible lossy conversion from int to short

    //int j = x^y ? ++i++: 0; //not compile
    int j = x^y ? ++i: 0; 
    System.out.println(j);  //5  
    j = x&y ? i++ : 0;
    System.out.println(j);  //0
    System.out.println(!x|y!=true);  //true
    //j = !x|y!=true ? i++ : 10L; //possible lossy conversion from long to int 
    j = !x|y!=true ? i++ : 10; 
    System.out.println(j);  //5
  }
}
OCAJP>javac test.java 
OCAJP>java test
5
0
true
5
Back OCAJP