letsdoitjava

if shorthand

Jul 8th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1.  
  2. public class JavaTernaryOperatorExamples {
  3.     /**
  4.        * Examples using the Java ternary operator
  5.        * @author alvin alexander, devdaily.com
  6.        */
  7.       public static void main(String[] args)
  8.       {
  9.         // min value example
  10.         int minVal, a=3, b=2;
  11.         minVal = a < b ? a : b;
  12.         System.out.println("min = " + minVal);
  13.         System.out.println();
  14.        
  15.         // absolute value example
  16.         a = -10;
  17.         int absValue = (a < 0) ? -a : a;
  18.         System.out.println("abs = " + absValue);
  19.         System.out.println();
  20.  
  21.         // result is assigned the value 1.0
  22.         float result = true ? 1.0f : 2.0f;
  23.         System.out.println("float = " + result);
  24.         System.out.println();
  25.      
  26.         // result is assigned the value "Sorry Dude, it's false"
  27.         String s = false ? "Dude, that was true" : "Sorry Dude, it's false";
  28.         System.out.println(s);
  29.         System.out.println();
  30.        
  31.         // example using the ternary operator on the rhs, in a string
  32.         int x = 5;
  33.         String out = "There" + (x > 1 ? " are " + x + " cookies" : "is one cookie") + " in the jar.";
  34.         System.out.println(out);
  35.       }
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment