Totally agree with Rima! But, if you want a bit more control over the process, maybe you want to do a custom implementation for converting int to binary in Java. You could manually construct the binary string using bitwise operations. Here’s an example that uses a StringBuilder to optimize performance:
public static String toBinary(int num) {
StringBuilder binary = new StringBuilder();
while (num > 0) {
binary.append(num % 2);
num /= 2;
}
return binary.reverse().toString();
}
int number = 156;
System.out.println(toBinary(number)); // Output: "10011100"
This gives you more flexibility—let’s say you want to tweak the formatting or convert to another base in the future. Also, by using StringBuilder
, you avoid the inefficiency of string concatenation in loops, which can be costly performance-wise. It’s a solid choice when you need more customization!