java - Not throwing Null Pointer Exception for Object Type Even default value is NULL -
package sample; public class sample4array { public static void main(string[] args) { int a[] = new int[10]; system.out.println(a[1]); for(int i=0;i<a.length;i++) { system.out.println(a[i]); //default value 0 } integer x[] = new integer[10]; for(int i=0;i<x.length;i++) { system.out.println(x[i]); //default value null & not throwing exception. } } }
to consider; first loop returns 0 default value & second loop default value null it's not throwing exception
when declare reference variable (i.e. object) creating pointer object. consider following code declare variable of primitive type int:
int x; x = 10;
in example variable x int , java initialize 0 you. when assign 10 in second line value 10 written memory location pointed x.
but, when try declare reference type different happens. take following code:
integer num; num = new integer(10);
the first line declares variable named num, but, not contain primitive value. instead contains pointer (because type integer reference type). since did not yet point java sets null, meaning "i pointing @ nothing".
in second line, new keyword used instantiate (or create) object of type integer , pointer variable num assigned object. can reference object using dereferencing operator
. (a dot).
the exception asked occurs when declare variable did not create object. if attempt dereference num
before creating object nullpointerexception
. in trivial cases compiler catch problem , let know "num may not have been initialized" write code not directly create object.
Comments
Post a Comment