is there any concept of shared variable in java and if it is what is it?
5 Answers
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"

- 119,724
- 44
- 140
- 158
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());
}

- 2,846
- 6
- 33
- 64
Not sure what this question means. All public classes are shared, all variables can be shared if they accessible through public methods, etc.

- 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
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.

- 48,893
- 5
- 92
- 171