• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

static

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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);
}
}
}
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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

 
Anderson gave himself the promotion. So I gave myself this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic