java long初始化_Java变量的初始化

Java变量默认值

Java变量的初始化,如果不赋值,将会有个默认值,对于基本类型,比如int,long是0, boolean 是false等,引用类型如果不设置,将会是null.

package variable.initialize;

public class Test {

int intAge;

short shortAge;

long longAge;

float floatAge;

double doubleAge;

char charC;

boolean booleanFlg;

byte byteB;

String string;

private void print() {

System.out.println("The default value for int is " + intAge);

System.out.println("The default value for short is " + shortAge);

System.out.println("The default value for long is " + longAge);

System.out.println("The default value for float is " + floatAge);

System.out.println("The default value for double is " + doubleAge);

System.out.println("The default value for char is " + charC+((int)charC));

System.out.println("The default value for boolean is " + booleanFlg);

System.out.println("The default value for bayte is " + byteB);

System.out.println("The default value for String is " + string);

}

public static void main(String[] args) {

new Test().print();

}

}

输出结果:

The default value for int is 0

The default value for short is 0

The default value for long is 0

The default value for float is 0.0

The default value for double is 0.0

The default value for char is

The default value for boolean is false

The default value for bayte is 0

The default value for String is null

初始化顺序

Java 先初始化静态比变量和静态块,然后在初始化非静态变量和块,这些都在构造方法调用前调用。

package variable.initialize;

class Dog {

int age;

Dog(int age) {

this.age = age;

System.out.println("This is the constructor of Dog class, with age " + age);

}

}

public class Test2 {

Dog dog1 = new Dog(2);

{

System.out.println("I am a nomal block.");

}

static Dog dog2 = new Dog(3);

static{

System.out.println("I am a static block.");

}

private Test2() {

System.out.println("This is the constructor of Test class.");

}

public static void main(String[] args) {

new Test2();

}

}

输出结果:

This is the constructor of Dog class, with age 3

I am a static block.

This is the constructor of Dog class, with age 2

I am a nomal block.

This is the constructor of Test class.

从输出结果验证了上面的理论,并且如果多个相同类型(此处指的是静态和非静态)的变量或块,则按照顺利来初始化。

对于静态的只在class第一次加载的时候初始化,并且初始化一次

本地变量

对于方法内的变量,如果在定义的时候没有初始化,Java会随机赋值,对于没有赋初始值的变量,在使用的时候,编译器会发出警告。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值