A trick with Java’s Increment Operator

Almost every Java programmer knows how and when to use the unary increment operator (++) on an integer. If we have an integer i, both i++ and ++i increment the value of i by 1 (though in slightly different ways). However, if you have an integer array arr, and there is a value at its zeroth position, what effect does arr[0]++ have on the zeroth element of arr
I had an interesting discussion with my friend on this case. I was of the opinion that the value of arr[0] if printed out in the next line would have increased by 1. My friend, however said that since Java uses pass by value for primitives, arr[0] gets the value of the zeroth element. So though we increment this value, the value of the element will not be affected. 
In my opinion, arr[0]++ is equivalent to 
arr[0]=arr[0]+1

The way my friend saw the effect of the operation can be written as
int temp  = arr[0]
temp++ //or temp=temp+1
So, which do you think is the case? I am pretending this is very difficult to understand or to guess; just don’t hesitate to try out if you’re not sure 🙂
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

2 thoughts on “A trick with Java’s Increment Operator

Leave a Reply

Your email address will not be published. Required fields are marked *