Jagannath
Generics
1 Answer(s)      2 years and 8 months ago
Posted in : Java Beginners
public class A {
  int i;
  int j;
  void funA()
  {
    i = i+1;
    System.out.println(i);
    j = j+1;
    System.out.println(j);
  }
}

......................................................................

public class Demo<G> {
  G x;
  public static void main(String[] args) {

  Demo<A> d3 = new Demo<A>();
  try
  {
    d3.x.i = 5;//why Null pointer Exception
  }
  catch (Exception e) {
    e.printStackTrace();
  }
 }
}
Advertisement
View Answers

December 31, 2012 at 3:20 PM


Hi jagan,

Before you have assign the value for i, you should declare x object explicitly with new operator d3.x = new A(); d3.x.i = 5; Now null pointer exception won't come.

public class Demo<G> {
  G x;
  public static void main(String[] args) {

  Demo<A> d3 = new Demo<A>();
  try
  {
    d3.x = new A();
    d3.x.i = 5;//why Null pointer Exception
  }
  catch (Exception e) {
    e.printStackTrace();
  }
 }
}

Please try with this code.










Related Tutorials/Questions & Answers:
Advertisements
eraser type generics in java
eraser type generics in java  Explain eraser type generics in java with example
Why Generics was introduced in Java?
Why Generics was introduced in Java?  Hi, Why Generics was introduced in Java and what is was its motive? Thanks   Generics were... for compile time type checking. Read the tutorial for more details of Generics