Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem in NullPointerException  RSS feed

 
Randika Isuru
Ranch Hand
Posts: 38
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

these days i'am try to understand Java Generics and collection part i'am still in beginner for this section. i wrote a code using HashMap.. this is my code it is too long code but my problem is occur in small piece in this code. but i decide to put whole code then i can tell your all to what is my problem exactly.



when i run this code i get output something like this



E:\Education\OCJP Practicals\MyTest\Example HashMap>java ExHashMap
null
HI
3 : HI
2 : Two
10 : Ten
1 : One
9 : Nine
8 : Eight



900
Exception in thread "main" java.lang.NullPointerException
at ExHashMap.main(ExHashMap.java:51)




my problem is occur in this line



actually i write above piece of code to get output "null" i wish to print command prompt "null" just like my 1 attempt (see line one of my out put). but unfortunately i get NullPointerException

i try to understand why this give me a NullPointerException but i'am unable to understand that i need your help to solve this problem..

one more thing when i comment this two lines and compile and run this code again it is works properly...

but if we consider this lines



when i do this without casting it is also give me a NullNointerException. when i cast it to long itz works. that why i do the same thing for 7 (preceding piece of code). but it's still give me a NullPointerException..
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer to your question lies in unboxing. Read this:

http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Now, with this line:

The right hand side evaluates to null as there is no entry in map2 with the key value 7. However, you are assigning the result to a primitive long, not a wrapper type Long. So, in order to assign the Long reference to a primitive long, the value is unboxed. As this value is null, a NullPointerException occurs.

 
Randika Isuru
Ranch Hand
Posts: 38
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much James Boswell now i get the point thanks again...
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No problem Randika.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!