java基礎面試題(10.30)
阿新 • • 發佈:2018-11-20
面試題一:
package com.yan.interview; import java.util.Arrays; public class Exam4 { public static void main(String[] args) { int i = 1; String str = "hello"; Integer num = 200; int[] arr = {1,2,3,4,5}; MyData my = new MyData(); change(i,str,num,arr,my); System.out.println("i = " + i); System.out.println("str = " + str); System.out.println("num = " + num); System.out.println("arr = " + Arrays.toString(arr)); System.out.println("my.a = " + my.a); } public static void change(int j, String s, Integer n, int[] a,MyData m){ j += 1; s += "world"; n += 1; a[0] += 1; m.a += 1; } } class MyData{ int a = 10; }
執行結果:
i = 1
str = hello
num = 200
arr = [2, 2, 3, 4, 5]
my.a = 11
方法的引數傳遞機制:
- 形參是基本資料型別 傳遞資料值
- 實參是引用資料型別 傳遞地址值
- 特殊的型別:String、包裝類等物件不可變性
面試題二:
package com.yan.interview; public class Exam5 { static int s;//成員變數,類變數 int i;//成員變數,例項變數 int j;//成員變數,例項變數 { int i = 1;//非靜態程式碼塊中的區域性變數 i i++; j++; s++; } public void test(int j){//形參,區域性變數,j j++; i++; s++; } public static void main(String[] args) {//形參,區域性變數,args Exam5 obj1 = new Exam5();//區域性變數,obj1 Exam5 obj2 = new Exam5();//區域性變數,obj1 obj1.test(10); obj1.test(20); obj2.test(30); System.out.println(obj1.i + "," + obj1.j + "," + obj1.s); System.out.println(obj2.i + "," + obj2.j + "," + obj2.s); } }
執行結果
2,1,5
1,1,5
考點
- 就近原則
- 變數的分類
- 成員變數:類變數、例項變數
- 區域性變數
- 非靜態程式碼塊的執行:每次建立例項物件都會執行
- 方法的呼叫規則:呼叫一次執行一次
當局部變數與xx變數重名時,如何區分:
- 區域性變數與例項變數重名: 在例項變數前面加“this.”
- 區域性變數與類變數重名: 在類變數前面加“類名.”