What does & do in Java?

Im looking over a piece of Java code I didn't write and noticed that it included &amp in it in a few places. Its a piece of code from a infix to postfix notation converter.

If I put this piece of code in Eclipse it dosn't like these &amps and creates errors for them, the error being &amp cannot be resolved as a variable.

Heres the code

public static String[] infixToRPN(String[] inputTokens) { ArrayList<String> out = new ArrayList<String>(); Stack<String> stack = new Stack<String>(); // For all the input tokens [S1] read the next token [S2] for (String token : inputTokens) { if (isOperator(token)) { // If token is an operator (x) [S3] while (!stack.empty() &amp;&amp; isOperator(stack.peek())) { // [S4] if ((isAssociative(token, LEFT_ASSOC) &amp;&amp; cmpPrecedence( token, stack.peek()) <= 0) || (isAssociative(token, RIGHT_ASSOC) &amp;&amp; cmpPrecedence( token, stack.peek()) < 0)) { out.add(stack.pop()); // [S5] [S6] continue; } break; } // Push the new operator on the stack [S7] stack.push(token); } else if (token.equals("(")) { stack.push(token); // [S8] } else if (token.equals(")")) { // [S9] while (!stack.empty() &amp;&amp; !stack.peek().equals("(")) { out.add(stack.pop()); // [S10] } stack.pop(); // [S11] } else { out.add(token); // [S12] } } while (!stack.empty()) { out.add(stack.pop()); // [S13] } String[] output = new String[out.size()]; return out.toArray(output);
}
1

6 Answers

You are copy pasting code from a badly encoded website. This &amp; should be replaced with an ampersand (&).

In HTML, you cannot simply write &, because that is an escape character. So, in history, they invented the escape sequence for ampersands, which is: &amp;. That is what the website is showing you unfortunately.

So, to answer the question: &amp;&amp; should be: &&. That is the logical AND operator.

This looks like an encoding problem with the source file.

&amp; is the ampersand character from the ISO-8859-1 character set.

That looks like a mis-encoding of a Java file. I'm only aware of the && operator, which is logical AND.

1

&amp; is the HTML escaped version of &.

You should replace all &amp; with &

There is no &amp; in java, it's obviously a result of copy-paste from an HTML page. Replace &amp; with & to fix it.

In Java you have:

  • boolean AND --> &&
  • bitwise AND --> &

Your issue is that your code contains XML entities that haven't been successfully decoded, so &amp; means &, just as &gt; would mean >.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like