Need help understanding recrursive and static methods
I'm having trouble understanding the concepts of static methods, and how to call them. Also how recursive methods work through.
for example, take this code:
Code :
public static void recur2 (int n)
{
if(n<=0)
{
return;
}
else
{
recur2(n - 2);
System.out.print(n);
}
}
what does the method call recur2(5) display? Furthermore, this would be easy to just test and see what the result is, but I don't know how to call static methods.
Normally I would create some class and add the line "public static void main(String[] args)" which would be my driver class for whatever class I created to do some problem. So by that method I would create these two classes:
Code :
public class Test{
public static void recur2 (int n)
{
if(n<=0)
{
return;
}
else
{
recur2(n - 2);
System.out.print(n);
}
}
}
Code :
public class TestDriver{
public static void main(String[] args){
System.out.println(recur2(5));
}
}
But that gives me an error saying this recur2(int) is undefined for the type TestDriver
Re: Need help understanding recrursive and static methods
You need to specify in what context that method exists. Static simply means it exists in the context of the class itself, not any particular instance of that class. You can quantify this by qualifying the method with the class name.
Code java:
public class TestDriver{
public static void main(String[] args){
// recur2 belongs to the Test class
System.out.println(Test.recur2(5));
}
}