Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

run time Exception | Compile time error

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Second{
public void showData1(){
System.out.println("I m in class Second");
}
}

public class first{
Second q;
public void showData(){
System.out.println("I m in first ");
q.showData1();
}
public static void main(String[] args){
first p=new first();
p.showData();

}
}

sir in the above code it is compiling fine at run time it is throwing an exception that in showData NullPointerException becouse i have decleared a refrence of class Second type well no problem.
when same thing i m doing in main that first p(It is a refrence of type first ) it is leading into a compile time error that variable p might not insialized.But why it is not happning with q? why with q it is throwing an exception allthough here should also be the compile time error. But it is not why?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15490
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because member variables are initialized with default values, and local variables are not.

So the member variable q in class first is initialized with null if you don't initialize it yourself.

The local variable p in the main method isn't initialized with a default value, so the compiler complains that the value isn't initialized.
 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks sir

Arun
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic