# System.out.println(040|343);

• 06-26-2010, 10:17 AM
satheshshiva
System.out.println(040|343);
I was asked this in a Java Interview. I checked that
System.out.println(040|343); prints "345". But How? Whats the operation taking place ?
• 06-26-2010, 10:48 AM
JosAH
Quote:

Originally Posted by satheshshiva
I was asked this in a Java Interview. I checked that
System.out.println(040|343); prints "345". But How? Whats the operation taking place ?

Any integer starting with a zero (0) introduces an octal representation of the number so 040 == 32 in decimal. The vertical bar (|) is the bitwise or operator, so 032 | 343 in binary is: 100000 | 101011001 == 101111001 which is 375 in decimal. I don't know where they got 345 as an answer from ...

kind regards,

Jos
• 06-26-2010, 11:20 AM
cselic
Quote:

I checked that
System.out.println(040|343); prints "345"
With small program I get "375"
Code:

```public class Bitwise {         public static void main(String[] args) {                 System.out.println(040 | 343);         } }```
when you have octal number you can convert it to binary number by number. Every octal number consist of 3 binary numbers ( 2 ^ 3 = 8 ).

So how convert 40 to binary?
4 = 100 ( 1 * 2 ^ 2 + 0 * 2 ^ 1 + 0 * 2 ^ 0 )
0 = 000 ( 0 * 2 ^ 2 + 0 * 2 ^1 + 0 * 2 ^ 0)
Then you have 40 in binary 100000.

in decimal:
100000 = (1 * 2 ^ 5 + 0 * 2 ^ 4 + 0 * 2 ^ 3 + 0 * 2 ^ 2 + 0 * 2 ^ 1 + 0 * 2 ^ 0 ) = 32

and finally you have (32 | 343).
• 06-26-2010, 01:30 PM
satheshshiva
Thanks to both of you above.

Sorry for the typo.. its "375"
• 06-26-2010, 06:49 PM
Lil_Aziz1
When one a person ever use bitwise comparison in practical applications?

EDIT: I'd be a bit chagrined if my imminent boss asked me for the result from
Code:

`System.out.println(040|343)`
at an interview lol.
• 06-26-2010, 10:26 PM
cselic
Quote:

When one a person ever use bitwise comparison in practical applications?
It's very good to use bitwise operators in many occasions.

For example if you have device with 100.000 characteristic, it's cheaper to work with bits.
100.000 characterictics (on/off) implemented with bits is like working with 100.000 / 8 = 12.500.
Program is faster, but is difficult to implement.

Bitwise operators is a connection with low level languages (asembly languague).