java检查变量是否定义,Java检查变量是否已初始化

So I'm pretty new to Java. Been taking a class at my college, this first semester is focussing on getting the syntax down and some of the basic ideas right while using a java library called ObjectDraw. Next semester we're going to start getting away from ObjectDraw and into core Java some more. Anyways I have run into a few problems where I need to use something similar to php's isset function. I know php and java are EXTREMELY different so I shouldn't try to compare them but php is my only basis of previous knowledge on something similar to programming. I just wondered if there was some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. For example...

if(box.isset()) {

box.removeFromCanvas();

}

So far I've had this problem where I am getting a run-time error when my program is trying to hide or remove an object that hasn't been constructed yet.

解决方案

Not really - there's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned with its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {

box.removeFromCanvas();

}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {

box.removeFromCanvas();

// Forget about the box - we don't want to try to remove it again

box = null;

}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile

String x;

System.out.println(x);

// Will compile, prints null

String y = null;

System.out.println(y);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值