天天看点

Java变量及运算符

1.实例变量

2.类变量

3.局部变量

4.常量 :final

5.main方法

  1. //头文件
  2. java.*

//类名Demo2

public class Demo2{

//实例变量,从属于对象,在方法外面,类里面。如果不初始化的话,输出默认值。数值类型默认值0 0.0;字符串类型默认值null;布尔类型默认值false。

String string1;

int string2=3;

//常量,修饰符static,不存在先后顺序

final static double PI=3;

static final double PII=3.1;

//类变量,必须带static修饰符。从属于类,在main方法外写,在main里调用也可直接被输出。

static int a=3;

//main方法
public static void main(String[] args){
    int i=3;//局部变量,必须声明和初始化,且必须写在方法里。仅作用于所写的那个类。
    
    System.out.println(a);//输出前面的类变量a  运行结果是3
    System.out.println(i);//输出局部变量i   运行结果是3
    
    //输出实例变量
    Demo2 demo2=new Demo2();//先定义声明
    System.out.println(demo2.string1);//输出实例变量string1     运行结果是null
    System.out.println(demo2.string2);//输出实例变量string2  运行结果是3
    System.out.println(PI);//输出常量PI  运行结果是3
    System.out.println(PII);//输出常量PII  运行结果是3.1

}
public void others(){
//其他方法
}           

}