Java学习笔记01-传值or传引用
2015-11-14 本文已影响81人
1Z实验室阿凯
突然发现Java在传值和引用部分上,借助C语言里面的指针(底层内存分配)可以很容易理解,或者者说这些难点都是C语言的遗留问题和Java无关
Note:关于传值与传引用的定义可参考下方链接
Java 方法的参数是按什么传递的问题,其答案就只能是:即是按值传递也是按引用传递,只是参照物不同,结果也就不同 Java传值与引用
直接上代码
/*
*This Program demonstrate parameter passing in java
*@Version 1.00
*@Author Scorpion
*/
public class ParamTest{
public static void main(String[] args){
/**
*Test1: Methods can't modified numeric parameters
*/
System.out.println("TestTrip Value...");
double percent = 10;
System.out.println("Before: percent="+percent);
tripleValue(percent);
System.out.println("After: percent="+percent);
/**
*Test2: Method can change the state of object parameters
*/
System.out.println("\nTesting tripleValue:");
Employee harry = new Employee("Harry",5000);
System.out.println("Before: salary = "+harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary = "+harry.getSalary());
/**
*Test3: Methods can't attach new objects to object parameter
*/
System.out.println("Testing swap:");
Employee a = new Employee("Alice",70000);
Employee b = new Employee("Bob",60000);
System.out.println("Before: a=" + a.getName());
System.out.println("Before: b=" + b.getName());
swap(a,b);
System.out.println("After: a=" + a.getName());
System.out.println("After: b=" + b.getName());
}
public static void tripleValue(double x){
x = 3 * x;
System.out.println("End of Method:x="+x);
}
public static void tripleSalary(Employee x){
x.raiseSalary(200);
System.out.println("End of Method x = "+x.getSalary());
}
/**
*Note: just like pointer
*/
public static void swap(Employee x,Employee y){
Employee temp = x;
x = y;
y = temp;
System.out.println("End of Method: x="+x.getName());
System.out.println("End of Method: y="+y.getName());
}
}
class Employee{//simplified Employee class
private String name;
private double salary;
public Employee(String n,double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
}
OUTPUT
TestTrip Value...
Before: percent=10.0
End of Method:x=30.0
After: percent=10.0
Testing tripleValue:
Before: salary = 5000.0
End of Method x = 15000.0
After: salary = 15000.0
Testing swap:
Before: a=Alice
Before: b=Bob
End of Method: x=Bob
End of Method: y=Alice
After: a=Alice
After: b=Bob
对应C语言片段片段
Part1: tripleValue
void tripleValue(int a,int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
void main()
{
int a = 10;
int b = 9;
tripleValue(a,b);
}
Part2:tripleSalary
void tripleSalary(int * salary)
{
*salary +=2000;
}
void main()
{
int salary = 5000;
int* p = &salary;
tripleSalary(p);
}
Part3:Swap
void swap(int* a,int* b)
{
int* tmp = null;
tmp = a;
a = b;
b = tmp;
}
void main()
{
int a = 9;
int b = 10;
int *pa = &a;
int *pb = &b;
swap(pa,pb);
}