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 static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static" Watch "static" New topic


Jimmian Lin

Joined: May 31, 2008
Posts: 16
I was wondering why in the following code for factorial, I needed to declare the factorial and iter methods static.

public class example_fact2{
public static void main(String[]args){
public static int factorial(int n){
return iter(1, 1, n);
private static int iter(int counter, int product, int n){
if(counter> n){
return product;
return iter(counter+1, product*counter, n);
Juva Yuva

Joined: Dec 18, 2008
Posts: 17
Originally posted by Juva Yuva:

Thats because you declared the method (factorial) as Class method. And since main is static , methods can be called directly . Otherwise It can be accessed in non-static way , by creating instance of the class.

1) Try creating an instance of the class in the main method , call the factorial method with the instance.
2)And remove the static modifiers from the methods
I agree. Here's the link:
subject: static
It's not a secret anymore!