您的位置:首页 > 其它

变量及其传递

2017-12-08 11:17 92 查看
1.变量类型(内存空间):

基本类型

引用型

例:

public class MyDate {
int year;
int month;
int day;

public MyDate(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;

}

void addYear(){
year++;
}

public void display(){
System.out.println(year + "-" + month + "-" + day);
}

public static void main(String args[])
{
MyDate m = new MyDate(2004, 9, 22);
MyDate n = m;
n.addYear();
m.display();
n.display();
}

}

只复制引用,操纵的同一个对象


2.字段变量和局部变量 区别

(1)定义:

类中;方法中的变量

(2)内存中:

对象的一部分,堆中;存在栈中

(3)初始化:

可自动赋值;显示赋值

(4)语法:

可被public,private, static,final修饰;不能被访问控制符及static修饰

都可以被final修饰

例:

class Test()
{
int a;//自动赋值为0
void fun(){
int b;
System.out.println(b);//无法通过,需要赋初值
}
}


3.传递

Java是值传递,复制;对于引用型变量,传递值是引用值,不复制对象实体。

public class TransByValue {

public static void main (String[] args) {
int a = 0;
modify (a); System.out.println(a);//result:0 值传递

int [] b = new int [1];
modify(b);
System.out.println(b[0]); //result:1 引用类型
}

public static void modify (int a) {
a++;
}
public static void modify (int[] b) {
b[0] ++;
b = new int[5];
}
}


4.返回类型

基本类型

引用类型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: