Pages

Java ternary operator

Today i have learned about ternary operator in java. Before this, when i found it in java code, i will ask myself what it is and what we call it...now i will share with you what i understand about ternary operator.Now, see java code below


************************************************************
COMPLETE SOURCE CODE FOR : JavaTernaryOperator.java
************************************************************


public class JavaTernaryOperator
{
public static void main(String[]args)
{
int a=0;
int b=4;
int c=5;

//THIS IS EXAMPLE OF TERNARY OPERATOR
a=(b>c?b:c);

System.out.println(a);
}
}


************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************

In the java code above, example of ternary operator is a=(b>c?b:c);.So, what it mean ?

This is the answer :
Value a is equal to b if b larger than c or value a is equal to c if b smaller than c.So, java code above has same meaning with java code below.


public class JavaTernaryOperator
{
public static void main(String[]args)
{
int a=0;
int b=4;
int c=5;

if(b>c)
{
a=b;
}
else
{
a=c;
}

System.out.println(a);
}
}


Now, you can choose which one you want to use when write your java program. It seem when we use ternary operator we can make our program more shorter.
Related Posts Plugin for WordPress, Blogger...

I Also Can Create T-Shirt Logo For You