Home > OS >  Why do we use Static keyword for initializing a variable
Why do we use Static keyword for initializing a variable

Time:03-03

I'm an absolute beginner. I have a doubt regarding this recursive program which prints Fibonacci series.

My doubt is ; why they used static keyword to declare the integer variable n1, n2 and n3 in the 2nd line of code ?

Also why they use static void for the recursive function printFibonacci(int count) in the 3rd line of code?


class FibonacciExample2{
 static int n1=0,n2=1,n3=0; 
 static void printFibonacci(int count)
{

if(count>0){

n3 = n1   n2;

n1 = n2;

n2 = n3;

System.out.print(" " n3); printFibonacci(count-1);

}

}

public static void main(String args[]){

int count=10;

System.out.print(n1 " " n2);//printing 0 and 1 printFibonacci (count-2);

}

}



CodePudding user response:

Static members are present in all the instantiated objects. You can see static members as members shared by all objects of a certain class. You should be careful when modifying a static member as this member will be modified in all objects. Static methods are methods that can be called without an object. In your case FibonacciClass.method(). However in static methods only static members can be used as these are not dependent upon an object.

CodePudding user response:

The function for the Fibonacci series is here

So you don't need to create static fields for it

int fibonacci(int x){
if (x <= 1){
  return x;
}
return fibonacci(x-2)   fibonacci(x-1);

}

it works like this if you provide 5

       fibonacci(3)                                 fibonacci(4)
fibonacci(1)   fibonacci(2)             fibonacci(2)                fibonacci(2)
              /    \                     /       \                      /  \
    fibonacci(1)   fibonacci(1)  fibonacci(1)   fibonacci(1) fibonacci(1)   fibonacci(1)

add all ones and the answer will be returned. check how methods are working in stack memory to Cleary understand this.

  • Related