Increment/Decrement Confusion - java

What is happening when we decrement the code here:
temp[--countArray[getDigit(position, input[tempIndex], radix)]]
If temp is 1 in this case: are we decrementing first so that we are assigning to 0? How immediate is this decrement? It always seems to confuse me within array brackets.

Try unpacking the brackets on different levels of indentation:
temp[ // get this index in temp
-- // decrement by 1
countArray[ // get this index in countArray
getDigit(position, input[tempIndex], radix) // call getDigit()
]
]
In human-readable terms, it calls getDigit() to index into countArray, then decrements that value and uses it to index into temp.
The decrement operator --x is different from x-- because of what it returns. By the end of the operation, x always ends up as one less than it was, but --x returns the new value of x, while x-- returns the old value of x from before it was decremented. The same applies for ++x and x++.

Let me break this down some. Here's some code that's equivalent to above:
int digit = getDigit(position, input[tempIndex], radix);
countArray[digit]--;
int count = countArray[digit];
temp[count] // Do something with the value
Incidentally, this is a classic illustration of why you shouldn't sacrifice clarity to brevity.

Related

In Java,operator precedence, increment and decrement, why isn't the first println statement executed? [duplicate]

This question already has answers here:
How increment and decrement with if condition
(2 answers)
Closed 5 months ago.
class Example{
public static void main(String args[]){
int x=99;
if(x++==x){
System.out.println("x++==x : "+x); //Why this code line is not run?
}
if(++x==x ){
System.out.println("++x==x : "+x);
}
}
}
Why isn't the first println statement executed?
The operands of an expression are evaluated left to right.
In the expression x++ == x, first x++ is evaluated. It increments x by 1, but returns the original value of x. So x++ returns 99.
Then x is evaluated, which returns 100 (since it was incremented by x++).
Since 99 is not equal to 100, this condition evaluates to false.
If you change the expression to x==x++, you'll get true.
The differece between i++ and ++i is very simple.
i++ - means exactly first get the value and then increment it for the further usage
++i - means exactly first increment the value and use the incremented value
Following the shippet x++ == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand and use it in the expression
Increment x and thus x == 100
Get x = 100 as the right operand (note it is already incremented)
99 != 100
Following the shippet ++x == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand
Increment x and thus x == 100 and use it in the expression
Get x = 100 as the right operand (note it is already incremented)
100 == 100
You can see all these logic. E.g. not experienced developer cannot know these details. Therefore the best practice is to avoid such increments in the expression. Just do it before the expression in the single line. In this case the logic will be straight forward and you get much less problems.

Post Increment Infinite loop i += i++; [duplicate]

This question already has answers here:
Why does this expression i+=i++ differs from Java and C?
(8 answers)
Closed 6 years ago.
I am not understanding why this post increment equation does not increase. I would have thought that after the += operation the value would increment by 1 and then the second time around i would have a 1 value. But the output is an infinite loop of 0 zero. Is anyone able to explain why 'i' doesn't increase.
int i = 0;
for(; ; ) {
if ( i >= 10) break;
i += i++;
}
System.out.println(i);
Let's examine i += i++;
i++ means read the value for i, then increment i.
i += x means evaluate i, then evaluate x and add the 2 and put the result in i.
So, what happens is:
i gets evaluated, it is 0
i++ gets evaluated. it returns 0, and the value for i is set to 1
i += i++ is now i = 0 + 0.
i = 0
Try with ++i to get the result of the incrementation before reading its value.
While the answer from #njzk2 is correct, it is useful to point out why it is correct.
There are other possibilities - for example, why doesn't Java execute the postincrement operator after the assignment? (Answer: because that's not what the Java Language Designers chose)
The evaluation order for compound assignments (things like +=) is specified in the Java Language Specification section 15.26.2. I'll quote how it is defined for Java 8:
First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression
completes abruptly for the same reason; the right-hand operand is not
evaluated and no assignment occurs.
Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes
abruptly, then the assignment expression completes abruptly for the
same reason and no assignment occurs.
Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation
indicated by the compound assignment operator. If this operation
completes abruptly, then the assignment expression completes abruptly
for the same reason and no assignment occurs.
Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion
(ยง5.1.13) to the appropriate standard value set (not an
extended-exponent value set), and the result of the conversion is
stored into the variable.
The most important thing is that the value of the left hand expression is saved first, then the right hand is completely evaluated, and then the result of the compound operation is stored in the variable on the left hand side.
No surprise you are getting into infinity loop..
class Demo{
public static void main(String[] args){
int i = 0;
for( ; ; ) {
if (i >= 10)
break;
i = i+i++;
System.out.println(i);
}
}
}
assume the above code, I have just replaced your line with increment with what compiler will substitute.
Now, initially i=0;
So
i = i+i++
results in i = 0 + 0 // and now i is 1
but at the end you again make i equal to 0!
Hence infinity...

When is the x++ evaluated?

In
int x = 5;
int answer = x++ * 6 + 4 * 10 / 2;
the output is 50, and but why the ++ operator doesn't evaluate the expression to 51?
The ++ is on the x not the result.
why the ++ operator doesn't evaluate the expression to 51?
Can you explain how or why that would work? If you wanted that just do
int answer = x * 6 + 4 * 10 / 2 + 1;
The assignment is using the postfix operator which increments after the statement is executed.
The JLS mentions this:
The value of the postfix increment expression is the value of the
variable before the new value is stored.
For more details see the full specification entry.
Postfix operator is evaluates after execution of statement.
According to java
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.
The defined effect of the ++ postfix operator is that the variable x gets incremented, as if you wrote x = x+1, but the value of the expression x++is the value before the increment. If you want to have th esame effect regarding how xchanges, but use the after avlue in the surrounding expression, you need to use ++x. And if you actually didn't want to increment the contents of x at all, use (x+1).
(It is however not defined, I think, when the assignment of the incremented value to x takes place - it might even be afer anwser obtains its value; on the other hand, usually x++ is almost atomic.)

Why do people write --i? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Incrementing in C++ - When to use x++ or ++x?
I've seen things like i++ commonly used in, say, for loops. But when people use -- instead of ++, for some reason some tend to write --i as opposed to i--.
Last time I checked, they both work (at least in JavaScript). Can someone tell me if this is so in other C-family languages, and if it is, why do some people prefer --i to i--?
++i is faster than i++. Why? See the simple explication.
i++
i++ will increment the value of i, but return the pre-incremented value.
temp = i
i is incremented
temp is returned
Example:
i = 1;
j = i++;
(i is 2, j is 1)
++i
++i will increment the value of i, and then return the incremented value.
Example:
i = 1;
j = ++i;
(i is 2, j is 2)
This is simillar for --i and i--.
I don't believe the preference for prefix (++i) vs. postfix (i++) varies depending on whether it's an increment or a decrement.
As for why, I prefer prefix where possible because my native language is English, which has mostly a verb-before-object structure ("eat dinner", "drive car"), so "increment i" or "decrement i" is more natural for me than "i decrement". Of course, I'll happily use postfix if I'm using the result and I need the value prior to the increment in an expression (rather than the incremented value).
Historically the increment/decrement operator were motivated by stack management. When you push an element on the stack:
*(stackptr++) = value
when you pop:
value = *(--stackptr)
(these were converted to single ASM instructions)
So one gets used to increment-after and decrement-before.
You can see another idiomatic example in filling in direct and reverse order:
for (p=begin;p!=end;)
*(p++) = 42;
for (p=end;p!=begin;)
*(--p) = 42;
It's pretty much a preference thing, that only comes into play if you're doing the pre- or post-increment on types that are more complicated than primitives.
Pre-increment ("++i") returns the value of i after it has been incremented, and post-increment ("i++") returns the value before increment. So, if i was of a complicated type that had overloaded the pre-increment and post-increment operators, the pre-increment operator can just return the object, whereas the post-increment would have to return a copy of the object, which could well be less efficient if the object is substantial. And in most cases (for loop increments, etc.), the value is ignored anyways.
Like I said, most of the time, not a problem, and just a preference thing.
In C and C++,++ and -- operators have both prefix form: ++i and --i, and suffix form: i++ and i--. Former means evaluate-then-use and latter means use-then-evaluate. The difference is only relevant when either form is used as part of an expression. Otherwise it's a matter of preference or style (or lack thereof).
F.ex., in int i = 0; int n = ++i;, i is first incremented and then its value, now 1, is assigned to n. In n = i++ value of i, still 1, is assigned to n and is then incremented, with i == 2 now.
When used as a statement, that is: i++; ++i; both forms are equivalent.
The difference is pre-incrementing or post-incrementing (and likewise with decrementing).
Quoting the Wikipedia article on the topic that shows up as the second Google result for "c decrement":
int x;
int y;
// Increment operators
x = 1;
y = ++x; // x is now 2, y is also 2
y = x++; // x is now 3, y is 2
// Decrement operators
x = 3;
y = x--; // x is now 2, y is 3
y = --x; // x is now 1, y is also 1
So, it's not so much a matter of preference as a matter of difference of results.

Java: increment through Float.floatToIntBits?

I need to increment a float value atomically. I get its int value by calling Float.floatToIntBits on it. If I just do an i++ and convert it back to float, it does not give me the expected value. So how would I go about it?
(I'm trying to create an AtomicFloat through AtomicInteger, hence this question).
EDIT: here's what I did:
Float f = 1.25f;
int i = Float.floatToIntBits(f);
i++;
f = Float.intBitsToFloat(i);
I wanted 2.25, but got 1.2500001 instead.
The reason is that the bits you get from floatToIntBits represents
sign
exponent
mantissa
laid out like this:
Repr: Sign Exponent Mantissa
Bit: 31 30......23 22.....................0
Incrementing the integer storing these fields with 1 won't increment the float value it represents by 1.
I'm trying to create an AtomicFloat through AtomicInteger, hence this question
I did precisely this in an answer to this question:
Java: is there no AtomicFloat or AtomicDouble?
To add functionality to increment the float by one, you could copy the code of incrementAndGet from AtomicInteger (and change from int to float):
public final float incrementAndGet() {
for (;;) {
float current = get();
float next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
(Note that if you want to increment the float by the smallest possible value, you take the above code and change current + 1 to current +Math.ulp(current).)
The atomic part can be implemented atop compareAndSet for a wrapper class as shown in the link of aioobe. The increment operators of AtomicInteger are implemented like that.
The increment part is a completely different problem. Depending on what you mean by "increment a float", it either requires you to add one to the number, or increment it by one ULP. For the latter, in Java 6, the Math.nextUp method is what you are looking for. For decrement by one ULP, the Math.nextAfter method is useful.

Categories

Resources