Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
following code give output b = 0;
Java
int b = 0;
b = b++;
b +=b;
System.out.println("Byte : "+b);


What I have tried:

b = b++;

why b++ assign 0 not 1
Posted
Updated 31-Oct-16 19:33pm
Comments
Suvendu Shekhar Giri 1-Nov-16 1:18am    
First check few good tutorials and learn the basics.
Richard MacCutchan 1-Nov-16 3:50am    
Because that code just makes no sense. Go to the Java tutorials and study the section on operators.

1 solution

Although, the question looks to be just a homework and to which we do not respond, generally, but, here are the possibilities of such results which may help you understand the basics of increament.

Quote:
int x = 34;
int y = x++;

x is first assigned to y and then incremented by one. Therefore, x becomes 35 while y is assigned with the value 34.

Reference: Increment and Decrement Operators - Java Tutorial - Java With Us[^]

Now, when you assign the post-increamented value to the same variable it just assign the old value i.e, 0 to b in the following line-
Java
b = b++; //b=0

So you are getting 0 as output.

Change the above line to just -
Java
b++; //b=1


Try following code-
Java
int b = 0;
b++; //changed line
//b +=b; // meaningless as it addsup to itself
System.out.println("Byte : "+b);


Hope, I was able to clarify your doubt. If not, please let me know :)
 
Share this answer
 
Comments
sdsoft.comze.com 1-Nov-16 6:21am    
but i = i++ + i;// i = 1

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900