Meaningless Drivel is fun!*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static" Watch "static" New topic
Author

static

Jimmian Lin
Greenhorn

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){
System.out.println(factorial(7));
}
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;
}
else{
return iter(counter+1, product*counter, n);
}
}
}
Juva Yuva
Greenhorn

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
 
wood burning stoves
 
subject: static
 
Similar Threads
Can't Break Out of a Loop
Recursion
recursion situation baffles me
BigInteger Power/Exponent BigInteger
Qa dd'rouy Again