0

I'm searching for modifier in Java that has the same exact purpose as Static in C++ has. I mean, that variable is only initialized once in function, then every time we call that function again, values from the previous call are saved. That's how code looks in C++:

void counter()
{
    static int count=0;
    cout << count++;
}

int main()
{
    for(int i=0;i<5;i++)
    {
        counter();
    }
}

and the output should be 0 1 2 3 4, is there something that has the same purpose, but in Java?

WPKS
  • 15
  • 2

3 Answers3

0

hope this will help..// u need to create a constructor first.

 public class answer2 {
 static int count =0;
 answer2() {
    System.out.println(count);
    count++;
}
public static void main(String[]args) {
    for(int i=0;i<5;i++) {
    new answer2();
    }
}
 }
0

just define static variables as a class member normally. java developers promote object oriented programming so even your main function is a method defined in another class whose name is same as your program name.

now for your question if you want to define a static variable:


    public class abc

    {
       public static int count = 0;
    }

    public class xyz
    {
       public void increment()
       {
           abc.count++;
       } 

       public static void main(String[] args)
       {
          System.out.println(abc.count);
          increment();
          System.out.println(abc.count);
       }
    }

Hope it helps.

Anand
  • 361
  • 1
  • 9
  • 23
  • I needed to change something in code, because it didn't want to compile. I've made abc static, count deleted public, xyz static, increment static. Only that way it wanted to compile. – WPKS Sep 29 '19 at 14:48
0

looks like you are starting with java. To help you understand the concept i wrote the same code with comments for your understanding.

package yourXYZpackage;

public class yourABCclass{

//Declare in class body so your methods(functions) can access 
//and the changes made will be global in C++ context.  
  static int count=0; 

  void counter()
  {
        count = count++;
        System.out.println(count); 
        //thats how you can display on console
  }
  //this is the main method like C++
  public static void main(String[] args){
      
      for(int i=0;i<5;i++)
      {
          counter();
      }
  }
}