Thursday, 28 December 2017

2.1 If Else and Ternary operator

Below is the example of even odd , Biggest number and ternary operator.

class IfElse
{
public static void main(String args[])
{
//If else
int a=5;

if(a%2==0)
{
System.out.println("Even");
}
else
{
System.out.println("Odd");
}

   //if else if
int p=4;
int q=9;
int r=2;

if (p>q && p>r)
{
System.out.println(p+" is greater than "+q+" and "+r);
}
else if (q>p && q>r )
{
System.out.println(q+" is greater than "+p+" and "+r);
}
else
{
System.out.println(r+" is greater than "+p+" and "+q);
}

//ternary operator
int x=4;
int y=5;
int z=x>y?2:10; // x is less than y therefore it will give 10
System.out.println(z);


//ternary operator is not the exact replacement of if else
Object obj1;
if(true)
{
obj1=new Integer(10);
System.out.println(obj1);
}
else
{
obj1= new Double(20.0);
System.out.println(obj1);
}
//the if else answer will be 10 but ternary output will be 10.0
// in ternary the datatype of output will be the biggest datatype from the both of the variable
Object obj2;
System.out.println(true?new Integer(10):new Double(20.0));
System.out.println(false?new Integer(10):new Double(20.0));
}
}

No comments:

Post a Comment