• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

run time Exception | Compile time error

 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks sir

Arun
 
Oh sure, it's a tiny ad, but under the right circumstances, it gets bigger.
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic