What function does the "^" operator serve in Java?

When I try this:

```
int a = 5^n;
```

...it gives me:

for n = 5, returns 0

for n = 4, returns 1

for n = 6, returns 3

...so I guess it doesn't indicate exponentiation. But what is it then?

It is the `XOR`

bitwise operator.

It's bitwise XOR, Java does not have an exponentiation operator, you would have to use `Math.pow()`

instead.

As others have said, it's bitwise XOR. If you want to raise a number to a given power, use `Math.pow(a , b)`

, where `a`

is a number and `b`

is the power.

As already stated by the other answer(s), it's the "exclusive or" (XOR) operator. For more information on bit-operators in Java, see: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html

AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.

The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.

To use your example:

- The binary representation of 5 is 0101.
- The binary representation of 4 is 0100.

A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

With 4 and 5, the only difference is in the last place; so

0101 ^ 0100 = 0001 (5 ^ 4 = 1) .

As many people have already pointed out, it's the XOR operator. Many people have also already pointed out that if you want exponentiation then you need to use Math.pow.

But I think it's also useful to note that `^`

is just one of a family of operators that are collectively known as bitwise operators:

```
Operator Name Example Result Description
a & b and 3 & 5 1 1 if both bits are 1.
a | b or 3 | 5 7 1 if either bit is 1.
a ^ b xor 3 ^ 5 6 1 if both bits are different.
~a not ~3 -4 Inverts the bits.
n << p left shift 3 << 2 12 Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p right shift 5 >> 2 1 Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p right shift -4 >>> 28 15 Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.
```

From here.

These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.

It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).

`^`

in Java is the exclusive-or ("xor") operator.

Let's take `5^6`

as example:

```
(decimal) (binary)
5 = 101
6 = 110
------------------ xor
3 = 011
```

This the truth table for bitwise (JLS 15.22.1) and logical (JLS 15.22.2) xor:

```
^ | 0 1 ^ | F T
--+----- --+-----
0 | 0 1 F | F T
1 | 1 0 T | T F
```

More simply, you can also think of xor as "this *or* that, but *not both*!".

As for integer exponentiation, unfortunately Java does not have such an operator. You can use `double Math.pow(double, double)`

(casting the result to `int`

if necessary).

You can also use the traditional bit-shifting trick to compute some powers of two. That is, `(1L << k)`

is two to the *k*-th power for `k=0..63`

.

: this answer was merged from another question where the intention was to use exponentiation to convert a stringMerge note`"8675309"`

to`int`

without using`Integer.parseInt`

as a programming exercise (`^`

denotes exponentiation from now on). The OP's intention was to compute`8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0 = 8675309`

; the next part of this answer addresses that exponentiation is not necessary for this task.

Addressing your *specific* need, you actually don't need to compute various powers of 10. You can use what is called the Horner's scheme, which is not only simple but also efficient.

Since you're doing this as a personal exercise, I won't give the Java code, but here's the main idea:

```
8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
= (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9
```

It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.

In table form:

```
step result digit result*10+digit
1 init=0 8 8
2 8 6 86
3 86 7 867
4 867 5 8675
5 8675 3 86753
6 86753 0 867530
7 867530 9 8675309=final
```

use Math.pow instead:

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#pow%28double,%20double%29

That is because you are using the xor operator.

In java, or just about any other language, ^ is bitwise xor, so of course,

10 ^ 1 = 11. more info about bitwise operators

It's interesting how Java and C# don't have a power operator.

In other languages like Python you can do 10**2=100, try it.

^ is binary (as in base-2) xor, not exponentiation (which is not available as a Java operator). For exponentiation, see java.lang.Math.pow().

Meanwhile, in Groovy:

```
def x = 89
def y = 92
print "x ^ y = ${x ^ y}\n"
print "x ** y = ${x ** y}\n"
print "Math.pow(x,y) = ${Math.pow(x,y)}\n"
```

Running the above using `groovyShell`

for example gives:

```
x ^ y = 5
x ** y = 220739783027264538664507899981652263884030030210130685655986852988723754592147271358302675499604456885393671329478799379899078505327879299542726514661188445083298962617396644428321
Math.pow(x,y) = 2.2073978302726454E179
```

It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.

ex :-

To use your example:

The binary representation of 5 is 0101. The binary representation of 4 is 0100.

A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

0101 ^ 0100 = 0001 (5 ^ 4 = 1) .

Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like

- XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
- If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
- Swapping values without using temporary variable
- Finding missing number in the range 1 to n
- Basic validation of data sent over the network.

Lot many such tricks can be done using bit wise operators, interesting topic to explore.

Similar Questions

What does syso-statements stand for in Java?

I am looking through some example code of overloading new/delete and there I have the following // manage memory for instances void * roun_class:: operator new(std::size_t s) { void * result(::operato

When I list all boolean operators over one variable, I find one operator which does nothing: A f(A) 0 0 1 1 Does this operator f have an official name? Bye

What distribution does Java's Random follow?

What is Linq? I know it's for databases, but what does it do?

I'm interested to know what this snippet of RSH code does, and whether Bash has something similar: if [ -z $ALPHA \ -z $BRAVO \ -z $CHARLIE \ -z $DELTA ]; then var=$ZULU fi

I've seen := used in several code samples, but never with an accompanying explanation. It's not exactly possible to google its use without knowing the proper name for it. What does it do?

struct reserved_memory { void *safety; size_t safety_size; reserved_memory(size_t size) : safety_size(size) { init(); } bool use() { if (safety) { ::operator(safety); safety=0; return true; } else ret

This question already has an answer here: What is “rvalue reference for *this”? 3 answers A few questions on SO use a particular syntax for declaring default assignment operators. Rule-of-Three

I saw this $(a[rel~='single']) somewhere. What is the operator ~= in jquery? Does anyone know where the documentation for that is? Thanks in advance.

Possible Duplicate: Reference - What does this symbol mean in PHP? What does the '<>' mean? if ($class->stuff <> 'specific') Just working on a little project and came across a strang

Given the code : A = [1 2 3; 3 2 1] B = A.^2 The output : B = 1 4 9 9 4 1 But if I do this : B = A^2 The output is : Error using ^ Inputs must be a scalar and a square matrix. To compute elementwi

What UI Framework does Java Web Start use? And where can I begin development for it? I'm running Netbeans but I'm fairly confused as to how Java Web Start works

What does this !== mean in php and is there any doc's on it?

So I'm interested is there a way to overload operator in Java 8? Is there exist something like void operator(){ } in C++?

I'm trying to understand the power of functors. Okay, so they are pointers to functions, but what can they do that other classes that didn't implement operator() can't do? For instance : #include

I'm quite new to C# and trying to do a basic image processing software. I understand this snippet extracts A,R,G,B from an ARGB int value of a WriteableBitmap pixel current for(int i = 0; i < bit

Answers to a recent post (Any chances to imitate times() Ruby method in C#?) use the => operator in the usage examples. What does this operator do? I can't locate it in my C# book, and it is hard t

I use jstack to output the thread info. And there is a thread: VM Thread prio=10 tid=0x0878b400 nid=0x760a runnable What is this thread used to do? It takes 50% CPU usage and most of CPU time

I know that :: is the scope resolution operator. However what does it mean if something simply starts with a scope resolution operator. I know that something needs to be placed before the scope resolu

I came accross the sql query where the <=> operator is put. What does <=> operator mean? SELECT STR_ID, TEX_TEXT AS STR_DES_TEXT, IF( EXISTS( SELECT * FROM SEARCH_TREE AS SEARCH_TREE2 WHER

What does empty operator warning (translated from russian) mean in netbeans? for(int v = 1; v <= n; v++) { int parent = in.nextInt(); if(parent == 0); root = v; }

what does ignore function do in SML fun prntlst f l = if NULL l then () else (ignore(f (HD l)); prntlst f (TL(l))); what does ignore do here

Possible Duplicate: What does ||= mean? In this previous question, I asked about an effective way of associating Post, User, Comment and Vote models. The Vote model has a polarity column which store

I have a powershell script that runs some executable using call operator. Something like this: $executable = 'c:\dev\test.exe' & $executable | Out-Host Write-Host 'done' That test.exe in turn run

Does anyone know what extra classes parameter from Java2WSDL tool mean? Java2DSDL Reference I am looking to answer this question, but have no success.

What does this statement in C++ mean. I came across by reading about Typelists. I don't understand what the operator > stands for in typelist? I have never used this so far in C++ template stuff?

Given this example: module A module B def foo puts 'foo' end extend A::B end end What does this extend A::B do?

I read the JVM specification for the fpstrict modifier but still don't fully understand what it means. Can anyone enlighten me?

What does DbConnection.EnlistTransaction do? Thank you for your time.

Possible Duplicate: Java Synchronization I'm reading the book Beginning Android Games. It uses synchronized() a lot but I don't really understand what it does. I haven't used Java in a long time and

Often I hear people say, I know Java EE, or I've mastered Java EE. What does that mean: when can I say that, or what would I need to learn to know Java EE?

I am working through a C#/ASP.NET tutorial and I run into an operator i have never seen before. return RSVPs.Any(r => r.AttendeeName.Equals(userName, StringComparison.InvariantCultureIgnoreCase));

Java is a Strong Static Casting so does that mean there is no use for === I have looked at tons of documentation and have not seen Identical Comparison Operator.

What does the bash operator <<< mean, as inside the following code block? And how come does $IFS remain to be a space, not a period? LINE=7.6.5.4 IFS=. read -a ARRAY <<< $LINE ec

What does the &= operator do in C#? For example: bool approved; // Approved is a property of cra, also bool approved &= cra.Approved; Thanks a lot!

I read the following code from c.learncodethehardway.org/book/ex28.html echo Running unit tests: for i in tests/*_tests do if test -f $i then if $VALGRIND ./$i 2>> tests/tests.log then echo $i

What does this function do? _() Can you link me to the relevant documentation, as searching for _ is nigh on impossible?

I see this in the Django source code: description = _(Comma-separated integers) description = _(Date (without time)) What does it do? I try it in Python 3.1.3 and it fails: >>> foo = _(

What does aspectj-weaver.jar do? What are its common uses?

This question already has an answer here: Javascript || operator 5 answers I'm fairly new to JavaScript. What does || do?

I'm reviewing the tutorial Advanced Auto-Dependency Generation and found a script with this: %.P : %.c ....; [ -s $@ ] || rm -f $@ What does that part of the target do? I know I've seen this synta

I'm reading A Gentle Introduction to Haskell (which is not so gentle) and it repeatedly uses the : operator without directly explaining what it does. So, what exactly does it do?

I was playing around with the Datetime.ParseExact method, and it wants an iformatprovider.. It works inputting null, but what exactly does it do? Thanks :)

Consider: >>> a = {'foo': {'bar': 3}} >>> b = {'foo': {'bar': 3}} >>> a == b True According to the python doc, you can indeed use the == operator on dictionaries. What is

Specifically, in the case of object reference equality, what does the == operator do? Does the comparison return true if the references evaluate to the same object address at the time of comparison? O

This question already has an answer here: What does the !~ method do with String in Ruby 2 answers When declaring syntax such as: a !~ b where a,b are variables, what does it mean?

Other than the standard +, -, *and / operators; but what does these mean (** , ^ , %, //) ? >>> 9+float(2) # addition 11.0 >>> 9-float(2) # subtraction 7.0 >>> 9*float(2) #

In Javascript, what does it mean when there is a logical operator in a variable declaration? example: var z = x || y; Thanks!

Possible Duplicate: what's the difference between ( | ) and ( || ) in javascript? I've seen this in a couple examples here but I never fully understood what it's supposed to do. Can anyone give me a