Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null question

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A {
static String a;
public static void main(String[] args)

{
System.out.println("A1a is:" + a==null);
}

***
All is prints is false. It does not print 'A1a is:' WHy is this? If I do...
System.out.print("A2a is:" );
System.out.println(a==null); It prints..

'A2a is:true' that is what I expected, but the first one I am still confused about.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anthony Smith:
All is prints is false. It does not print 'A1a is:' WHy is this?

Operator precedence. Your code as is checked if the String "A1a is:" + a is null.
Try using System.out.println("A1a is:" + (a==null)); instead.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it is doing this:
("A1a is:" + a) == null
try changing your code to this:
"A1a is:" + (a==null)
You have to remember the order that operators are invoked.
 
Eureka Jana
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ha Ha,
I am going to become the precedence king.I just now answered one question(Question about multiple assignments) regarding the precdence and yet again:
System.out.println("A1a is:" + (a==null));
Before that + has higher precedence than == so it concates a with "A1a is :" and then checks for null which is false.If you put the backet then it will work fine.
Got it,
Regards,
Jana
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now, wouldn't a "precedence king" post replies to questions preceding all other replies?
 
Eureka Jana
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hummmmmmm.....
Oh ho Actually I missed that by time constraint.I had a work here after I tried to reply.So I missed the train.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
3 replies within 6 minutes that all agree. Not bad.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic