java变量的分类与初始化 - 官方文档总结

2017/6/25

转载写明出处: http://www.cnblogs.com/daren-lin/p/java-variable-and-default-value.html

首先学习java最权威的就是官方的文档了,今天从头读了文档,把一些小细节理清楚。

 

变量

Java语言里的变量分以下4类:

1. Instance Variables: (Non-Static Fields) 就是类里非静态的field

2. Class Variables: (Static Fields) 类里静态的field

3. Local Variables: 局部变量

4. Parameters: 参数

两个术语要注意,分别是field和variable。field是指上面的1和2,是class拥有的。而不是field的变量就叫variable,对应上面的3和4,或者说局部的都是variable。

 

命名

Java的文档中明确写了推荐的命名方式,这就是为什么java的代码里命名基本都差不多。格式就是用连续的有意义的单词,从第二个单词开始,首字母大写。比如: speed, currentGear

 

基本数据类型 Primitive Data Type

Java有8个基本数据类型

整数型 4个: byte, short, int, long

浮点 2个: float, double

字符 1个: char

布尔 1个: boolean

他们的默认初始值如下:

 

Data TypeDefault Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object)   null
boolean false

 

 

默认值 Default Value

关于没有初始化的变量的默认的值,c/c++是不会帮你设置的,而java不同,官方文档描述的很清楚:

The eight primitive data types are: byte, short, int, long, float, double, boolean, and char. The java.lang.String class represents character strings. The compiler will assign a reasonable default value for fields of the above types; for local variables, a default value is never assigned. A literal is the source code representation of a fixed value. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

就是对于Field来说,自动设成默认值,比如int设成0,object设成null。而对于Variable来说,不会自动设置,如果没有初始化的编译器会报错

 

参考:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variablesummary.html

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

 

posted @ 2017-06-26 10:44  DarenLin  阅读(333)  评论(0编辑  收藏  举报