Why java is asking to initialize the variables when it is local(为什么java在本地时要求初始化变量)
问题描述
请看下面的代码.方法 printTest() 正在打印未初始化变量的默认值,但是当涉及到 main 方法时,java 要求进行变量初始化.谁能解释一下为什么?
Please see the code below. The method printTest() is printing the default value of the uninitialized variables but when it's comes to main method java is asking for variable initialization. Can anybody explain why?
public class Test1 {
public static void main(String[] args) {
int j;
String t;
System.out.println(j);
System.out.println(t);
}
}
public class Test2 {
int i;
String test;
public static void main(String[] args) {
new Test().printTest();
}
void printTest() {
System.out.println(i);
System.out.println(test);
}
}
推荐答案
局部变量主要用于中间计算,而实例变量应该携带用于未来和中间计算的数据.Java 不强制初始化实例变量并允许默认值,但对于局部变量,开发人员调用它来分配值.所以为了避免错误,你需要初始化局部变量.
Local variables are used mostly for intermediate calculations whereas instance variables are supposed to carry data for calculations for future and intermediate as well. Java doesnt forces to initialize instance variable and allows default value but for local variables its the developers call to adssign the value. So to avoid mistakes you need to initialize local variables.
这篇关于为什么java在本地时要求初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么java在本地时要求初始化变量


- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01