Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Conditional (Logical) Operators

                         

Conditional operators return a true or a false value based on the state of the variables i.e. the operations using conditional operators are performed between the two boolean expressions.

Symbol Name of the Operator
 & AND
 && Conditional-AND
 | OR
 ||  Conditional-OR
 ! NOT
 ? :   Ternary (shorthand for if-then-else statement)

I. AND (&) and Conditional-AND (&&) operators:

  The AND (&) operator  is similar to the Conditional-AND operator (&&). Both of its operands are of boolean type, even these operands may be boolean expressions. Other Relational operators can also be used with these operators.

Lets use a Truth Table to know the status of an output

 Op1 or Exp1  Op2 or Exp2  Result
 True  True  True
 False  False  False
 True  False  False
 False  True  False

If we analyze the table we find that result is always true only in case of first condition where both operands(or expressions) are true. On the other hand result is always false in other conditions. 

Note that  this table works alike for & and && operators.

In case of "&" operator, if both operands or expressions are true, the result is always true, otherwise it is false if either left-hand or right-hand operand is false

In case of  "&&" operator, the result is also true, if both operands or expressions are true
But this operator evaluates only the left-hand operand. It doesn't evaluate the right-hand operand if the left-hand operand is false then it will not jump to the right-hand operand to evaluate it, and will come out from that statement and read the next statement. That's why this mechanism is known as short-circuiting. Consider the following statements where the second expression returns false after evaluating only the left-hand operand.

 true   &&  true  = true;      // both operands are evaluated
 false  &&  true = false;    
// only left-operand is evaluated

But the "&" operator always evaluates both of its operands whether the first operand is true or false. Consider the following statements where the second expression returns false after evaluating the right-hand operand.

   true  &  true   = true;       // both operands are true
   true  &  false  = false;     
//  both operands are evaluated 

II.  OR (|)and Conditional-OR (||)operators :

 Likewise, the OR operator(|) is similar to the Conditional-OR operator (||) and returns true, if one or another of its operand is true.
Lets use a Truth Table to know the status of an output that works alike for "|" and "| |" operators.

 Op1 or Exp1  Op2 or Exp2  Result
 True  True  True
 False  False  False
 True  False  True
 False  True  True

If we analyze the table then we find that, result is always false only if both operands or expression are false. On the other hand, result is always true in rest of the other conditions.

Still these exists a major difference in their mode of use: 

The "|" operator always evaluates both of its operands and returns true if one or other of its operand is true. Otherwise false if both the conditions are  false. Consider the following statements where the second expression returns false after evaluating the right-hand operand.

 true  | false = true;       // left operand is true but both are evaluated
 false | false = false; 
     //both operands are evaluated  

In case of "||" the result is also true, if one of the both operands is true. Otherwise it evaluates to false if both operands are false. But this operator conditionally evaluates the right-hand operand only if the left-hand operands is false. Like the Conditional-AND operator, this mechanism is also known as short-circuiting. Consider the following statements where the first expression returns true after evaluating the right-hand operand.

false || true  = true;    // both operands are evaluated
true  || false = true;  
  // only left-operand is evaluated

III. NOT ("!") operator :

The NOT ("!") operator performs the boolean NOT operation on a single operand or an expression. It checks the boolean status of a current operand or expression and reverses the value of a boolean expression i.e. if the current value of an operand or expression is true then it reverses as false; but if the value of an operand or expression is false then it reverses as true.
Consider the following example:

class BoolNotDemo {
  public static void main(String[] args){
    int x = 2;
    int y = 1;
    boolean bl;

     bl = !(x > y); // bl is false
     System.out.println("x is not greater than y:"+bl);

       bl = !(y > x); // bl is true
   System.out.println("y is not greater than x:"+bl);
  }
}

Output of the Program: 

C:\nisha>javac BoolNotDemo.java

C:\nisha>java BoolNotDemo
x is not greater than y : false
y is not greater than x : true

Download this program

IV. ternary ("?:") operator

Java supports another conditional operator that is known as the ternary  operator "?:"  and basically is used for an if-then-else as shorthand as

boolean expression ? operand1 : operand2;

The "?:" operator evaluates an expression which may also be an operand and returns operand1 if the expression is true; otherwise returns operand2, if the expression is false. We can understand this thing with the help of a diagram shown as:

If we analyze this diagram then we find that, operand1 is returned, if the expression is true; otherwise operand2 is returned in case of false expression.

Lets have an example implementing some  Logical operators:

class ConditionalOperator {

     public static void main(String[] args){
          int x = 5;
          int y = 10, result=0;
      boolean bl = true;
          if((x == 5) && (x < y))
        System.out.println("value of x is "+x);
          if((x == y) || (y > 1))
        System.out.println("value of y is greater than the value of x");
         result = bl ? x : y;
        System.out.println("The returned value is "+result);
     }
}

Output of the Program: 

C:\nisha>javac ConditionalOperator.java

C:\nisha>java ConditionalOperator
value of x is 5
value of y is greater than the value of x
The returned value is 5

Download this Program

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Latest Searches:
duplicate string in ar
Jframe Tutorials
find the number of day
Photoshop Web Layouts
jquey
StringtoStringarray
Java example program t
cancel button in Jsp
paper insert in coreld
connection pooling wit
seam many to many
struts framework archi
DBMS
mtab comany
Java Swing Center a Di
simialaritytransformma
Agents
JProgressBar
addinghibernatetoolsin
duplicate string in a
to set combox
break?à®?à®??à®???????
ejb 2
paint()
server means
checkastringforspaces
how to design chocolat
Java 3D
the action class
hibernatefind(object)
registeremailaddresswi
Read the Key-Value of
servlet.jar download
json with gwt
programinjavatoimpleme
Photoshop Photo Retouc
openGL
Datetimepicker FOR .NE
how to get the text da
EasyEclipse for Ruby
send parameters in ser
Cinema 4D Materials Li
update mysql using jsp
Apache JSP
Vector
retrieve image into da
usingcheckboxinJ2EE
optimistic lock
ip
Display Data from Data
whyamethodcannotfindas
Lightwave3DModellingEa
tomcate 5.0 downloadab
create a DAtabase usin
volatile variables
hashtable
addtwonumbersinjavausi
Photoshop Drawing Rain
ajax tutorial
convert calendar to da
example for trim() met
HttpRequestAttributeLi
set session servlet
examples of java progr
MULTIPLE SELECT COMBO
Photoshop Effects Crea
createxmlusingjava
ActionFormbeaninstruts
beans setproperty
Jigloo SWT/Swing GUI B
commentinphp
'stringvariableinswitc
how 2 getAttribute for
If tag Struts2
string buffer in java
compare two classs
Photoshop Brushes Spar
example of sendredirec
swithstatementexamplei
call ?о????????о????
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.