Here’s a Java program to check if a given number is a power of two:
import java.util.Scanner;
public class PowerOfTwo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
boolean isPowerOfTwo = checkPowerOfTwo(num);
if (isPowerOfTwo) {
System.out.println(num + " is a power of two.");
} else {
System.out.println(num + " is not a power of two.");
}
}
public static boolean checkPowerOfTwo(int num) {
if (num <= 0) {
return false;
}
return (num & (num - 1)) == 0;
}
}
In this program, we first take user input for a number. We then call the `checkPowerOfTwo()` method to check if the number is a power of two.
A power of two is a number that can be expressed as 2^n for some integer n. For example, 2, 4, 8, 16 are powers of two.
The `checkPowerOfTwo()` method takes an integer `num` as a parameter and returns a boolean indicating whether the number is a power of two or not. We first check if the number is less than or equal to 0, in which case it cannot be a power of two. We then use the bitwise AND operator to check if `num` and `num - 1` have no common bits set. If they have no common bits set, then `num` is a power of two.
At the end of the program, we print out whether the number is a power of two or not.