//given the following code,what will be the output? A
class Value{
public int i=15;
}
public class Test{
public static void main(String argv[]){
Test t=new Test( );
t.first( );
}
public void first( ){
int i=5;//局部变量i = 5;注意这个i是局部变量
Value v=new Value( );
v.i=25;//创建了一个value对象,并把这个对象i的值赋值为25
second(v,i);//v(v中的属性值为25)和局部变量i=5传进second方法
System.out.println(v.i);//v的属性i在second函数中被改为了20
}
public void second(Value v,int i){
i = 0;//second方法的局部变量,与之前的i没有关系
v.i = 20;//将传进来的V中的属性i的值改为20
Value val = new Value( );
v = val;//新创建的Value对象val,属性i值为15,并将v指向val对象,
//v已经和之前传进来的对象没关系了
System.out.println(v.i+" "+i);//此时v的属性i为15,先输出 15(v.i) 0(i)
}
}
A、15 0 20
B、15 0 15
C、20 0 20
D、0 15 20
//给出以下代码,请给出结果. B
class Two{
Byte x;
}
class PassO{
public static void main(String[] args){
PassO p=new PassO();
p.start();
}
void start(){
Two t=new Two();
System.out.print(t.x+””);
Two t2=fix(t);
System.out.print(t.x+” ” +t2.x);
}
Two fix(Two tt){
tt.x=42;
return tt;
}
}
A、null null 42
B、null 42 42
C、0 0 42
D、0 42 42
E、An exception is thrown at runtime
F、Compilation
//指出下列程序运行的结果 ()
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public static void main(String args[]) {
Example ex = new Example();
// ex.str叫实参
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
}
// str叫形参
public void change(String str1, char[] ch1) {
str1 = "test ok";
ch1[0] = 'g';
}
}
A、 good and abc
B、 good and gbc
C、 test ok and abc
D、 test ok and gbc
答案:B
解析:大家可能以为Java中String和数组都是对象所以肯定是对象引用,然后就会选D,其实这是个很大的误区:因为在java里没有引用传递,只有值传递,引用数据类型传递的是地址值,
把实参的地址值赋值给形参,实参和形参通过地址值指向同一个对象,你可以通过它修改这个地址的内容(引用不变),因为此时这个内容的地址和原地址是同一地址