• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why NulllPointer Exception ?  RSS feed

 
Dishi Jain
Ranch Hand
Posts: 46
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the below code :



It gives :
Exception in thread "main" java.lang.NullPointerException : Line 5

Why is it giving NPE? Isnt the variable defaulted with 0.0f? Also, I am not performing any dot operation, it's just a multiplication operation.
Thanks.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Zero would be the default value for the primitive "float", but the default value of all object references is null.
 
Xander Jacob
Greenhorn
Posts: 13
Java Netbeans IDE Netscape
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java is highly case-sensitive. In Line 2, you created a Float object. In Line 5, you created a float primitive that referred to a Float object. To fix this, just de-capitalize the Float in Line 2.

Otherwise, if you are a subclass of Xander Jacob (me), you'll go the hard way and use that Float object. The details are in Java's Float page.
In short, the Object form is created with a float value inside. Right now, your i Float is a null. Initialize it with
.
Refer to it with

but that's the hard way. Don't capitalize Line 2 and you'll be golden
 
Xander Jacob
Greenhorn
Posts: 13
Java Netbeans IDE Netscape
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, yeah. Your original question is why nullPointerException.
Your Float i was a null. It did not equate to anything, so using it would come up with a null pointer exception.
 
Siddarth Cherukumudi
Ranch Hand
Posts: 36
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The reason why you were getting NPE(NullPointerException) is that you expected the instance variables to be given default values, thats what happening exactly
but float and Float are not the same, one is datatype and other is nothing but a wrapper class.

The variable of type class gets the default value null

thats the secret behind the Infamous NPE

HIH
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!