Explain how the bitwise OR operator (|) works and provide an example.

Quick Overview

Explain how the bitwise OR operator combines two integers bit by bit and work through an example in binary. Tests binary arithmetic, setting bits and combining flags with masks, and the difference between bitwise OR and short-circuit logical OR.

Explain how the bitwise OR operator (|) works and provide an example.

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: easy

Interview Round: Other

Explain how the bitwise OR operator (`|`) works and provide an example. OR is one of the basic tools for working with flags and bit masks, and interviewers often follow up by asking how it differs from the logical OR operator. ```hint Line the bits up Write both numbers in binary with the same number of digits and look at one column at a time. ``` ### What a Strong Answer Covers - The rule OR applies at each bit position, in words or as a truth table. - A worked example showing both operands and the result in binary. - How bitwise `|` differs from logical `||` or Python's `or`. - Typical uses, such as setting a bit or combining flags. - How OR behaves on negative numbers in two's complement. ### Follow-up Questions - How do you set bit i of an integer x without changing any other bit? - How does `a | b` relate to `a + b` and `a & b`, and when is `a | b` equal to `a + b`? - In Java, why can `p == null | p.x <= 0` throw an exception when `p == null || p.x <= 0` does not?

Overview: Explain how the bitwise OR operator combines two integers bit by bit and work through an example in binary. Tests binary arithmetic, setting bits and combining flags with masks, and the difference between bitwise OR and short-circuit logical OR.

PracHub logo
General
Nov 25, 2026
easySoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Explain how the bitwise OR operator (|) works and provide an example.

OR is one of the basic tools for working with flags and bit masks, and interviewers often follow up by asking how it differs from the logical OR operator.

What a Strong Answer Covers Guidance

  • The rule OR applies at each bit position, in words or as a truth table.
  • A worked example showing both operands and the result in binary.
  • How bitwise | differs from logical || or Python's or .
  • Typical uses, such as setting a bit or combining flags.
  • How OR behaves on negative numbers in two's complement.

Follow-up Questions Guidance

  • How do you set bit i of an integer x without changing any other bit?
  • How does a | b relate to a + b and a & b , and when is a | b equal to a + b ?
  • In Java, why can p == null | p.x <= 0 throw an exception when p == null || p.x <= 0 does not?