Question

I am allowed to do a bitwise & between a boolean variable and a String. There is no compilation error!

What would the result? How does it work. As per my understanding, it shall not allow the bitwise operation of this type. Is it a bug or bitwise feature thinks only interms of bit and dont care about type?

Was it helpful?

Solution

It is possible to bitwise & characters, but not Strings. Exapmle:

public class BitwiseTest {
  public static void main(String[] args) {
    System.out.println(Integer.toBinaryString(0));
    System.out.println(Integer.toBinaryString(1));
    System.out.println(Integer.toBinaryString(2));
    System.out.println(Integer.toBinaryString(1&2));
    System.out.println(Integer.toBinaryString(1&'2'));
  }
}

prints ...

0
1
10
11
110011

whereas this does not compile:

System.out.println(Integer.toBinaryString(1&"my String"));

compiler output:

$ javac BitwiseTest.java 
BitwiseTest.java:10: operator & cannot be applied to int,java.lang.String
System.out.println(Integer.toBinaryString(1&"my String"));
                                           ^
1 error
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top