-3

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

Narayan
  • 6,031
  • 3
  • 41
  • 45
Vipul
  • 2,637
  • 6
  • 25
  • 28

5 Answers5

1

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"
Spoike
  • 119,724
  • 44
  • 140
  • 158
1

Use static keyword, example:

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

Everytime you call method getCount(), count value will increase by 1

barbsan
  • 3,418
  • 11
  • 21
  • 28
ggDeGreat
  • 1,098
  • 1
  • 17
  • 33
0

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());
}
Zian Choy
  • 2,846
  • 6
  • 33
  • 64
0

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

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • they can be shared as protected and private too as long as the calling method has access to them. – Spoike Nov 08 '09 at 12:34
0

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.

Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171