File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes method question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "method question" Watch "method question" New topic

method question

Mitch Krah
Ranch Hand

Joined: Sep 06, 2004
Posts: 41
I have the following code:

First he compiler made me put the printResults outside of main. I don't understand this??? Why can't I have a method inside of main? Next the compiler will not let me call printResults from inside of main. When I call the printResult method (as shown above), I get an error saying you cannot call a non-static method from a static context???

Pleasa help?

Thank you,

[ edited to preserve formatting using the [code] and [/code] UBB tags -ds ]
[ December 05, 2004: Message edited by: Dirk Schreckmann ]
Paul Santa Maria
Ranch Hand

Joined: Feb 24, 2004
Posts: 236
Hi -

You've actually asked a very important - and, in some ways, very subtle -question. You can get a good, detailed explanation here:

Bruce Eckel ("Thinking in Java, 3rd Ed") explains it as follows:

"[A static method is] the equivalent of a global function (from C)...
It means that there is no 'this' (no per-instance data) for that particular method.

"You cannot call non-static methods from inside static methods (although the reverse is possible", and you can call a static method for the class itself, without any object. In fact, that's primarily what a static method is for."

Please take a look at the JavaDoc for "java.lang.Math". You'll notice that most of the math functions (abs(), sin(), cos(), etc etc) are all static functions. The reason is simple - you shouldn't have to create an entire object just to get the absolute value of a number. You just call ... a "static method": "abs (x)".

'Hope that helps .. Paul Santa Maria
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Try this:
static void printResults(int m, int x, int s, double a) {

Mike Gershman
SCJP 1.4, SCWCD in process
Paul Santa Maria
Ranch Hand

Joined: Feb 24, 2004
Posts: 236
With all due respect, you shouldn't just "try static printResults()..." as you need to understand the (important) difference between static and non-static methods and data.

For purposes of illustration, here's a slightly different example, using non-static methods:

'Hope that helps .. PSM
I agree. Here's the link:
subject: method question
jQuery in Action, 3rd edition