
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Java Program to Count set bits in an integer
To count set bits in an integer, the Java code is as follows −
Example
import java.io.*; public class Demo{ static int set_bits_count(int num){ int count = 0; while (num > 0){ num &= (num - 1); count++; } return count; } public static void main(String args[]){ int num =11; System.out.println("The number of set bits in 11 is "); System.out.println(set_bits_count(num)); } }
Output
The number of set bits in 11 is 3
The above is an implementation of the Brian Kernighan algorithm. A class named Demo contains a static function named ‘set_bits_count’. This function checks if the number is 0, and if not, assigns a variable named ‘count’ to 0. It performs the ‘and’ operation on the number and the number decremented by 1.
Next, the ‘count’ value is decremented after this operation. In the end, the count value is returned. In the main function, the value whose set bits need to be found is defined. The function is called by passing the number as a parameter. Relevant messages are displayed on the console.
- Related Articles
- Python Program to Count set bits in an integer
- C/C++ Program to Count set bits in an integer?
- Golang Program to count the set bits in an integer.
- C/C++ Program to the Count set bits in an integer?
- Count set bits in an integer in C++
- C# program to count total set bits in a number
- Java Program to Count Number of Digits in an Integer
- Shift the bits of an integer to the right and set the count of shifts as an array with signed integer type in Numpy
- Shift the bits of an integer to the left and set the count of shifts as an array in Numpy
- Java program to count total bits in a number
- Sort an array according to count of set bits in C++
- Java program to reverse bits of a positive integer number
- Program to convert set of Integer to Array of Integer in Java
- Python Count set bits in a range?
- Python program to count total set bits in all number from 1 to n.

Advertisements