سؤال

Hi I am having the following code. when i am using instance variables i am getting the output as follows(Default Values)

int value: 0
float value: 0.0
String value: null
Static int value: 0

But if i try declare the local variable and print the default value it is giving an error that the variable should be initialized. Can any one explain me the reason please?

public class DefaultValues {
  int a;
  float b;
  String c;
  static int d;
  public static void main(String[] args) {      
    int e;                                     // <----
    DefaultValues dv = new DefaultValues();
    System.out.println("int value: "+dv.a);
    System.out.println("float value: "+dv.b);
    System.out.println("String value: "+dv.c);
    System.out.println("Static int value: "+d);
    System.out.println("local int value: "+e); // <----
  }
}
هل كانت مفيدة؟

المحلول

Only instance variables, static(Class) variables and array components are initialized to default values.

Local variables cannot be used unless they are initialized as they are not assigned default values.

نصائح أخرى

From Java Language Specification 3.0, 4.12.5 Initial Values of Variables:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified by the compiler using the rules for definite assignment (§16).

We may have uninitialied local vars but compiler will not allow to use unless we explicitly intialize them. This is Java language rule. See JLS 4.12.5. Initial Values of Variables http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html

•A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).

For Class members(variable) JVM will put the default values or initialize it by default value, for a local variables it makes you assign and initial value before accessing the variable.

From Doc :

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.

You can check the Default Values of different datatype in Primitive Data Types for more information about the class members default values.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top