1. Introduction
Logical operators are a cornerstone of programming logic, allowing you to combine multiple conditions. Scala supports all the standard logical operators found in many other programming languages. This blog post will introduce Scala's logical operators and show how to use them with examples.
Scala - Logical Operators
Scala provides the following logical operators to form compound Boolean expressions:
&& (Logical AND): Returnstrue if both operands aretrue.
|| (Logical OR): Returnstrue if at least one of the operands istrue.
! (Logical NOT): Returns the inverse of the Boolean value.
2. Program Steps
1. Define Boolean variables for comparison.
2. Use logical operators to combine these variables into logical expressions.
3. Print the results of the logical operations.
4. Execute the program to observe the Boolean outcomes.
3. Code Program
object LogicalOperatorsDemo extends App { val cond1: Boolean = true val cond2: Boolean = false // Logical AND println(s"cond1 && cond2: " + (cond1 && cond2)) // Logical OR println(s"cond1 || cond2: " + (cond1 || cond2)) // Logical NOT println(s"!cond1: " + (!cond1)) println(s"!cond2: " + (!cond2))}Output:
cond1 && cond2: falsecond1 || cond2: true!cond1: false!cond2: true
Explanation:
1. InLogicalOperatorsDemo, we declare two Boolean variablescond1 andcond2, wherecond1 istrue andcond2 isfalse.
2. We then perform logical operations using&& (AND),|| (OR), and! (NOT) operators. For example,cond1 && cond2 evaluates if bothcond1 andcond2 are true, which in this case isfalse.
3. The|| operator checks if at least one ofcond1 orcond2 is true. Here,cond1 is true, so the whole expression evaluates totrue.
4. The! operator negates the Boolean value, so!cond1 returnsfalse, and!cond2 returnstrue.
5. The output clearly shows each operation's result, which corresponds to the basic rules of logical operations in Boolean algebra.
Comments
Post a Comment