天天看點

java 前置_Java中的前置++和後置++的了解

前言

在C、C++等程式設計語言中都會存在i++,++i,在實際運用中我們總能記住一句話==i++(後置++)是先使用在+1,而++i(前置++)是先自增再使用==。但是在一些很燒腦的場合,這種規律就會“失效”。

本文會首先簡單的介紹下前置和後置++在一些場合的實際應用,可以看到的是合理的使用++會使得代碼簡潔不少。

++前置後置的實際使用

package com.dimple.javabase;

import java.util.Arrays;

public class AddOpt {

public static void main(String[] args) {

int i = 0;

String[] people = {"Dennis Ritchie", "Bjarne Stroustrup", "James Gosling"};

System.out.println(Arrays.asList(people).toString());

System.out.println("preposition ++");

System.out.println(" before operation···");

System.out.println(" i= "+i);

System.out.println(" "+people[i++]);

System.out.println(" after operation···");

System.out.println(" i= "+i);

System.out.println("postposition ++");

i = 0;

System.out.println(" before operation···");

System.out.println(" i= "+i);

System.out.println(" "+people[++i]);

System.out.println(" after operation···");

System.out.println(" i= "+i);

}

}

運作結果如下:

[Dennis Ritchie, Bjarne Stroustrup, James Gosling]

preposition ++

before operation···

i= 0

Dennis Ritchie

after operation···

i= 1

postposition ++

before operation···

i= 0

Bjarne Stroustrup

after operation···

i= 1

Process finished with exit code 0

上面的都是很基礎的,隻是單純的為了回憶一下,所有需要記住的是:

==前置++(++i)是先進行++操作後再指派==

==後置++(i++)是先進行指派再進行++操作==

最近在網上看到這樣一個題,本文的主要目的是這道題。

一道很燒腦的題

朋友在面試的時候遇到了一道題,然後我們一起交流的時候,他把這道題給我說了下,結果我也做錯了.是以在此記錄下:

題是這樣的:

package com.dimple.javabase;

public class Increment {

private static int k = 0;

public static void main(String[] args) {

int j=0;

int n=0;

for(int i=0;i<100 ;i++){

j=j++;

k=k++;

n=++n;

}

System.out.println(j);

System.out.println(k);

System.out.println(n);

}

}

答案出乎我的意料:

100

不需要去看編譯後的位元組碼,其實很簡單的就可以看出來:

分析:

在分析之前我們還是先看一個這樣的代碼:

package com.dimple.javabase;

import java.util.Arrays;

public class AddOpt {

public static void main(String[] args) {

int j=0;

j = j++;

System.out.println(j);

}

}

以上代碼如果我們使用的是IDEA編譯器的話,在j下面有一個小波浪線提示以下話:

The value changed at ‘j++’ is never used less… (Ctrl+F1)

Inspection info: This inspection points out the cases where a variable value is never used after its assignment, i.e.:  - the variable never gets read after assignment OR  - the value is always overwritten with another assignment before the next variable read OR  - the variable initializer is redundant (for one of the above two reasons)

以上提示說的是:該j變量并沒有被使用。emmmmm不是讓它=j了嗎?以上隻是一個小的插曲,接下來開始我們的分析。

首先我們看到==j=j++;==這樣的一句話,本身是有問題的(為了說明,我們把表達式左邊的j叫做j1,右邊的j叫做j2(注意,隻是叫做!)):

1. 執行時,首先是會執行等号右邊的話,也就是==j1=j2==這一句話,那麼這樣的一句話,得到的結果是j1=0,對吧。

2. 這個時候如果按照正常的邏輯,那麼應該是執行j++這句話了對吧。是這樣沒錯,肯定是會執行j++這一句話的。注意:執行這個j2++的時候,并不和j1在同一個工作區,j2++完了之後,并沒有任何的變量去接收它。導緻j2++廢棄。是以j一直都是0.

總結

–操作符同理,其實細緻點這個問題是可以看出來的,還是需要修煉基本功呀···