The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
July 2000



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.



Posted by sanjay singh on July 19, 2000 at 11:18 AM

I want to know the explanation for a situation i am facing while running a small java
program . I am trying to run a small java program
using String and getting a result and I am not able to convice myself
Can you please take a little pain in answering my question . Let me write down my
java proggram . It is 15 line program . I am going to metion line
number in my question .

My java source Code :

1 public class test9 {

2 String s1 = null ;
3 String s2 = " ";

4 public void amethod()
5 {
6 if (s1.equals(s2))
7 System.out.println("equals");
8 }

9 public static void main(String args[])
10 {
11 test9 a = new test9();
12 a.amethod();

13 }
15 }

My question: Here is the situation For the above code
I am getting a NullPointerException as follow while running it.
C:\jdk1.2.1\bin>java test9
Exception in thread "main" java.lang.NullPointerException
at test9.amethod(
at test9.main(

But it does not throw NullPointerException when String S1 = " " is mentioned
at line# 2 and String S2 = null is mentioned at line# 3;

Why is it so ?
The second scenario should also give NullPointerException.
Does the left hand side of equals() method have to be initialized ?

for more detail reference ..I do not get NullPointerException
when I change my java program as follow .

Modified program : Which runs fine . does not throw NullPointerException why ?

public class test9 {

String s1 = " ";
String s2 = null;

public void amethod()

if (s1.equals(s2))


public static void main(String args[])
test9 a = new test9();


If my question is not clear Please send me a mail asking for detail.

  • RE:String Kishori Sharan July 19, 2000 at 5:20 PM (0)

Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us