• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Primitive type and the NULL value

 
David A King
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question regarding the primitive data types. I understand that it is not allowed to assign a null value to a primitive type like this, int myval = null;
But when I declare a primitive type like int myval;  and Don't assign a value at the time of declaration, isn't the value of the primitive null?
AKA: can I test that variable for  the null value like if(myval == null).?

Or am I off base?

Thanks,

Dave
 
Henry Wong
author
Marshal
Pie
Posts: 22096
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David A King wrote:
But when I declare a primitive type like int myval;  and Don't assign a value at the time of declaration, isn't the value of the primitive null?


Depends on the type of variable. If it is a static or instance variable, the default value of a primitive int is zero. If it is a local variable, then the compiler will complain if you try to use it prior to assigning it a value.

Henry
 
David A King
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry,
Yes, I should have been more specific. I realize that an instance primitive will get a default value. In the case of a local method variable though, can I test it for null?
Or will I just get an error when I try to refer to the non-initialized primitive?
 
Henry Wong
author
Marshal
Pie
Posts: 22096
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David A King wrote: In the case of a local method variable though, can I test it for null?
Or will I just get an error when I try to refer to the non-initialized primitive?


Well, to "test" it, you will have to use it, and ... that, of course, is a compiler error (as already mentioned). And this is, in addition to the compiler error that null is only for object references, and not primitives.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic