Home > OS >  Logical && and II operation with integer in Java
Logical && and II operation with integer in Java

Time:12-05

I have understood reading some problems here about the logical operation in Java. In Java, the whole operation is concentrating on boolean values, unlike C/C . In C ,

#include <iostream>
using namespace std;
int main()
{
    int i=1, j= 1, k=0,m;
    m=   i ||   j &&   k ;
    cout<<m;
    return 0;
}

I just wanted to learn how can I write this program in Java so that I can get the expected result.

CodePudding user response:

There’s no direct equivalent, because in C/C 0 is false, true otherwise whereas Java is strongly typed; in Java you can’t cast an int to a boolean.

In Java, you have to do the “casts” from int to boolean and back again with code:

m = (  i != 0) || (  j != 0) && (  k != 0) ? 1 : 0;

You can use the bitwise operators | and &:

m =   i |   j &   k; // valid java, result 2

but it’s semantically different.

CodePudding user response:

To conserve the short-circiuting behavior of the operators, you can split them into if statements:

int main()
{
  int i = 1, j = 1, k = 0, m;
    i;
  if (i == 0) {
      j;
    if (j != 0) {
        k;
      if (k == 0) {
        m = 0;
      } else {
        m = 1;
      }
    } else {
      m = 0
    }
  } else {
    m = 1;
  }
  System.out.print(m);
  return 0;
}

Another possibility would be to convert the integers into booleans (in C 0 coerces to false and every other value to true) in each step and eventually convert the final boolean back to 0 or 1. It is at least as unreadable as the nested if statements above:

int main() { 
  int i = 1, j = 1, k = 0, m;
  m = ((  i != 0) || (  j != 0) && (  k != 0)) ? 1 : 0;
  System.out.print(m);
  return 0;
}

But since all your numbers are constants, the simplest (and most readable) solution is to pre-compute the value:

int main() {
  System.out.println(1);
  return 0;
}
  • Related