eta99
eta99

Reputation: 15

java buf[--pos] = (byte)b Please, explain me what is in the square brackets

I'm reading sourcecode of PushbackInputStream to gain my understand about unread() method: http://javasourcecode.org/html/open-source/jdk/jdk-6u23/java/io/PushbackInputStream.java.html but on the line 194: buf[--pos] = (byte)b makes me don't understand what that said. Can anyone tell me the meaning of --pos in that line? Thanks in advance.

Ps: I even try to code this:

class Test2 {
public static void main(String[] args) {
    char[] c = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
            'i', 'n', 'a', 't', 'e', 'd' };
    char temp = 'o';
    c[--1] = tmp;
 }
}

but eclipse tells me: invalid argument operation

Upvotes: 0

Views: 345

Answers (5)

Bhushan Bhangale
Bhushan Bhangale

Reputation: 10987

Invalid argument operation error is because you are doing the decrement operation on a number instead of a variable.

Upvotes: 0

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

In the real code, pos is the current index into the buffer. To unread a byte, you need to decrement that index by one and store the specified byte at the new current index location in the buffer.

--pos has as side effect decrementing pos by one, and as result the new value of pos, so buf[--pos] = (byte)b; does the job.

Because of the side effect, the operand of -- has to be something that can be decremented by one. A constant cannot.

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25695

1 is a constant. You cannot decrement a constant - or change its value -

However you can do this: pos = 1;, buf[--pos] will do what you want it to do, because pos is a variable, and not a constant.

alternatively just use buf[0]

Upvotes: 0

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

-- is decrement operator, it makes sense only for a field (variable) not constant.

buf[--pos] = (byte)b; means set byte value b to buf[pos - 1] and pos would result in being decremented.

Upvotes: 0

NPE
NPE

Reputation: 500267

--pos means "decrease the value of pos by one, and use the resulting value".

This cannot be applied to a constant: --1 is not valid. However, you could just write 0 instead.

Upvotes: 1

Related Questions