3

My code is as following:

char ch = t.charAt(t.length() - 1);
        // result of XOR of two char is Integer.
        for(int i = 0; i < s.length(); i++){
            ch = ch^s.charAt(i);
            ch = ch^t.charAt(i);
        }

        return ch;

it throws error

Line 6: error: incompatible types: possible lossy conversion from int to char ch = ch^s.charAt(i);

Line 7: error: incompatible types: possible lossy conversion from int to char ch = ch^t.charAt(i);

2 errors

However, When I change

ch = ch^s.charAt(i);
ch = ch^t.charAt(i);

to

ch ^= s.charAt(i);
ch ^= t.charAt(i);

Then, my code can work.

Are '^=' and '* = ^' different?? Why I search this question about '^=', it says they are same??

What is the '^=' operator?

Zexi Gong
  • 169
  • 11

2 Answers2

8

From the functionality, they are the same: both perform an exclusive OR.

But the data types are different:

Community
  • 1
  • 1
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • Question: is this the same as doing `int x; int y;` and `x = x / y;` vs `x /= y;` You don't know if the value is gonna be a decimal-one (and get truncated) or an integer (*based on the inputted values*)? eg. `x = 3, y = 2`. – Joel Feb 06 '20 at 09:24
  • @Joel With integers, the result is always integer. If you want to avoid that, you have to multiply with 1.0 befre the division (or to add 0.0), or to cast. – glglgl Feb 06 '20 at 09:33
  • yes, it will be truncated as i mentioned in my question. But, i'm wondering if the concept is the same? it forces the type of LH-value? – Joel Feb 06 '20 at 09:34
  • @Joel Yes. I added a link to the relevant part of the Java Language Specification. – glglgl Feb 06 '20 at 09:54
0

You need to declare ch to be an int, or store the result of the bitwise xor ^= in an int field. Right now it's trying to store it in a char which is where the error is coming from.

Z4-tier
  • 7,287
  • 3
  • 26
  • 42