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

Difference between += and = 1+ in Java

Me and my friend have been working on a problem for school. We are traversing a graph with DFS and are counting the number of nodes in each given component. We get widely different results and have identified where the difference lies.

When going into the next recursion, my friend uses the syntax

componentSize += DFS_visit(nextNodeToVisit);

whereas I use

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

componentSize = 1 + DFS_visit(nextNodeToVisit);

I originally thought these two were the same, so what is the difference? And which one should be used in our case?

>Solution :

 componentSize += DFS_visit(nextNodeToVisit); 

means

 componentSize = componentSize + DFS_visit(nextNodeToVisit);

Compare that with

 componentSize = DFS_visit(nextNodeToVisit) + 1;

See the difference?

In general a <op>= b means roughly the same as a = a <op> b where <op> an operator. (There is also a typecast of the LHS to the type of a.)


And which one should be used in our case?

It is not clear which is correct. We would need to see the data structure and more of the algorithm.

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