aspose file tools*
The moose likes Beginning Java and the fly likes run time Exception | Compile time error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "run time Exception | Compile time error" Watch "run time Exception | Compile time error" New topic
Author

run time Exception | Compile time error

Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
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

Joined: Aug 16, 2005
Posts: 14350
    
  22

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
Thanks sir

Arun
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: run time Exception | Compile time error