Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Master-java Conditional operator in java

Related Tutorials


 
 

Share on Google+Share on Google+

Conditional operator in java

Advertisement
Conditional operators return either true or false value based on the expression.

Conditional operator in java

Operator are used to perform some specific operation. In this tutorial we will discuss about conditional operator in java. Conditional operator is used to evaluate boolean expression which return or false. The operation performed between two boolean expressions. It has three operands. The conditional AND(&&) and conditional OR( | | ) perform on two boolean expression. Now here is the example how it works:

public class Demo
{
 public static void main(String args[])
 {
 int a=10;
 int b=2;
 if((a==10)&&(b==2)){
  System.out.println(" conditional AND");}
  if((a==10)||(b==2)){
  System.out.println("Conditional OR");}
  }
 }

The example above show how these conditional AND and conditional OR works, if the value of a=10 and b=2 then it become true and print "conditional AND", second one if a=10 or b=2 one of the condition become true, "conditional Or" get printed.

When you will execute the above example the output will be as follows:

Download Source Code

One more conditional operator ?:, which take three operands that's why it is called ternary operator.

syntax: variable a = (expression) ? statement-1 if true : statement-2 if false

This statement could be read as, "if  condition is true then assign to value of statement-1 to a,  otherwise assign the value of statement-2 to a".

public class Demo
 {
  public static void main(String args[])
  {
  int a=10;
  int b=2;
  boolean condition=true;
  int result=condition ? a : b;
  System.out.println("Result = " +result);
  }
 }

This program will print 10 to the console,  if condition is true. otherwise print 2. Ternary operator is used instead of if-else statement because it increase the readability of code.

When you will execute the above example the output will be as follows:

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 19, 2013

Related Tutorials

Discuss: Conditional operator in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com