0
class LNode {
LNode next;
int value;
}
public class asasasa {
    public static void main(String ar[]) {
         LNode list = new LNode(), list2=list;
         list.value = 9;
         list = list.next;
         list.value = 6;
         list.next = null;
        while (list2.next != null) {
             System.out.println(list2.value);
             list2 = list2.next;
        }
   }

}

* Exception in thread "main" java.lang.NullPointerException at asasasa.main(asasasa.java:10)* Kindly help with the concept and give a simpler code for such linked list


1 Answers1

0

list is never initialized, therefore it is null. Referring to it will always result in a NullPointerException.

ajax992
  • 826
  • 7
  • 15
  • Yeah that's what I meant to say ^ RT – ajax992 Jul 11 '17 at 16:30
  • can You please give a solution to it? – NISHANT BARANWAL Jul 11 '17 at 16:33
  • You say: list= new LNode(); This creates a new node. Then, promptly after, you say list = null; So you created an object and then destroyed it. You cannot reference any object's fields or methods if it is null, because "null" is the concept of nothing. – ajax992 Jul 11 '17 at 16:39
  • LNode list=new LNode(),list2; list2=list; – NISHANT BARANWAL Jul 11 '17 at 16:44
  • but still getting nullpointerexception – NISHANT BARANWAL Jul 11 '17 at 16:45
  • Maybe you've heard of References. In your code now, list and list2 are the exact same object. Any changes you make to list1 will change list2 and vice versa. This is because both variables point to the same object in memory. This _only_ happens with Objects, but never with raw data types (int, double, etc.) Remove the 2 lines that declare list1 and list2 as null. Think of it like this. You tell the compiler, set list1 to nothing. Then you tell the compiler, give me something from nothing, or maybe set something in nothing. What sense does that make? Only the _new_ modifier creates an instance – ajax992 Jul 11 '17 at 16:51
  • LNode list = new LNode(); LNode list2 = new LNode(); In this example, list and list2 are 2 separate, different, objects. LNode list = new LNode(); LNode list2 = list; In this example, list and list2 are the **same** object. Hope this helped. – ajax992 Jul 11 '17 at 16:51
  • but how to insert value in such linked list? – NISHANT BARANWAL Jul 11 '17 at 16:55
  • You are saying list = list.next. List.next does not exist because you never created it. Instead you might wanna say list.next = new Node() – ajax992 Jul 11 '17 at 16:58
  • You're welcome, lmk if you need more help – ajax992 Jul 11 '17 at 17:03