Java中的变量如果没有赋值,成员变量默认被初始化,局部变量则不会。

 

对于成员变量 int a;         // a的初始值为0

如下例中的成员变量a,b,c,d

public class VariableInitialValue {

	public static void main(String args[]) {

		TestVariable obj = new TestVariable();

		System.out.println("a="+obj.a);
		System.out.println("b="+obj.b);
		System.out.println("c="+obj.c);
		System.out.println("d="+obj.d);

	}
}

class TestVariable {

	int a;
	char b;
	float c;
	String d;
}

 输出结果为:

Java变量的初始值

对于局部变量int a;          // a默认没有初始化

对没有初始化的变量进行操作,java编译器会给出错误警告。

如下例中的局部变量a,b

public class VariableDeclaration {

	public static void main(String args[]) {

		System.out.println("Examples of variable declaration");

		int a;
		System.out.println("a="+a);

		String b;
		System.out.println(b);

	}
}

 

错误信息:

The local variable a may not have been initialized

The local variable b may not have been initialized

 

相关文章:

  • 2021-12-05
  • 2022-01-23
  • 2021-07-09
  • 2021-11-29
  • 2021-09-20
  • 2022-12-23
猜你喜欢
  • 2021-12-05
  • 2021-11-29
  • 2022-12-23
  • 2018-09-07
  • 2021-11-29
相关资源
相似解决方案