Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

java and Arithmetic Operators and Increment

It is one of the simple operations and I do not understand why and I just save it, but this bothers me, so I want to understand why?

int a = 2;
int b = 4;
int c = 10;
a = b++;
System.out.println(a);
a = ++b;   
System.out.println(a);    

This process ++ I did not understand how it works. In this case, the output is 4 and 6

But I only added 1 and the result was an added 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the beginning, she only took the value 4 without added any thing, then in the second output, she added 2

If you put the code in the sixth line a = ++c, the output will be by adding 1, not 2, to c.

so Some help to understand please.

On the other hand, since = is an assignment, I imagine that the result will preserve the last number, and now if I modify the code as follows:

int a = 2;
int b = 4;
int c = 10;
a = b++;
System.out.println(a);
a = ++c;   
System.out.println(a);
a = ++b;
System.out.println(a);

Here the output will be

4
11
6

I did not expect this either, as the last output should have been 5, not 6.

So I would like some help, please, so that I can understand and not just memorize.

>Solution :

The rule to remember is: Always process from left to right.

a = b++; // First assign b to a, then increment b.
// Here a=4, b=5
a = ++b; // First increment b, then assing the incremented value to a.
// Here a=6, b=6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading