General discussion

Locked

Related Java Prog, Please explain the pr

By abdulmajeed_mam ·
import java.io.*;

public class TestVar
{
public static void main(String args[])
{

TwoKinds obj1 = new TwoKinds();
TwoKinds obj2 = new TwoKinds();
System.out.println();
System.out.println("Object1 data");
obj1.dispVar();
System.out.println("Object2 data");
obj2.dispVar();
System.out.println();
obj1.x = 500;
obj1.y = 500;
System.out.println("Object1 data now");
obj1.dispVar();
System.out.println();
System.out.println("Object2 data now");
obj2.dispVar();
System.out.println();
}
}

/**
Object1 data
x is equal to 10
y is equal to 50

Object2 data
x is equal to 10
yis equal to 50


Object1 data now
x is equal to 500
y is equal to 500


Object1 data now
x is equal to 10
y is equal to 500*/
--------------------------------------------class TwoKinds
{
int x;
static int y;

public TwoKinds()
{

This conversation is currently closed to new comments.

4 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

Related Java Prog, Please explain the pr

by basilisk In reply to Related Java Prog, Please ...

I'm assuming you're having trouble understanding why the "Object2data now" part of the output shows "y is equal to 500" when the main program does not seem to be changing obj2.

This is because y is declared to be a static class member ("static int y;") in the definition of the TwoKinds class. Normally, each object or instance of a class has its own separate copy of the class variables (so obj1.x and obj2.x are different places in memory), but for static variables, every instance of the class shares the same copy (so obj1.y and obj2.y are the same location in memory).

This is an example of aliasing, an easy-to-misuse and hard-to-track feature in many programming languages.

Collapse -

Related Java Prog, Please explain the pr

by abdulmajeed_mam In reply to Related Java Prog, Please ...
Collapse -

Related Java Prog, Please explain the pr

by srishankar.r In reply to Related Java Prog, Please ...

Since the variable y is declared as static in TwoKinds class it will be shared by all the instances (i.e. ob1 and ob2 in this case). The updation of ob1.x to 500 updates the static variable y of TwoKinds class which is shared by ob2 giving the output as mentioned.

Collapse -

Related Java Prog, Please explain the pr

by abdulmajeed_mam In reply to Related Java Prog, Please ...
Back to Web Development Forum
4 total posts (Page 1 of 1)  

Related Discussions

Related Forums