Operator Precedence in Java

June 17, 2008

Context:

Taken by surprise when….

System.out.println( "~~~~~~~~~" + fooObject != null );
System.out.println( "~~~~~~~~~" + fooObject );

… came up with the following output…

true
~~~~~~~~~ null

… why on earth was the compiler saying (first line) that fooObject was NOT null but then going on to print it as a null !! And to top things up… why on earth was ‘~~~~~~…’ missing !?

Solution:

In short… operator precedence !! Since the operator ‘+’ has a higher priority in comparison to ‘!=’, the compiler was actually treating…

"~~~~~~~~~~~~~~~~~~~~~~~~~~~" + fooObject

… as the left operand to the operator ‘!=’ and null as it’s right operand. As if….

("~~~~~~~~~~~~~~~~~~~~~~~~~~~" + fooObject) !=  (null)

… resulting in the missing ‘~~~~…’ and a ‘true’ being printed although it should have been false (since fooObject was null). So the statements were restructured as ….

System.out.println( "~~~~~~~~~" + ( fooObject != null ) );
System.out.println( "~~~~~~~~~" + fooObject );

… resulting in ….

~~~~~~~~~ false
~~~~~~~~~ null

…. MUCH better. Sometimes the most basic of things can be overlooked !!

Wa Allahu ‘Alam

Entry Filed under: Java. Tags: , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Recent Comments

Categories

Top Posts

Links

Blog Stats

Meta