Behavior of Java Postincrementor [duplicate] - java

This question already has answers here:
post increment operator java
(3 answers)
Closed 9 years ago.
public static void main(String[] args) {
int a = 1;
int b = a++;
System.out.println(b);
}
Why does the code above print 1? I was told that a++ means you would get the value of a. then increment it. But the code above never incremented a and just printed 1. Could someone please explain what is going on here?

It works as expected; Here is the code explained:
public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// b is assigned the value of a (1) and THEN a is incremented.
// b is now 1 and a is 2.
int b = a++;
System.out.println(b);
// if you had printed a here it would have been 2
}
This is the same code but with pre-increment of a:
public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// a is incremented (now 2) and THEN b is assigned the value of a (2)
// b is now 2 and so is a.
int b = ++a;
System.out.println(b);
// if you had printed a here it would have been 2 so is b.
}

int b = a++ is equivalent to int b = a; a += 1. When you print b, a==2 && b==1

a++ is like saying a-then increment a by 1. So after you say b = a++, b = 1 and a = 2.
If you were to preincrement b = ++a, you would get b = 2 Preincrement increases before it assigns value.
Conclustion
a++ assign value before incrementing
++a increments, then assigns value.

The reason is is as follow.
If it is i++, then equalent code is like this.
result = i;
i = i+1;
return result
If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i
So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)

Post Increment Meaning = First complete assignment then Increment.
Pre Increment Meaning = First Increment then assign .
ex:
int a=0,b;
b=a++; // ie. Step1(First complete assignment): b=0, then a++ ie a=a+1; so a=1 now.
System.out.println(b); // prints 0
System.out.println(a); // prints 1
if
int a=0,b;
b=++a; // ie. Step1(First Increment ): a++ ie a=a+1; so a=1 now, b=a , ie b=1.
System.out.println(b); // prints 1
System.out.println(a); // prints 1

Related

Java increment operator strange behavior [duplicate]

Is there a difference between ++x and x++ in java?
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
yes
++x increments the value of x and then returns x
x++ returns the value of x and then increments
example:
x=0;
a=++x;
b=x++;
after the code is run both a and b will be 1 but x will be 2.
These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.
int x = 0;
int y = 0;
y = ++x; // result: x=1, y=1
int x = 0;
int y = 0;
y = x++; // result: x=1, y=0
Yes,
int x=5;
System.out.println(++x);
will print 6 and
int x=5;
System.out.println(x++);
will print 5.
In Java there is a difference between x++ and ++x
++x is a prefix form:
It increments the variables expression then uses the new value in the expression.
For example if used in code:
int x = 3;
int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4
System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'
x++ is a postfix form:
The variables value is first used in the expression and then it is incremented after the operation.
For example if used in code:
int x = 3;
int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4
System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4'
Hope this is clear. Running and playing with the above code should help your understanding.
I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)
To be accurate (and probably, a bit pedantic),
int y = 2;
y = y++;
is compiled into:
int y = 2;
int tmp = y;
y = y+1;
y = tmp;
If you javac this Y.java class:
public class Y {
public static void main(String []args) {
int y = 2;
y = y++;
}
}
and javap -c Y, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):
public class Y extends java.lang.Object{
public Y();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_2 // Push int constant `2` onto the operand stack.
1: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
2: iload_1 // Push the value (`2`) of the local variable at index `1` (`y`)
// onto the operand stack
3: iinc 1, 1 // Sign-extend the constant value `1` to an int, and increment
// by this amount the local variable at index `1` (`y`)
6: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
7: return
}
Thus, we finally have:
0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp
When considering what the computer actually does...
++x: load x from memory, increment, use, store back to memory.
x++: load x from memory, use, increment, store back to memory.
Consider:
a = 0
x = f(a++)
y = f(++a)
where function f(p) returns p + 1
x will be 1 (or 2)
y will be 2 (or 1)
And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.
Generally, just use x = x + 1. It's way simpler.
Yes.
public class IncrementTest extends TestCase {
public void testPreIncrement() throws Exception {
int i = 0;
int j = i++;
assertEquals(0, j);
assertEquals(1, i);
}
public void testPostIncrement() throws Exception {
int i = 0;
int j = ++i;
assertEquals(1, j);
assertEquals(1, i);
}
}
Yes, using ++X, X+1 will be used in the expression. Using X++, X will be used in the expression and X will only be increased after the expression has been evaluated.
So if X = 9, using ++X, the value 10 will be used, else, the value 9.
If it's like many other languages you may want to have a simple try:
i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check
If the above doesn't happen like that, they may be equivalent
Yes, the value returned is the value after and before the incrementation, respectively.
class Foo {
public static void main(String args[]) {
int x = 1;
int a = x++;
System.out.println("a is now " + a);
x = 1;
a = ++x;
System.out.println("a is now " + a);
}
}
$ java Foo
a is now 1
a is now 2
OK, I landed here because I recently came across the same issue when checking the classic stack implementation. Just a reminder that this is used in the array based implementation of Stack, which is a bit faster than the linked-list one.
Code below, check the push and pop func.
public class FixedCapacityStackOfStrings
{
private String[] s;
private int N=0;
public FixedCapacityStackOfStrings(int capacity)
{ s = new String[capacity];}
public boolean isEmpty()
{ return N == 0;}
public void push(String item)
{ s[N++] = item; }
public String pop()
{
String item = s[--N];
s[N] = null;
return item;
}
}
Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression.
Take an example:
public static void main(String args[])
{
int i , j , k = 0;
j = k++; // Value of j is 0
i = ++j; // Value of i becomes 1
k = i++; // Value of k is 1
System.out.println(k);
}
The Question is already answered, but allow me to add from my side too.
First of all ++ means increment by one and -- means decrement by one.
Now x++ means Increment x after this line and ++x means Increment x before this line.
Check this Example
class Example {
public static void main (String args[]) {
int x=17,a,b;
a=x++;
b=++x;
System.out.println(“x=” + x +“a=” +a);
System.out.println(“x=” + x + “b=” +b);
a = x--;
b = --x;
System.out.println(“x=” + x + “a=” +a);
System.out.println(“x=” + x + “b=” +b);
}
}
It will give the following output:
x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17
public static void main(String[] args) {
int a = 1;
int b = a++; // this means b = whatever value a has but, I want to
increment a by 1
System.out.println("a is --> " + a); //2
System.out.println("b is --> " + b); //1
a = 1;
b = ++a; // this means b = a+1
System.out.println("now a is still --> " + a); //2
System.out.println("but b is --> " + b); //2
}
With i++, it's called postincrement, and the value is used in whatever context then incremented; ++i is preincrement increments the value first and then uses it in context.
If you're not using it in any context, it doesn't matter what you use, but postincrement is used by convention.
There is a huge difference.
As most of the answers have already pointed out the theory, I would like to point out an easy example:
int x = 1;
//would print 1 as first statement will x = x and then x will increase
int x = x++;
System.out.println(x);
Now let's see ++x:
int x = 1;
//would print 2 as first statement will increment x and then x will be stored
int x = ++x;
System.out.println(x);
Try to look at it this way:
from left to right do what you encounter first. If you see the x first, then that value is going to be used in evaluating the currently processing expression, if you see the increment (++) first, then add one to the current value of the variable and continue with the evaluation of the expression. Simple

The pre-decrement operator is not loading the decremented value in Java

I have the following simple code:
public static void main(String[] args) {
int i = 1, j = 10;
do {
if (i++ > --j) continue;
} while (i < 5);
System.out.println("i=" + i + " j=" + j);
}
The output is: i=5 j=6
This result shows that the values of "i" and "j" that the if statement have used in the first "do" iteration were the original values (i.e. 1 for i, and 10 for j). I can understand that for the i++, but I do not understand why --j in the if statement was 10 instead of 9 in the first iteration. What I thought is that --j should be 9 instead of 10 because it is a pre-decrement.
Can someone clarify?
Thanks!
Thanks all for clarifying; I got the point as the following:
First "do" iteration: i=1, j=9, After the if is executed, i=2 and j=9
Second iteration: i=2, j=8, After the if, i=3 and j=8
Third iteration: i=3, j=7, After the if, i=4 and j=7
Fourth iteration: i=4, j=6, After the if, i=5 and j=6
At this point i is no longer < 5 and exits the loop with i=5 and j=6.
It is quite simple to me:
The loop runs 4 times before i<5==false
i: 1+4=5
j: 10-4=6
Clear enough?
I ran this code on my computer and your code works correctly. Try to write:
if (--j==9) {
System.out.println("yup");
}
yup will be printed.
My initial impression was that the sequence would be -
(1,10) (2,9),(3,8),(4,7) and finally (5,6).
However a quick check indicates that is not the case.
Given -
public static void main(String[] args) {
int a = 1, c = 0;
int b = 10, d = 0;
do {
c = (a++);
d= (--b);
System.out.println("c :"+ (c) +", d:"+ (d) +", a:"+(a) + ", b:"+(b));
if ( c > d) {
System.out.println("(c > d) !!");
continue;
}
}while( c<5);
System.out.println("c :"+ (c) +", d:"+ (d));
}
The output is -
c :1, d:9, a:2, b:9
c :2, d:8, a:3, b:8
c :3, d:7, a:4, b:7
c :4, d:6, a:5, b:6
c :5, d:5, a:6, b:5
c :5, d:5
At no point is the "continue" called since the criteria (LHS > RHS) is never satisfied.
In general, its not a good idea to mix the two conventions precisely due to the confusion it creates.
As an added precaution, its better to have the increment operation as an independent step (without any assignment) for the same reason (unless the code is a performance intensive one).
int i = 1;
i++;
System.out.println("i :"+i);

Return the larger value if it is in the range 10..20

I am trying to work out this problem on codingbat and the problem is Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range. The solution has been given below but I can not understand the first part as the comment says larger value is a, but the code says( b > a ) and what does this mean: int temp = a; a = b; b = temp;. Can anyone please explain it...
public int max1020(int a, int b) {
// First make it so the bigger value is in a
if (b > a) {
int temp = a;
a = b;
b = temp;
}
// Knowing a is bigger, just check a first
if (a >= 10 && a <= 20) return a;
if (b >= 10 && b <= 20) return b;
return 0;
}
The first if statement makes sure that a is not smaller than b (if a is smaller than b, it swaps a and b - that's what the 3 assignment statements involving the temp variable do).
The second if statement returns a if it's in the required range (and at this point we know a >= b).
If not, the third if statement returns b if it's in the required range.
Otherwise 0 is returned (when both a and b are not in the required range).
It says that if the value of b is greater than that of a, switch the 2 values. So, for example, if a = 10 and b = 15:
if (b > a) { is true so will get in the if
int temp = a; temp will take the value 10
a = b; a will take the value 15
b = temp; b will take the value 10
So, the values of a and b will be switched, if the value of b is greater than that of a. Therefore, a will have the bigger value.

Java sum puzzle, stuck with out of bounds error that I can't find

In trying to find to work out a programming puzzle in java, I'm getting some errors that I don't understand even though I've tried editing the code / narrowing the code down to try figure it out.
My entire program is below and can be run as soon as you paste it (main method is written with the current test parameters that I want in the method that I made already). The description of the puzzle is written in the right after the start of the class, but in short the puzzle is to make a method that takes 3 parameters a, b, and c, and the method returns the sum of these 3 unless any of them is the integer 13 - in this case this 13 and the parameters to the right are omitted from the sum.
When I try run my current test it says there is an ArrayIndexOutOfBoundsException: 3 error under the line if(x == 0 && x == 13) which is found under the for loop for(int x=0; x<params.length; x++).
I don't understand how this error is coming about - I'm adding making x the counter for the parameter inside the array, and adding 1 and 2 to it to make the elements on the right 0. I understand it could go out of bounds here but it's under an if statement that checks if the x is 13 and 0, meaning it has to only perform this when I'm checking the first param (at index 0). But for some reason it is still out of bounds, as if the it is doing the check at x>=1 where the +1 and +2 after will send it out of bounds.
Can any one see what's causing the error?
Note: My idea solving this was store the params in the array, check if they are 13, if it is make that number 0 and ones stored to its right 0, then return the sum of the array after.
public class Logic2Q3 {
/*
* Given 3 int values, a b c, return their sum. However, if one of the values is 13
* then it does not count towards the sum and values to its right do not count.
* So for example, if b is 13, then both b and c do not count.
*
* e.g.:
* luckySum(1, 2, 3) -> 6
* luckySum(1, 2, 13) -> 3
* luckySum(1, 13, 3) -> 1
*
*/
public int luckySum(int a, int b, int c) {
int[] params = new int[3]; // array to store params
int sum = 0; // for storing the final sum
// store params for checking here
params[0] = a;
params[1] = b;
params[2] = c;
// check the array of parameters and alter them according to specs
for(int x=0; x<params.length; x++) {
// in the case 13 is found
if(params[x] == 13) {
// case that it's the first element (a) and is also the 13
if(x == 0 && x == 13)
// make both elements on the right 0 to not add to the sum
params[x] = 0;
params[x+1] = 0;
params[x+2] = 0;
// case that it's the second element (b)
if(x == 1 && x == 13)
// make only the element on the right 0
params[x] = 0;
params[x+1] = 0;
}
}
// after the array is altered to omit a, b, and c being 13 or to the right of 13, sum everything
for(int x=0; x<params.length; x++) {
// += must be used on initialised instance variable only
sum += params[x];
}
return sum;
}
public static void main(String[] args) {
Logic2Q3 test = new Logic2Q3();
System.out.println(test.luckySum(3,13,7));
}
}
the second time your for-loop runs, if param[x] equals 13 or any time later than 0, the line params[x+2] = 0 is always executed! please read a coding guideline for java and never ever use an if-statement without setting the correct scope with {//if statement stuff} !!!
After reading the guidelines you should be able to solve your problem!
EDIT: in addition those if statements can never be true! x cannot equal 0 and 13 at the same time
Whilst your code potentionally creates a IndexOutOfBoundExeption because you do access the values at either x+1 or x+2 there are also other mistakes. There are missing paranthesis and the if condition will never be true, as you check if one value will be equal to two values (unlogical right?).
All in all my best guess is, that you are making this complete luckySum "puzzle" a bit to complicate, because all you actually need is one loop and a variable sum. Once you found a value you can simply break out of the loop and return the sum. Here´s a more simplified version of what you are doing.
public static void main(String[] args) {
System.out.println(luckySum(1, 2, 3));
System.out.println(luckySum(1, 2, 13));
System.out.println(luckySum(1, 13, 3));
}
/**
* Given 3 int values, a b c, return their sum. However, if one of the values is 13
* then it does not count towards the sum and values to its right do not count.
* So for example, if b is 13, then both b and c do not count.
*
* e.g.:
* luckySum(1, 2, 3) -> 6
* luckySum(1, 2, 13) -> 3
* luckySum(1, 13, 3) -> 1
*
*/
public static int luckySum(int... values) {
// Using varargs for dynamic amound of values
// Sum variable
int sum = 0;
// loop over all values
for(int x=0; x<values.length; x++) {
// in the case 13 is found break out of the loop
if(values[x] == 13) {
break;
// As a second option you could just return sum here
// return sum;
}
// add value to the sum
sum += values[x];
}
return sum;
}
O/P
6
3
1

Java Char increment [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 8 years ago.
I was executing the following code
class First
{
public static void main(String arg[])
{
char x= 'A';
x = x++;
System.out.println(x);
}
}
Here the output is A.
My question is why didn't x get incremented before printing.
You're using the post-increment operator incorrectly - you don't need to use assignment as well. And in this case it undermines what you're trying to do.
For context, remember that the post-increment operator increases the value, and returns the old value. That is, x++ is roughly equivalent to:
int x_initial = x;
x = x + 1;
return x_initial;
Hopefully now you can see why your code is failing to change x. If you expand it, it looks like:
char x= 'A';
char y;
{
y = x;
x = x + 1;
}
x = y;
System.out.println(x);
and the net effect of the assignment, is to set x back to what it was originally.
To fix - you can simply call x++. Or, if you want to make it clear there's some sort of assignment happening, x += 1 or even just x = x + 1 would do the same thing.
class First
{
public static void main(String arg[])
{
char x= 'A';
x = x++; // it is post increment as ++ sign is after x
System.out.println(x);
}
}
Post Increment(x++) : First execute the statement then increase the value by one.
Pre Increment (++x) : First increase the value by one then execute the statement.

Categories

Resources