Q:

Java program to SET and CLEAR bits of the given number

belongs to collection: Java Basic Programs

0

Java program to SET and CLEAR bits of the given number

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to implement infinite loop using whil... >>
<< Java program to demonstrate the example of the rig...