• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

null pointer exception

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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);
 
drifter
Posts: 1364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic