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

Optional counter behaviour

I’am currently studying for OCP and I’m simply asking why the first optional does not increment "counter" :

Integer counter = 1;
Optional<Integer> optional = (Optional<Integer>) Optional.empty().orElse( Optional.of(counter +1));
System.out.println(counter); //print 1 

AtomicInteger counter2 = new AtomicInteger(1);
Optional<Integer> option = (Optional<Integer>) Optional.empty().orElse( Optional.of(counter2.getAndIncrement()));
System.out.println(counter2); // print 2

>Solution :

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

Because expression counter + 1 does not modify the counter variable itself. Try ++counter instead.

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