版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/85234227
1. In the case of a method’s local variables, if you say:
void f() {
int i;
i++;
}
you’ll get an error message that says that i might not be initialized.
2. member initialize.
case 1: The compiler automatically initialize these values.
// housekeeping/InitialValues.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Shows default initial values
public class InitialValues {
boolean t;
char c;
byte b;
short s;
int i;
long l;
float f;
double d;
InitialValues reference;
void printInitialValues() {
System.out.println("Data type Initial value");
System.out.println("boolean " + t);
System.out.println("char [" + c + "]");
System.out.println("byte " + b);
System.out.println("short " + s);
System.out.println("int " + i);
System.out.println("long " + l);
System.out.println("float " + f);
System.out.println("double " + d);
System.out.println("reference " + reference);
}
public static void main(String[] args) {
new InitialValues().printInitialValues();
System.out.println(new InitialValues().c + 1);
}
}
/* Output:
Data type Initial value
boolean false
char []
byte 0
short 0
int 0
long 0
float 0.0
double 0.0
reference null
1
*/
The char value is zero, which in my platform(jdk 1.8) char output is [] ( in windows is [ ]).
case 2: The compiler appropriately complains about forward referencing, since it is about the order of initialization and not the way the program is compiled.
// housekeeping/MethodInit3.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class MethodInit3 {
// - int j = g(i); // Illegal forward reference
int i = f();
int f() {
return 11;
}
int g(int n) {
return n * 10;
}
}
referecnes:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/InitialValues.java
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/MethodInit3.java