对象字段java,什么是初始化的java对象字段?

在Java中,未初始化的字段会自动赋予默认值,如0或null。对于对象引用,如String,其默认值为null。基本类型如int默认为0。然而,依赖这些默认值被认为是不良编程习惯。局部变量则不同,它们必须在使用前明确初始化,否则会导致编译错误。建议在类定义时明确初始化字段,以提高代码的清晰性和可预测性。
摘要由CSDN通过智能技术生成

Is it null for Object type?

class C {

int i;

String s;

public C() {}

}

Will s be always null?

What about simple types as int? What will that be? Zero or an arbitrary value?

What about local variables in methods?

public void meth() {

int i;

}

What is the unitialized value of i?

Relying on such default values, however, is generally considered bad

programming style.

Ok, what do you suggest we do?

class A {

String s = "";

int i = 0;

}

OR:

class A {

String s;

int i;

public A() {

// default constructor

s = "";

i = 0;

}

}

Which is better and why?

解决方案

It's not always necessary to assign a

value when a field is declared. Fields

that are declared but not initialized

will be set to a reasonable default by

the compiler. Generally speaking, this

default will be zero or null,

depending on the data type. Relying on

such default values, however, is

generally considered bad programming

style.

The following chart summarizes the

default values for the above data

types.

Data Type Default Value (for fields)

byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d

char '\u0000'

boolean false

String (or any object) null

Local variables are slightly

different; the compiler never assigns

a default value to an uninitialized

local variable. If you cannot

initialize your local variable where

it is declared, make sure to assign it

a value before you attempt to use it.

Accessing an uninitialized local

variable will result in a compile-time

error.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值