This is a program to assign global variable with command line args:
class B
{
int x;
B ref;
B (int data)
{
this.x=data;
}
}
public class MyClass {
public static void main(String args[]) {
B b1 = null;
for (String s1 : args)
{
if (b1 == null)
{
b1 = new B(Integer.parseInt(s1));
}
else
{
B element = b1;
while (element != null)
{
element=element.ref;
}
element.ref=new B(Integer.parseInt(s1));
}
}
B element=b1;
while (element != null)
{
System.out.println(element.x + ",");
element=element.ref;
}
}
}
-the program is throwing one exception;i.e; Exception in thread "main" java.lang.NullPointerException: Cannot assign field "ref" because "<local6>" is null
at MyClass.main(MyClass.java:27).
this exception was caused because it should have been "element.ref" in the validation statement of the while loop which is inside the else block.
Can someone explain me why?