1.先弄明白基本数据类型和引用数据类型的区别
int num = 1;
String name = "HHH"
num 是基本数据类型,值直接保存在变量中。
name 是引用数据类型,变量中保存的只是一个地址,而这个地址才指向真正的对象。
2.弄清楚赋值运算符 = 的作用
对于基本数据类型num = 20 就是把20这个值直接存到变量num中去。
num = 6 + 3; 就是把6+3的结果9这个值直接存到变量num中去
对于引用数据类型 String str = "java"; 只是把str这个变量中保存的地址改变,存入对象"java"的地址。
例子:
void foo(int value) {
value = 100;
}
public static void main(String[] args) {
int num = 10;
foo(num);
}
num = 10代表基本数据类型num中存了10这个值
调用foo()方法后,value = 10,变量value中存放了10
value = 100; 变量value 中存了100
所以num没有改变还是10
void foo(String str) {
str = "windows";
}
public static void main(String[] args) {
String str = "hello";
foo(str);
}
实参str是引用数据类型,它存放的是"hello"这个对象的地址
调用foo()方法后,形参str中也存放了”hello“这个对象的地址
在foo()方法体中,形参str中存放的地址变为"windows"这个对象的地址
实参str没有改变
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;
Value v=new Value( );
v.i=25;
second(v,i);
System.out.println(v.i);
}
public void second(Value v,int i){
i = 0;
v.i = 20;
Value val = new Value( );
v = val;
System.out.println(v.i+" "+i);
}
}
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;
}
}
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public static void main(String args[]) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
}
public void change(String str1, char[] ch1) {
str1 = "test ok";
ch1[0] = 'g';
}
}
关于栈和堆的画法个人感觉存在很多问题,但是重点在理解引用类型数据的地址是如何变化的,画的漏洞百出,见笑了。