Recently, I started to wonder what I hadn't felt so far, but I have a question with the following code.
import java.util. *;

public class Main {
public static void main (String [] args) throws Exception {
int i = 1;
int j = 2;
if (i == 1 || j == 3) {
System.out.println ("correct");
if (i == 2 | j == 2) {
System.out.println ("correct");

Both are true and the conditional expression passes. What is the difference between this pipe and two pipes?
I always used it without thinking about it, but I suddenly wondered.
Please tell an expert! !

  • Answer # 1


    What is the difference between one pipe and two pipes?

    ||isshort circuit evaluation(if the left side is true, the right side is not evaluated).|is evaluated both left and right.


    |operator performsbitwise ORwhen applied to an integer type.||has no usage.

  • Answer # 2

    The difference between logical OR and bitwise OR.
    Please read "Operator" in your textbook and reference book.
    There is no two ||.
    The || operator does not apply the operator |

  • Answer # 3

    It is as per answer from maisumakun, but I will explain with specific examples.

    Suppose that you want to write a condition of "null or equal to the empty string" "" for a string variable str. If you write this with a single vertical bar

    if (str == null | str.equals (""))

    It becomes. If str is null,str == nullis naturally true, but the latterstr.equals ("")is entered without any hesitation. The Then, NullPointerException occurs because we tried to invoke the method on null.

    On the other hand, with two bars,

    if (str == null || str.equals (""))

    Whenstr == nullbecomes true, the operation result ofstr == null || str.equals ("")is set to true. Sincestr.equals ("")is not judged (this is "short-circuit evaluation" by maisumakun), NullPointerException does not occur.