user1985 user1985 - 4 months ago 8
Java Question

Reference variable in java is not changing its state

I have the following code:

class Cat {
String name;
float time;

void action(){
if (time >= 0 && time < 8) {
System.out.println("I am sleeping");
} else if (time >= 8 && time < 12) {
System.out.println("I am playing");
} else if (time >= 12 && time < 19) {
System.out.println("I am sleeping");
} else if (time >= 19 && time <= 24) {
System.out.println("I am playing");
} else {
System.out.println("Wrong input");
}
}
}

public class Main {

public static void main(String[] args) {
Cat cat1 = new Cat();
Cat cat2 = new Cat();

cat1.name = "kali";
cat2.name = "lali";

Cat time1 = new Cat();
Cat time2 = new Cat();
Cat time3 = new Cat();
Cat time4 = new Cat();

time1.time = 3;
cat1.action();

time2.time = 9;
cat1.action();

time3.time = 15;
cat2.action();

time4.time = 21;
cat2.action();
}
}


I expect the following output:

I am sleeping
I am playing
I am sleeping
I am playing


However I am getting the following output:

I am sleeping
I am sleeping
I am sleeping
I am sleeping


Why is it so?

As far I can decipher the state of the variable
time
is here constant and is not changing as per new input.

Answer

That's happening because you are executing the action operation over a different instance (e.g. cat1 instead of time1). As those are instance variables, they are only scoped on that instance.

The below would solve your problem:

time1.time = 3;
time1.action(); // instead of cat1

time2.time = 9;
time2.action(); // instead of cat2

// ...