• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Calling method from static main method

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So I've searched the forums, the internet and my SCJP book but have never really understood this concept and I'm looking for someone to fill in the missing piece it seems.

class Example {
public static void main(String[] args){
int x = 10;
final int y = new Example().go(x); // works
System.out.print(go(y)); // doesn't work
}

int go(int z) { return z++}
} // end class

I understand static is a singleton kept on the stack instead of the heap (if I remember right) but importantly it's not instantiated. So I get that Example when instantiated has this single main method for all subsequent instances, right? So I guess it doesn't know which instance to call go() on?

If that paragraph reads funny it's because I'm iffy on the whole thing. I guess I can't get out of my head how the JVM knows that a static method has already been created and not to create another one when another instance is created. I've got this picture in my head of all these objects floating around in the heap with this single static reference to main and I'm just wondering if there is a layman's terms on how static works at a low level. Any pointing to web resources would be greatly appreciated.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mr justin, it is a simple thing. now you see

First one:

final int y = new Example().go(x); // works

In this statement works well. Because you create an object (using "New") and then access the method "go()". I remember you java is an object orient language.so everything is an object.

Second one:

System.out.println(go(y));
In this statement you directly called the go method. It is not possible because java does not allowed to declare the method without any object or that method should be static. so your program gives compiler error.

Now you try this code: it will execute properly

class Example
{
public static void main(String[] args){
int x = 10;
final int y = new Example().go(x); // works
System.out.print("value" + go(y)); // doesn't work

}

static int go(int z)
{
return z++;
}
}

here i have given the solution to you what i know. so you have any doubt in my explanation then reply me. ok bye
 
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


1.The statement is in error because....
When you call an instance method(here, go()) without using a specific instance, the method is invoked on an implicit object "this".
You cannot refer to "this"(the implicit object) from within a static method(here, p.s.v.main()).

2. Static methods, as the name implies, build a static context...
meaning they should not be affected by the "properties" of an object(i.e. the instance fields..these fields can be called dynamic since they have different values for every object). Static methods can only refer to static fields of the class.So, when you have a method that you want to export, which is not affected by instance fields, you should declare it as static.

3. Static fields are not related to object instances but classes...
When a class is loaded, the code for its methods (both instance and static) are are copied into the JVM's memory. The memory used for storing any instance's fields is allocated when the instance is created, and released when the instance is Garbage Collected. Static fields are part of the class, and their memory is allocated when the class is loaded.
[ December 17, 2008: Message edited by: Monu Tripathi ]
 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sounds right Sivakumar, just want to be a little more specific about something.

when you declared

final int y = new Example().go(x);

you created an Example Object and called that Objects method go sending the go method the parameter x.

a value is assinged to y and then the Object is lost to the GC() because there are no refrence variables of type Example.

There would have been had you say done this

Example newExample = new Example();
final int y = newExample.go(x);

Note for this to work, you would need to change the code in

System.out.print("value" + go(y));
to
System.out.print("value" + newExample.go(y));

Changing the modifier to static on

"go(int z)" to
"static int go(int z)"

allows go() to be called even if there is no Object of class Example created. Instead, when the virtual machine loads and calls the static method in main, a static blueprint of Example is built and all static variables and methods are created in that blueprint,then, if you make an Object out of the class (by invoking "new" ie new Example) then all the nonstatic portions of class Example are created.

In summary, unless you are trying to access a static method or field, you must make an instance of a Class Object (new Example) before you can access a method or field in the Class. That Object must also not have become eligible for GC(); either.

This was the largest misunderstanding I had with the Java language, I didn't explain all the complexities, because there are still other constructors and static blocks and init statements that will fire before or after the statics. You need to figure out the complete order of class building/instantiation in java.
[ December 19, 2008: Message edited by: Chadd Franck ]
 
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
pay attention please!

to static only static!
this line you are calling one method that is not static, then this code do not compile. It necessary create a object to call one method non-static.

this line you created one object and after you called the method, then there is not problem here!

Then do not forget to static only static! do not exist other rule to it.
 
Ranch Hand
Posts: 826
Eclipse IDE Oracle Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Justin Bleach:
I guess I can't get out of my head how the JVM knows that a static method has already been created and not to create another one when another instance is created.



A static member is one pre class and is created when the class is 'first' loaded not when an instance of that class is created.
Find out when a class is loaded... during compiling or when the class is run?

Hope this helps.
 
Justin Bleach
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks all for your detailed explanation. I believe it makes more sense to me now and I can finally put it behind me ;-)
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don't try making anything static so you can call it from the main method. Call it from objectReference. Use the . operator, exactly like in the first few lines of code which Chadd Franck showed.
[ December 18, 2008: Message edited by: Campbell Ritchie ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic