黑马程序员技术交流社区
标题:
关于调用show()问题
[打印本页]
作者:
houyudong
时间:
2014-5-6 20:58
标题:
关于调用show()问题
本帖最后由 houyudong 于 2014-5-8 12:45 编辑
class Demo
{
public static void main(String[] args)
{
int x = 4;
show(x);
System.out.println(x);
}
public static void show(int x)
{
x = 2;
}
}
输出结果为:4
1、show(x),把x=4放入show方法,将4替换为2,输出x。为什么会是4不是2 ?那么show没有起到作用|??
class Demo
{
int x = 3;
public static void main(String[] args)
{
Demo d = new Demo();
d.x = 10;
show(d);//show(new Demo());
System.out.println(d.x);
}
public static void show(Demo d)
{
d.x = 6;
}
}
输出结果为:6
建立对象名为d的Demo类对象,成员变量x=3被d.x替换为10,将d对象放入show方法中,更改对象成员变量x为6.输出d对象的成员变量x值为6,这样流程对吗??
class Demo
{
public static void main(String[] args)
{
int[] arr = new int[2];
show(arr);
System.out.println(arr[0]);
}
public static void show(int[] arr)
{
arr[0]++;
}
}
输出结果为:1
定义一个数组名为arr的一维数组,有两个元素,调用show方法,将arr放入show方法,arr【0】++?什么意思。arr【0】中元素加一,还是角标加一????
这个show调用的的是对象还是变量?
作者:
大恶魔先森~
时间:
2014-5-6 21:14
1,
class Demo
{
public static void main(String[] args)
{
int x = 4;
show(x);
System.out.println(x);
}
public static void show(int x)
{
x = 2;
}
}
复制代码
对于System.out.println(x);来说show方法里的x为局部变量,所谓局部变量就是定义在方法内的变量,局部变量会随着方法的结束而被内存释放,而此时主函数并没有结束,所以打印语句打印的是int x=4;这个x,所以结果为4
2.
class Demo
{
int x = 3;
public static void main(String[] args)
{
Demo d = new Demo();
d.x = 10;
show(d);//show(new Demo());
System.out.println(d.x);
}
public static void show(Demo d)
{
d.x = 6;
}
}
复制代码
x的初始值为3,将10在赋值给x,x==10,然后调用show方法,将6赋值给了x,所以最后x==6。
3,
class Demo
{
public static void main(String[] args)
{
int[] arr = new int[2];
show(arr);
System.out.println(arr[0]);
}
public static void show(int[] arr)
{
arr[0]++;
}
}
复制代码
数组未初始化,默认的值都为0,所以arr[0]==0;然后调用show方法arr[0]++自增1,然后打印出来,所以结果为:1
这些题目都蛮基础的,建议还是认真点看毕老师的基础视频。
作者:
曹冬明
时间:
2014-5-6 22:12
这个就是Java中参数传递的问题了,只要记住,基本类型参数传的是值,也就是原变量值的拷贝,引用变量传的是地址,也就是引用
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2