Originally posted by srinivas bolloju:
can anybody help ....in main(),if i write below code....
1)why does it give nullpointerexception......
2)if at all it gives an exception.....why at runtime?
3)generally what is the point behind throwing exception at compile and runtime?
String vas[] = new String[5];
String str = vas[0].toUpperCase();
System.out.println(str);
1. An array of 5 String is created. Each element of the array is null at this point. (Default initialization: Arrays of objects are null, arrays of boolean are false, other primitives are zero, did I forget any?) Then you try to use one of the null Strings, so you get nullpointer exception.
2. The error is at runtime because it doesn't determine whether you initialized the String before you tried to use it.
3. Generally speaking, when the compiler knows a rule has been broken you'll get the error at compile time. When it depends upon what your program does you'll get the error at run time.
Perhaps someone else will elaborate on this, I'd recommend study on this topic.