Default Values - Java Clarification -
why aren't default values assigned variables, haven't been initialized within class main function???
class test { public static void main(string[] args) { int x;// x has no default value string y;// y has no default value system.out.println("x " + ); system.out.println("y " + ); } }
whereas default values assigned in case variables remain uninitialized in class without main function.
class student { string name; // name has default value null int age; // age has default value 0 boolean issciencemajor; // issciencemajor has default value false char gender; // c has default value '\u0000' int x; string y; }
be aware code in question represents different situations. in first case, variables local , exist inside main()
method. in second case you're declaring instance attributes, not local variables.
in java, attributes initialized automatically default values. in methods, in main()
method, must explicitly provide initialization value variables declared locally inside method.
this explained in java language specification, section §4.12.5:
each class variable, instance variable, or array component initialized default value when created (§15.9, §15.10)
each method parameter (§8.4.1) initialized corresponding argument value provided invoker of method (§15.12)
each constructor parameter (§8.8.1) initialized corresponding argument value provided class instance creation expression (§15.9) or explicit constructor invocation (§8.8.7)
an exception parameter (§14.20) initialized thrown object representing exception (§11.3, §14.18)
a local variable (§14.4, §14.14) must explicitly given value before used, either initialization (§14.4) or assignment (§15.26), in way can verified using rules definite assignment (§16)
to see several reasons why local variables not initialized automatically, please take @ previous question.
Comments
Post a Comment