java变量的初始化之后的默认值

对于类的成员变量


不管程序有没有显示的初始化,Java  虚拟机都会先自动给它初始化为默认值。

  1、整数类型(byte、short、int、long)的基本类型变量的默认值为0。

  2、单精度浮点型(float)的基本类型变量的默认值为0.0f。

  3、双精度浮点型(double)的基本类型变量的默认值为0.0d。

  4、字符型(char)的基本类型变量的默认为 “/u0000”。

  5、布尔性的基本类型变量的默认值为 false。

  6、引用类型的变量是默认值为 null。

  7、数组引用类型的变量的默认值为 null。当数组变量的实例后,如果没有没有显示的为每个元素赋值,Java 就会把该数组的所有元素初始化为其相应类型的默认值。

数组例子:

  1)   int[] a;   //声明,没有初始化默认值是null

  2)   int[] a=new int[5];   //初始化为默认值,int型为0

代码实例

public class ThisDemo {
    byte b;
    short s;
    int i;
    long l;
    float f;
    double d;
    char c;
    boolean n;
    int[] a;
    int[] t=new int[5];
    public static void main(String[] args) {
        ThisDemo  thisDemo = new ThisDemo();
        System.out.println( "byte = "+ thisDemo.b);
        System.out.println( "short = "+ thisDemo.s);
        System.out.println( "int = "+ thisDemo.i);
        System.out.println( "long = "+ thisDemo.l);
        System.out.println( "float = "+ thisDemo.f);
        System.out.println( "double = "+ thisDemo.d);
        System.out.println( "char = "+ thisDemo.c);
        System.out.println( "boolean = "+ thisDemo.n);
        System.out.println( "int[] = "+ thisDemo.a);
        System.out.println( "int[] t = "+ thisDemo.t[0]);
    }

结果:

byte = 0
short = 0
int = 0
long = 0
float = 0.0
double = 0.0
char = 
boolean = false
int[] = null
int[] t = 0

局部变量初始化


局部变量声明以后,Java 虚拟机不会自动的为它初始化为默认值。

  因此对于局部变量,必须先经过显示的初始化,才能使用它。

  如果编译器确认一个局部变量在使用之前可能没有被初始化,编译器将报错。

代码实例:

 public class ThisDemo {
    public static void main(String[] args) {
        byte b;
        short s;
        int i;
        long l;
        float f;
        double d;
        char c;
        boolean n;
        int[] a;
        int[] t=new int[5];
        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( "char = "+ c);
        System.out.println( "boolean = "+ n);
        System.out.println( "int[] = "+ a);
        System.out.println( "int[] t = "+ t[0]);
    }
}

结果:

Error:(15, 40) java: 可能尚未初始化变量b
Error:(16, 41) java: 可能尚未初始化变量s
Error:(17, 39) java: 可能尚未初始化变量i
Error:(18, 40) java: 可能尚未初始化变量l
Error:(19, 41) java: 可能尚未初始化变量f
Error:(20, 42) java: 可能尚未初始化变量d
Error:(21, 40) java: 可能尚未初始化变量c
Error:(22, 43) java: 可能尚未初始化变量n
Error:(23, 41) java: 可能尚未初始化变量a

 

 

posted @ 2018-05-16 15:30  盟约  阅读(528)  评论(0编辑  收藏  举报