java查找增量文件,Java增量运算符查询(++ i和i ++)

I have the following code:

public class Book {

private static int sample1(int i) {

return i++;

}

private static int sample2(int j) {

return ++j;

}

public static void main(String[] arguments){

int i = 0;

int j = 0;

System.out.println(sample1(i++)); //0

System.out.println(sample1(++i)); //1

System.out.println(sample2(j++));//1

System.out.println(sample2(++j));//2

System.out.println(i);//2

System.out.println(j);//2

}

}

My expected output is in comments. The actual output is below:

0

2

1

3

2

2

I'm getting confused with the function calls and incemental operator. Can someone kindly explain the actual result?

解决方案

First of all you need to know the difference between x++ and ++X;

In case of x++ :

First the current value will be used and it will be incremented next.

That means you will get the present value of x for the operation and if you

use x next time will get the incremented value;

In case of ++x :

First the current value will be incremented and it will be used (the incremented value) next, that means you will get the incremented value

at this operation and for other after this operation.

Now lets split the code and discuss them separately

method: sample1() :

private static int sample1(int i) {

return i++;

}

This method will take a int and return it first and then try to increment but as after returning the variable i will go out of scope so it will never be

incremented at all. exp in: 10-> out 10

method: sample2() :

private static int sample2(int j) {

return ++j;

}

This method will take a int and increment it first and then return it. exp in: 10-> out 11

In both case only the variables will change locally, that means if you call from main method the variables of main method will remain unaffected by the change

(as the sample1() and sample2() are making copy of the variables)

Now for the code of the main method

System.out.println(sample1(i++)); // it's giving sample1() `i=0` then making `i=1`

// so sample1() will return 0 too;

System.out.println(sample1(++i)); // it's making `i=2` and then giving sample1() `i=2`

// so sample1() will return 2;

System.out.println(sample2(j++)); // it's giving sample2() `j=0` then making `j=1`

// so sample2() will return 1;

System.out.println(sample2(++j)); // it's making `j=2` giving sample2() `j=2` then

// so sample2() will return 3;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值