Java program to SET and CLEAR bits of the given number

Given/input an integer number, we have to SET and CLEAR its bits.
Submitted by Nidhi, on March 07, 2022

Problem Solution:

In this program, we will create an integer variable and then we will set and clear the bits of the number using bitwise operators.

Program/Source Code:

The source code to SET and CLEAR bits of the given number is given below. The given program is compiled and executed successfully.

// Java program to SET and CLEAR bits 
// of the given number

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    int num = 0x0;

    //set 0th bit
    num |= (1 << 0);

    //set 1st bit
    num |= (1 << 1);

    System.out.printf("Number after setting 0th and 1st bits: %d\n", num);

    //Clear 0th bit
    num &= ~(1 << 0);

    //Clear 1st bit
    num &= ~(1 << 1);

    System.out.printf("Number after clearing 0th and 1st bits: %d\n", num);
  }
}

Output:

Number after setting 0th and 1st bits: 3
Number after clearing 0th and 1st bits: 0

Explanation:

In the above program, we created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we created an integer variable initialized with 0x0. Then we set and cleared bits of the created variable using bitwise operators.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.