变量
重点
1、调用方法的2种形式
Test a = new Test();
a.method1(5);
new Test().method1(6);
2、
finanl 只有一次!
基本变量类型
整型
类型 | 长度 | 数的范围 |
---|---|---|
byte | 8 | -128—127 |
short | 16 | |
int | 32 | |
long | 64 |
字符型
只能存放一个字符
char = ‘中’;
浮点型
类型 | 长度 |
---|---|
float (加F) | 32 |
double(e2 = 10^2) | 64 |
作用域(调用方法的2种形式)
public class Test{
//全局变量
int i = 1;
public void method1(int i) {
System.out.println(i);
}
public void methid2() {
System.out.println(i);
}
public static void main(String[]args) {
//调用方法函数的两种方法
//方法1
Test a = new Test();
a.method1(5);//结果打印出来是5
//方法2
new Test().method1(6);
}
final
当一个变量被final修饰的时候,该变量只有一次赋值的机会
public class HelloWorld {
public void method1(final int j) {
j = 5; //不能执行,在传入参数的时候已经进行了第一次赋值。
}
}
成员变量,局部变量
成员变量:有默认值
局部变量没有默认值,必须先定义,赋值,再使用。
public class heroTest {
int i;
void show() {
int y;
System.out.println(i);
//报错:The local variable y may not have been initialized
//要初始化 y = 0;
System.out.println(y);
}
}