views:

441

answers:

4

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

A: 

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
A: 

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

fastcodejava
they can be shared as protected and private too as long as the calling method has access to them.
Spoike
A: 

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
A: 

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