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 :
Because expression counter + 1 does not modify the counter variable itself. Try ++counter instead.