Two Laptop Bag
The moose likes Beginning Java and the fly likes Java Basics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java Basics" Watch "Java Basics" New topic

Java Basics

asheesh talwar
Ranch Hand

Joined: Dec 10, 2000
Posts: 31
I am confused why I am getting the following output when
I run this program ,can any one please give me explanation for this o/p.
class C{
static String a;
static String b;
public static void main(String[] args)
if(a == null)
System.out.println("Its a");
System.out.println("Its b");
The above program gives following output
Its a
Exception in thread "main" java.lang.NullPointerException
at C.main(
Angela Poynton
Ranch Hand

Joined: Mar 02, 2000
Posts: 3143
You are geting the exception because when you call the equals method it is expecting an object as an argument "null" is not an object.
First when you used if (a == null) you were testing the value of a.
when you used if(b.equals(null)) you were asking if b is pointing to the same object as null ... which is not possible.
This is an example of how the different comparators work on String objects. Remember if you create a String using:
String x = "hello";
Then create another String like this
String y = "hello";
x & y will point to the same String object!

[This message has been edited by Angela Poynton (edited December 13, 2000).]

Pounding at a thick stone wall won't move it, sometimes, you need to step back to see the way around.
asheesh talwar
Ranch Hand

Joined: Dec 10, 2000
Posts: 31
Thanx Angela
I agree. Here's the link:
subject: Java Basics
It's not a secret anymore!