I often set a primitive or object to an initail value of null, then try to test if it has received a "better" value yet. I want to write something like
Most of the time the compiler complains about my structuring the first 10x I try to write the loop test. Once I figure out how to do it, months go by and the next time I can't remember how it worked. Can someone please tell me what kinds of values (int, String, etc.) can be set to null and tested for a null value?
Joined: Sep 25, 2003
To compare objects you need to use the .equals method. Ususally when I am checking for null, I am checking a string so I go like this:
That seems to work for me. I do not clearly remember why I started doing it this way, but I think that I started doing it that way because I read an article or something that said that null is not considered an object in java. Lisa M.
author and iconoclast
Lisa -- -- Sorry, but you should use "==" to compare against null, and the String "null" is absolutely not the same as the literal value null. Have a look at the rest of this answer. Elouise -- please ignore the previous answer! The only thing wrong with your code is here
The code in doSomething() is correct and is the right thing to do. Now, as far as what kinds of values need to be tested for null: objects references do, primitives don't. The primitive types in Java are byte, short, char, int, long, float, double, and boolean. Strings aren't primitives, they're objects, as is everything else not on that list.
My code was unclear: all of that code snippet takes place inside class SomeObject. That's why I had a constructor. Every instance of "SomeObject" has its very own instance of an Object called "nextObj". My intention was to build a singlely linked list of Object (class) objects. My method "doSomething" needs to test whether nextObj is (still) null so I know whether there are more elements in my list. What I'd like to check on and finally get down in writing is this: Can a primitive be given/be tested for a value of null? If so, how would you write the code? Can an object be given/be tested for a value of null? If so, how would you write the code? [ November 04, 2003: Message edited by: Elouise Kivineva ]
Joined: May 05, 2000
What I'd like to check on and finally get down in writing is this: Can a primitive be given/be tested for a value of null? No Can an object be given/be tested for a value of null? Yes.