This week's book giveaway is in the General Computing forum.
We're giving away four copies of Learning Regular Expressions and have Ben Forta on-line!
See this thread for details.
Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Java Basics  RSS feed

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
}
if(b.equals(null))
{
System.out.println("Its b");
}
}
}
The above program gives following output
Its a
Exception in thread "main" java.lang.NullPointerException
at C.main(C.java:10)
Regards
Asheesh
 
Ranch Hand
Posts: 3143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
asheesh talwar
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx Angela
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!