Post/Pre increment operator question

In this article we will cover commonly asked interview question, often asked in most of the written tests- To guess the output of a program where Pre and Post increment operators are used.

Post/Pre increment operator question

int i = 1;
i = i++;
System.out.println(i);

This will print 1 because i++ is post-increment and i value is still 1.

int i = 1;
i= --i;
System.out.println(i);

This will print 0 because --i is pre-increment.

int i = 1;
i = i++ + --i
System.out.println(i);

This will print 2. Now most of the people will mark 3 as an answer but there is a logic behind its output.

Explanation:
i++ evaluates to 1. It will increment the value of i by 1 before --i is evaluated. The equation will be 
1 + (2-1) = 1 + 1 = 2.


Comments

Popular posts from this blog

Java Tutorial Series - Collections - LinkedList

Software Testing Life Cycle for Agile

Coforge Automation Testing | SDET | Interview Experience 2022 | Noida