您的位置:首页 > 编程语言 > Java开发

Java基础知识02 -- 变量与常量

2020-06-05 06:07 57 查看

变量

Demo5

  • 可以变化的量

  • Java是一种强类型(strongly typed)语言,每个变量都必须声明其类型

  • java变量是程序中最基本的存储单元,其要素包括变量名,变量类型和作用域

变量作用域

  • 类变量
  • 实例变量
  • 局部变量
public class demo5 { //class
// attribute: variables

// instance variable: subordinate object
// if not initialize, the default value of int is 0
// the default value of string is null
// boolean: default-false
// except primitive type, the default value of other type is null
String name;
int age;

// class variable; static
static double salary = 2500;

// main function
public static void main(String[] args) {
// local variable: must declare and initialize
int i = 10; // This variable only works in this method

// instance variable
// variable type  variable name = new demo5();
demo5 demo5 = new demo5();
System.out.println(demo5.age);
System.out.println(demo5.name);

// class variable -- static
System.out.println(salary);
}

// other function
public void add(){

}
}

常量

demo6

初始化之后不能再改变值,常量名通常使用大写字母和下划线

final 常量名 = 值

final是修饰符(modifier),不存在先后顺序问题

public class demo6 {

// final is Modifier, there is no order
//static final double PI = 3.14;
final static double PI = 3.14;
public static void main(String[] args) {
System.out.println(PI);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐