Search Logic Blocks

Tuesday, January 7, 2020

Java: Relational Operators

Relational operators are also called the comparison operators. Comparison operators are used to compare two values of the same data type and to return the result as a single boolean value - true or false. Following is the chart of all relational / comparison operators.

Suppose, x = 8, y = 6 then:

Operator Comparison Operation Result
== Equality x == y false
!= Not Equal To x != y true
> Greater Than x > y true
< Less Than x < y false
>= Greater Than / Equal To x >= y true
<= Less Than / Equal To x <= y false

Below is an example, how to write comparison operator Greater Than (>) -
boolean blnGreater;

int x = 45, y = 70;
blnGreater = (x > y); // will return false

y = 35;
blnGreater = (x > y); // will return true
Example : What should be the result of the following java code? Let's see - 

Class Compare (Compare.java)
public class Compare {
    public static void main(String args[]) {
        int x = 50, y = 50;
        boolean blnResult = false;

        int result = x + (y / 2) - 10;
        blnResult = (result == 30);

        System.out.println("Result is equal to 30: " + blnResult);
        System.out.println("Result is: " + result);
    }
}
result = x + (y / 2) - 10 = 50 + (50 / 2) - 10 = 50 + 25 - 10 = 65
blnResult = (result == 30) = (65 == 30) = false

Result is equal to 30: false
Result is: 65

Monday, January 6, 2020

Java: Assignment Operators

What is assignment?
Earlier, we learnt about all the data types, how to declare the variables using appropriate data types and their possible values of each data type. When we set the value to a variable first time, it is called initialization, and when we change the value using = operator, it's called an assignment.

int a; // Declaring a variable
int a = 5; // Declaring and initialization
a = 8; // assigning the values

What are the assignment operators?
Assignment operators are those operators, which perform operation on the variable and also assign the result to the variable same time. Following is the chart of all assignment operators. Earlier, we learnt about two unary operators - increment (++) and decrement (--) operators, they are assignment operators too.

Suppose, x = 15 and y = 6, then:
Operator Code Operation Result
= x = y x = y x = 6
+= x += y x = x + y x = 21
-= x -= y x = x - y x = 9
*= x *= y x = x * y x = 90
/= x /= y x = x / y x = 2
%= x %= y x = x % y x = 3
++ x++ x = x + 1 x = 16
-- x-- x = x - 1 x = 14

Suppose, x = true and y = false, then:
Operator Code Operation Result
&= x &= y x = x & y x = false
|= x |= y x = x | y x = true
^= x ^= y x = x ^ y x = true

NOTE: These assignment operators are also called compound assignment operators and they are very efficient. So, these operators are used frequently.