AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



programming-basics: Why it is printing same value even after four post increment?

class PostIncrement {
public static void main(String arg[]){
int a=10;
a=a++;
System.out.println(a);
a=a++;
a=a++;
a=a++;
System.out.println(a);
}
}

how the output is 10 after 3 increment operators?

programming x 169
basics x 171
Posted On : 2016-04-30 23:14:36.0
profile Saksham Kumar - anyforum.in Saksham Kumar
73433932708
up-rate
2
down-rate

Answers


a=a++ is evaluated as:

int oldValue = a;
a = a + 1;
a = oldValue; // 3rd Step

if you remove assignment operator it´ll print the new value incremented every time whenever you used increment operator.


class PostIncrement{
public static void main(String arg[]){
int a=10;
a=a++; //with assignment operator
System.out.println(a);
a++; //without assignment operator
a++;
System.out.println(a);
}
}


Output:
-----------------------------
10
12

Posted On : 2016-05-01 13:25:24
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188241268
Reply This Thread
up-rate
4
down-rate

"x = x++;" is almost certainly a mistake in any program.
http://stackoverflow.com/a/12033710/452708

Postfix operator means First use then increment.
Additionally, assigning value back to the variable "a" using "=" will never let the value increment using Postfix operator.

int a=10;
a=a++; // Variable a gets assigned Original Value 10 here before postfix can operate
System.out.println(a); //Prints 10
a=a++; // Variable a gets assigned Original Value 10 here before postfix can operate
a=a++; // Variable a gets assigned Original Value 10 here before postfix can operate
a=a++; // Variable a gets assigned Original Value 10 here before postfix can operate
System.out.println(a); //Prints 10

Posted On : 2016-05-19 16:04:46
Satisfied : 2 Yes  0 No
profile Abhijeet - anyforum.in Abhijeet
030
Reply This Thread
up-rate
3
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in