为什么Javac抱怨未初始化变量? [英] Why does javac complain about not initialized variable?

查看:53
本文介绍了为什么Javac抱怨未初始化变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于此Java代码:

String var;
clazz.doSomething(var);

为什么编译器会报告此错误:

Why does the compiler report this error:

变量'var'可能尚未初始化

Variable 'var' might not have been initialized

我认为所有变量或引用都被初始化为 null .为什么需要这样做:

I thought all variables or references were initialized to null. Why do you need to do:

String var = null;

??

推荐答案

实例和类变量初始化为null(或0),而局部变量不初始化.

Instance and class variables are initialized to null (or 0), but local variables are not.

请参见§4.12.5 JLS 的详细说明基本上是一样的东西:

See §4.12.5 of the JLS for a very detailed explanation which says basically the same thing:

程序中的每个变量都必须有一个值,然后才能使用它的值:

Every variable in a program must have a value before its value is used:

  • 每个类变量,实例变量或数组组件在创建时均使用默认值初始化:
    • [从所有默认值的清单中剔除]

    这篇关于为什么Javac抱怨未初始化变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆