Why does post-increment work on wrapper classes

前端 未结 5 664
南笙
南笙 2020-12-11 15:53

I was doing a review of some code and came across an instance of someone post-incrementing a member variable that was a wrapper class around Integer. I tried it myself and

5条回答
  •  既然无缘
    2020-12-11 16:02

    Answer by Sir Tedd Hopp is at a very complex level for programmers who are programming only for few or couple of years.

    Let me clear your doubt in simple way suppose

        Integer x=10;
        x++;
        System.out.println(x) ;
    

    output will be 11

    Because ++ either post or pre increment is doing Addition by 1 only internally

    ie x+1 is what it has to perform and put back the result in the same variable.

    ie x=x+1;
    

    now we all know that + operator can only take primitives but x is object , then we have auto-unboxing and auto-boxing concept. so the expression becomes

    x.intValue()+1;//step 1 auto-unboxing
    
    x=Integer.valueOf(x.intValue()+1);//step 2 auto-boxing
    

    Hence output comes as 11 after another step of auto-unboxing inside the println statement.

提交回复
热议问题