-2

I have a question that why this code is giving me an error while i am trying to call a static function defined within a class through a class reference and it makes possible to call a static function when i am creating an object of a reference.

public class Example
{
public static void main(String args[])  
{
Example t;
t.method();//getting error
Example t1=new Example t1();
t1.method();//it runs successfully
}
public static void method()
{
System.out.println("NullPointerException");
}
}
varun
  • 472
  • 4
  • 8
  • 24

4 Answers4

3

You should not call a static method on an instance of the class. You should use name of the class itself:

Example.method()

Also when you declare a variable and left it without initialization, It will not be initialized (Local variables) and when you try to call a method on it, you will get error

frogatto
  • 28,539
  • 11
  • 83
  • 129
  • _You can not call a static method on an instance of the class._ You can, but you shouldn't. – ggovan May 19 '14 at 12:23
  • @ggovan Yes you are right, I will edit it – frogatto May 19 '14 at 12:23
  • _Also when you declare a variable and left it without initialization, It will be initialized with null_. Only on instance variables, not locals. Hence the compiler complaint that the questioner is getting. – ggovan May 19 '14 at 12:25
  • @ggovan My mean is on non-primitive types that inherited from `Object` – frogatto May 19 '14 at 12:29
  • @ggovan I've googled and read some articles, yes you are right it is not null – frogatto May 19 '14 at 12:38
1

t is not initialised when you call t.method();. You therefore get a NullPointer on the non-instanciated t object.

Harry
  • 1,362
  • 12
  • 19
1
public class Example
{
public static void main(String args[])  
{
Example t;       // t points to nothing (not even null, actually, its as if it doesn't exist at all)
 t.method();//getting error  // how can you call a method of example with a reference to nothing.
Example t1=new Example t1(); // t1 points to an Example object.
t1.method();//it runs successfully // works fine , but is not suggested as the method is at class level, not at instance level. use Example.method() 
}
public static void method()
{
System.out.println("NullPointerException");
}
}
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • When `t.method()` is first called `t` is not null! It has not been initialised. If `t` were null then the code would compile and the method would be called correctly as it is a static method call. – ggovan May 19 '14 at 12:30
  • @ggovan -Thanks.. Ya.. Pretty dumb of me to use "null"... :) – TheLostMind May 19 '14 at 12:35
0

that is possible, but if you want to call anything through a reference, you need to instantiate it first.

do remember also: Java has methods, not functions. So, change:

Example t;

in

Example t = new Example();

and try again

Perneel
  • 3,317
  • 7
  • 45
  • 66
Stultuske
  • 9,296
  • 1
  • 25
  • 37