In this chapter you will learn:
- What is logical/Conditional operator in Java?
- Logical operator symbol
- Programming example
What is logical operator in Java?
Logical operator is also known as conditional operator in java. It is And (&&), Or(||) andNot(!). The logical operator is very useful when you need to compare two statements.
Operator | Description | Example |
&& | Conditional-AND – Compare two statement and return true if both are true | if(username==”user1″ && password==”pass123″) |
|| | Conditional-OR – compare two statement and return true if one of them is true | if(username==”user1″ || password==”pass123″) |
?: | Ternary (shorthand for if-then-else statement) | variable x = (expression) ? value if true : value if false |
You can understand the working of logical or conditional operator using this programming example:
Programming Example:
class LogicalOperator { public static void main(String[] args) { String username, password; username="user1"; password="pass123"; if(username=="user1" && password=="pass123") { System.out.println("Authorized Login Successful"); } else if(username=="user1" && password!="pass123") { System.out.println("Incorrect Password"); } else if(username!="user1" && password=="pass123") { System.out.println("User Not Registered"); } else { System.out.println("Incorrect UserID and Password"); } } }
Output
D:\JavaProgram>javac LogicalOperator.java
D:\JavaProgram>java LogicalOperator
Authorized Login Successful
D:\JavaProgram> __
Summary
In this chapter you have learned what is logical operator or conditional operator in Java. Mostly And(&&), Or(||) and Not(!) is considered as logical operator in Java. In the next chapter you will learn about Ternary Operator in Java.