उदाहरणों के साथ जावा लॉजिकल ऑपरेटर्स ||Java Assignment Operator with Examples

Java Logical Operators with Examples
  • Last Updated : 25 Nov, 2019

Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculation and functions be it logical, arithmetic, relational etc. They are classified based on the functionality they provide. Here are a few types:

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators

This article explains all that one needs to know regarding the Logical Operators.

Logical Operators

These operators are used to perform logical “AND”, “OR” and “NOT” operation, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Let’s look at each of the logical operators in a detailed manner:

  1. ‘Logical AND’ Operator(&&): This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. For example, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero).
    Syntax:

    condition1 && condition2

    Example:

    a = 10, b = 20, c = 20
    
    condition1: a < b
    condition2: b == c
    
    if(condition1 && condition2)
    d = a+b+c
    
    // Since both the conditions are true
    d = 50.

    // Java code to illustrate
    // logical AND operator
      
    import java.io.*;
      
    class Logical {
        public static void main(String[] args)
        {
            // initializing variables
            int a = 10, b = 20, c = 20, d = 0;
      
            // Displaying a, b, c
            System.out.println("Var1 = " + a);
            System.out.println("Var2 = " + b);
            System.out.println("Var3 = " + c);
      
            // using logical AND to verify
            // two constraints
            if ((a < b) && (b == c)) {
                d = a + b + c;
                System.out.println("The sum is: " + d);
            }
            else
                System.out.println("False conditions");
        }
    }
    Output:
    Var1 = 10
    Var2 = 20
    Var3 = 20
    The sum is: 50
    
  2. 'Logical OR' Operator(||): This operator returns true when one of the two conditions under consideration are satisfied or are true. If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false.
    Syntax:
    condition1 || condition2

    Example:

    a = 10, b = 20, c = 20
    
    condition1: a < b
    condition2: b > c
    
    if(condition1 || condition2)
    d = a+b+c
    
    // Since one of the condition is true
    d = 50.

    // Java code to illustrate
    // logical OR operator
      
    import java.io.*;
      
    class Logical {
        public static void main(String[] args)
        {
            // initializing variables
            int a = 10, b = 1, c = 10, d = 30;
      
            // Displaying a, b, c
            System.out.println("Var1 = " + a);
            System.out.println("Var2 = " + b);
            System.out.println("Var3 = " + c);
            System.out.println("Var4 = " + d);
      
            // using logical OR to verify
            // two constraints
            if (a > b || c == d)
                System.out.println("One or both"
                                   + " the conditions are true");
            else
                System.out.println("Both the"
                                   + " conditions are false");
        }
    }
    Output:
    Var1 = 10
    Var2 = 1
    Var3 = 10
    Var4 = 30
    One or both the conditions are true
    
  3. 'Logical NOT' Operator(!): Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the condition is true, the operation returns false.

    Syntax:

    !(condition)

    Example:

    a = 10, b = 20
    
    !(a<b) // returns false
    !(a>b) // returns true
    

    // Java code to illustrate
    // logical NOT operator
    import java.io.*;
      
    class Logical {
        public static void main(String[] args)
        {
            // initializing variables
            int a = 10, b = 1;
      
            // Displaying a, b, c
            System.out.println("Var1 = " + a);
            System.out.println("Var2 = " + b);
      
            // Using logical NOT operator
            System.out.println("!(a < b) = " + !(a < b));
            System.out.println("!(a > b) = " + !(a > b));
        }
    }
    Output:
    Var1 = 10
    Var2 = 1
    !(a < b) = true
    !(a > b) = false

1. Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly, there are various other arithmetic operators in Java.

OperatorOperation
+Addition
-Subtraction
*Multiplication
/Division
%Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators

class Main {
  public static void main(String[] args) {
    
    // declare variables
    int a = 12, b = 5;

    // addition operator
    System.out.println("a + b = " + (a + b));

    // subtraction operator
    System.out.println("a - b = " + (a - b));

    // multiplication operator
    System.out.println("a * b = " + (a * b));

    // division operator
    System.out.println("a / b = " + (a / b));

    // modulo operator
    System.out.println("a % b = " + (a % b));
  }
}

Output

a + b = 17
a - b = 7 
a * b = 60
a / b = 2 
a % b = 2 

In the above example, we have used +-, and * operators to compute addition, subtraction, and multiplication operations.

/ Division Operator

Note the operation, a / b in our program. The / operator is the division operator.

If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.

In Java,

(9 / 2) is 4
(9.0 / 2) is 4.5
(9 / 2.0) is 4.5
(9.0 / 2.0) is 4.5

Java Unary Operator Examples

The unary operator works on a single operand. Following are the examples of unary operators supported in java. Assume A = 60 and B = 20.

OperatorDescriptionExample
~ (bitwise compliment)
Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
++ (Increment)
Increases the value of operand by 1.
B++ gives 21
-- (Decrement)
Decreases the value of operand by 1.
B-- gives 19



Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example

int x = 10;

Try it Yourself »

The addition assignment operator (+=) adds a value to a variable:

Example

int x = 10;
x += 5;

Try it Yourself »

A list of all assignment operators:

OperatorExampleSame AsTry it
=x = 5x = 5Try it »
+=x += 3x = x + 3Try it »
-=x -= 3x = x - 3Try it »
*=x *= 3x = x * 3Try it »
/=x /= 3x = x / 3Try it »
%=x %= 3x = x % 3Try it »
&=x &= 3x = x & 3Try it »
|=x |= 3x = x | 3Try it »
^=x ^= 3x = x ^ 3Try it »
>>=x >>= 3x = x >> 3Try it »
<<=x <<= 3

Relational Operators in Java


Relational Operators Supported Data Types

  • The == and != operators can be used with any primitive data types as well as objects.
  • The <, >, <=, and >= can be used with primitive data types that can be represented in numbers. It will work with char, byte, short, int, etc. but not with boolean. These operators are not supported for objects.

Relational Operators Example


package com.journaldev.java;

public class RelationalOperators {

	public static void main(String[] args) {

		int a = 10;
		int b = 20;

		System.out.println(a == b);
		System.out.println(a != b);
		System.out.println(a > b);
		System.out.println(a < b);
		System.out.println(a >= b);
		System.out.println(a <= b);

		// objects support == and != operators
		System.out.println(new Data1() == new Data1());
		System.out.println(new Data1() != new Data1());

	}

}

class Data1 {
}

Output:

Relational Operators Java Example

Ternary Operator in Java

A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.

It's syntax is:

condition ? expression1 : expression2;

Here, condition is evaluated and

  • if condition is trueexpression1 is executed.
  • And, if condition is falseexpression2 is executed.

The ternary operator takes 3 operands (conditionexpression1, and expression2). Hence, the name ternary operator.


Example: Java Ternary Operator

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    // take input from users
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your marks: ");
    double marks = input.nextDouble();

    // ternary operator checks if
    // marks is greater than 40
    String result = (marks > 40) ? "pass" : "fail";

    System.out.println("You " + result + " the exam.");
    input.close();
  }
}

Output 1

Enter your marks: 
75
You pass the exam.

Suppose the user enters 75. Then, the condition marks > 40 evaluates to true. Hence, the first expression pass is assigned to result.

Output 2

Enter your marks: 
24
You fail the exam.

Now, suppose the user enters 24. Then, the condition marks > 40 evaluates to false. Hence, the second expression fail is assigned to result.


When to use the Ternary Operator?

In Java, the ternary operator can be used to replace certain types of if...else statements. For example,

You can replace this code

class Main {
  public static void main(String[] args) {
    
    // create a variable 
    int number = 24;

    if(number > 0) {
      System.out.println("Positive Number");
    }
    else {
      System.out.println("Negative Number");
    }
  }
}

with

class Main {
  public static void main(String[] args) {
    
    // create a variable 
    int number = 24;

    String result = (number > 0) ? "Positive Number" : "Negative Number";
    System.out.println(result);
  }
}

Output

Positive Number
Bitwise operators in Java
  • Difficulty Level : Easy
  •  Last Updated : 20 Jun, 2020

Bitwise operators are used to perform manipulation of individual bits of a number. They can be used with any of the integral types (char, short, int, etc). They are used when performing update and query operations of Binary indexed tree.

  1. Bitwise OR (|) –
    This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
    For example,
    a = 5 = 0101 (In Binary)
    b = 7 = 0111 (In Binary)
    
    Bitwise OR Operation of 5 and 7
      0101
    | 0111
     ________
      0111  = 7 (In decimal) 
  2. Bitwise AND (&) –
    This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0.
    For example,
    a = 5 = 0101 (In Binary)
    b = 7 = 0111 (In Binary)
    
    Bitwise AND Operation of 5 and 7
      0101
    & 0111
     ________
      0101  = 5 (In decimal) 
  3. Bitwise XOR (^) –
    This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
    For example,
    a = 5 = 0101 (In Binary)
    b = 7 = 0111 (In Binary)
    
    Bitwise XOR Operation of 5 and 7
      0101
    ^ 0111
     ________
      0010  = 2 (In decimal) 
  4. Bitwise Complement (~) –
    This operator is unary operator, denoted by ‘~’. It returns the one’s compliment representation of the input value, i.e, with all bits inversed, means it makes every 0 to 1, and every 1 to 0.
    For example,

    a = 5 = 0101 (In Binary)
    
    Bitwise Compliment Operation of 5
    
    ~ 0101
     ________
      1010  = 10 (In decimal) 

    Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -6.

filter_none

edit

play_arrow

brightness_4

// Java program to illustrate
// bitwise operators
public class operators {
    public static void main(String[] args)
    {
        //Initial values
        int a = 5;
        int b = 7;
  
        // bitwise and
        // 0101 & 0111=0101 = 5
        System.out.println("a&b = " + (a & b));
  
        // bitwise or
        // 0101 | 0111=0111 = 7
        System.out.println("a|b = " + (a | b));
  
        // bitwise xor
        // 0101 ^ 0111=0010 = 2
        System.out.println("a^b = " + (a ^ b));
  
        // bitwise and
        // ~0101=1010
        // will give 2's complement of 1010 = -6
        System.out.println("~a = " + ~a);
  
        // can also be combined with
        // assignment operator to provide shorthand
        // assignment
        // a=a&b
        a &= b;
        System.out.println("a= " + a);
    }
}

Output :

a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5 

Shift Operators: These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. General format:

 number shift_op number_of_places_to_shift;
  1. Signed Right shift operator (>>) –
    Shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of initial number. Similar effect as of dividing the number with some power of two.
    For example,
    Example 1:
    a = 10
    a>>1 = 5 
    
    Example 2:
    a = -10 
    a>>1 = -5
    We preserve the sign bit.
    
  2. Unsigned Right shift operator (>>>) –
    Shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0. (>>>) is unsigned-shift; it’ll insert 0. (>>) is signed, and will extend the sign bit.
    For example,
    Example 1:
    a = 10
    a>>>1 = 5
    
    Example 2:
    a = -10 
    a>>>1 = 2147483643
    DOES NOT preserve the sign bit. 
  3. Left shift operator (<<) –
    Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.
    For example,
    a = 5 = 0000 0101
    b = -10 = 1111 0110
    
    a << 1 = 0000 1010 = 10
    a << 2 = 0001 0100 = 20 
    
    b << 1 = 1110 1100 = -20
    b << 2 = 1101 1000 = -40 
  4. Unsigned Left shift operator (<<<) –
    Unlike unsigned Right Shift, there is no “<<<" operator in Java, because the logical (<<) and arithmetic left-shift (<<<) operations are identical.
filter_none

edit

play_arrow

brightness_4

// Java program to illustrate
// shift operators
public class operators {
    public static void main(String[] args)
    {
  
        int a = 5;
        int b = -10;
  
        // left shift operator
        // 0000 0101<<2 =0001 0100(20)
        // similar to 5*(2^2)
        System.out.println("a<<2 = " + (a << 2));
  
        // right shift operator
        // 0000 0101 >> 2 =0000 0001(1)
        // similar to 5/(2^2)
        System.out.println("b>>2 = " + (b >> 2));
  
        // unsigned right shift operator
        System.out.println("b>>>2 = " + (b >>> 2));
    }
}

Output :

a<<2 = 20
b>>2 = -3
b>>>2 = 1073741821

















Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.