Logical operator in JAVA




 Logical operators are widely used in decision making in JAVA. The Operators are used to check the given condition or expression whether they are true or false. Mostly logical operators are used to check condition if there are two or more expression and whether the expressions(two or more expressions) are returning true or not. There are three logical operator i.e. AND Operator (&&), OR Operator (||) and NOT Operator (!). Lets see below example to explore it in more convenient way. 

Let's suppose we are making console application based voting system. The criteria are defined below.

1)Must be citizen of some regulatory body, lets assume Nepal. At first he or she must have proof that he       or  she crossed 16 and has citizenship card. Then only the persoin is known as citizen. 

1) Must have crossed age 18. (Age defined he or she is eligible for vote or not).

2) Must have Voting Card.

If all the condition is satisfied then he or she is eligible to vote. Let's check this condition in java console based application.


public class VotingSystem {

public static void main(String[] args) {

int age = 19; // lets assume age = 19

boolean isCitizen = true; // lets assume he/she has citizenship

boolean hasVotingCard = true; // lets assume he/she has voting card.

boolean hasFather = true; // lets assume he/she has father

boolean hasMother = true; // lets assume he/she has mother

if (!(age > 18)) {

System.out.println("You are not eligible for voting");

}

if (hasMother || hasFather) {

System.out.println("you can apply for Citizenship card type: Descendant");

}

if (age > 18 && isCitizen && hasVotingCard) {

System.out.println("You are eligible for voting");

} else {

System.out.println("You are not eligible for voting");

}

}

}


In above code, variables are predefined for easiness. Using ! sign, if age is not greater then 18 is being checked. If condition is true, System.out.println("You are not eligible for voting"); will be executed. Using || sign, whether he/she has father or mother is checked. If any one of them is alive then he/she can get citizenship card (descendant). System.out.println("you can apply for Citizenship card type: Descendant"); will be executed. 

 Inside IF Condition three expressions are being checked whether all the conditions are satisfied or not to take decision to display the result. If all the condition satisfied then System.out.println("You are eligible for voting"); will be executed. If condition are not true than System.out.println("You are not eligible for voting");  will be executed. 

In this way we can use logical operators according to our need. 

You can get more videos on JAVA on youtube channel also: http://bit.ly/2Lrs2WC





Comments

Popular posts from this blog

Class and Object in Java

Loop Structure