```java public class ExampleMethod3 { public static void main(String[] args) { /* * 本篇說明會著重在於 return 以及方法跟值的變動上 。 * * 在 test 方法內的 i 值,其實是 myInt 的副本。 * 所以當 myInt 值傳入方法後變動 i 的內容, * 接著試著印出方法外面的 myInt,會發現印出來的仍然是 1。 */ int myInt = 1; test(myInt); System.out.println(myInt); /* * 那麼試著用有 return 的 test2 方法來看看 myInt 是否會變動。 * 同樣是傳入 myInt 到方法內,也同樣是變動內容,但這次會回傳值。 * * 這時仍然發現 myInt 不會被更動內容。 * 原因在於回傳的值需要有變數去承接,不然變更的仍然只有副本而已。 */ test2(myInt); System.out.println(myInt); /* * 最後試著用有 return 的 test2 方法,並且承接了回傳結果。 * * 這時發現 myInt 被更動內容了。 * * 此時可以了解到一件事情,那就是即使方法有回傳(return)這件事, * 但若沒有變數去承接這個變動,結果仍然不會有什麼改變。 */ myInt = test2(myInt); System.out.println(myInt); } public static void test(int i) { i ++; } public static int test2(int i) { i ++; return i; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up