• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between two type of null checks

 
bjit babu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

let suppose I have a class . and inside that class i am doing a null check.

class Example{

String str="abc";

if ( str ! = null){
//do some thing
}

OR

if(null != str) {
//do come thing
}
}

now my question is what is the difference between that two null check.
and which one hould we use in real time coding.



 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried them? Did you notice any difference?

I believe this sort of thing is a holdover from the C programming language. There, you could have any expression in the if-condition. Basically, there, 0 was false and ANYTHING ELSE was true.

Further, a common programming error was to use the '=' assignment operator when you meant to use the '==' equality operator. So, this was legal (just like it is in java:


However, since the 'value' of an assignment operation was the value being assigned, this was also legal:

Note the difference. The first one checks to see if x is equal to seven, and may be true or may be false. The second one ASSIGNS the value of 7 to x, making the value of that expression 7, therefore ALWAYS TRUE.

this was usually a mistake, but caused endless hours of hunting for bugs.

The recommended way to prevent this was to put the constant first:

since using the assignment operator would cause an error,, since it makes no sense

The upshot and my real point here, is that now, it doesn't really matter. you can write your null check either way, since java will never allow you to do

as it is not legal to test for true/false based on anything but a boolean.
 
Harsha Gedala
Ranch Hand
Posts: 41
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Added to the above reply, I guess following topic will give you more info.

Null Check
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In addition to what Fred said, there is only one way in Java you can get caught by this =/== mistake. That's if you have a boolean variable.

These will compile, but are almost certainly a mistake. Which is one reason (as well as better readability) why it's preferable to use:
 
bjit babu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks everyone.


what i came to know from this discusion is that its a convention coming down to java from c language.
There is no significance if we consider the performance .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic