Tutorial :what is shared variable in java


is there any concept of shared variable in java and if it is what is it?


It depends on what you mean as you can "share variables" or rather "share data" in various ways. I take it that you're a beginner, so I'll make it brief. The short answer is yes, you can share variables and below are a couple of ways to do it.

Share data as arguments for parameters in functions

void funcB(int x) {      System.out.println(x);       // funcB prints out whatever it gets in its x parameter  }    void funcA() {      int myX = 123;      // declare myX and assign it with 123      funcB(myX);      // funcA calls funcB and gives it myX       // as an argument to funcB's x parameter  }    public static void main(String... args) {      funcA();  }    // Program will output: "123"  

Share data as attributes in a class

You can define a class with attributes, when you instantiate the class to an object (i.e. you "new" it) you can set the object's attributes and pass it around. Simple example is to have a parameter class:

class Point {      public int x; // this is integer attribute x      public int y; // this is integer attribute y  }  

You can use it in the following way:

private Point createPoint() {      Point p = new Point();      p.x = 1;      p.y = 2;      return p;  }    public static void main(String... args)  {      Point myP = createPoint();      System.out.println(myP.x + ", " + myP.y);  }    // Program will output: "1, 2"  


If you want to share variables between 2 functions, you can use global variables or pass them with pointers.

Example with pointers:

public void start() {      ArrayList a = new ArrayList();      func(a);  }    private void func(ArrayList a)  {      a.add(new Object());  }  


Not sure what this question means. All public classes are shared, all variables can be shared if they accessible through public methods, etc.


In the VB sense, a static field in Java is shared by all instances of the class.

In the classical sense, Java has various RPC, service and database access mechanisms.


use static keyword eg:

private static int count = 1;  public int getCount() {          return count ++;      }  

everytime u call method getCount(), count will continue +1

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »