0

I defined two java class test1 and test2, in which a variable a=3 was defined in test1, and then changed to 10 in the connect() method, and I used Scanner to make the program not exit. But when I call test1.a in test2, the value obtained is still the initial value a=3 instead of a=10. What method should I use to get the modified value of a?

public class test1 {
        public static int a=3;
    public static void connect(){
        System.out.println(a);
         a=10;
        System.out.println(a);
        Scanner sc = new Scanner(System.in);
        sc.nextLine();
    }

    public static void main(String[] args) {
        connect();
    }
}
public class test2 {
    public static void main(String[] args) {
        System.out.println(test1.a);
    }
}
Oiiiwk
  • 31
  • 5
  • 7
    You've started two different instances of the JVM, the state is **not** shared between JVMs. In `test2.main()` the `connect()` method was never called – Lino Jun 23 '20 at 09:33

3 Answers3

0

It is because you never called test1.connect() in the first place, so the value was never modified. So call test1.connect() in main(). You cannot have two main() methods at once. :

public class test2 {
    public static void main(String[] args) {
        test1.connect();
        System.out.println(test1.a);
    }
}

And remove the main() in test1. Also, in Java, you usually use PascalCase for class names by convention. So, capitalize the first letter, use Test1 instead of test1.

In addition, if you want the value of a to be modified without calling any method and when the class is loaded(though I'm not sure why), you can use a static block:

public class Test1 {
        public static int a = 3;
       static {
        System.out.println(a);
        a = 10;
        System.out.println(a);
        Scanner sc = new Scanner(System.in);
        sc.nextLine();
    }
}
Amal K
  • 4,359
  • 2
  • 22
  • 44
0

In test2, you have to call test1.connect() to update a to 10. Then you could use System.out.println(test1.a) to get the value of the modified a.

Roy Yang
  • 31
  • 2
0

These two classes are separate in their execution. A static variable is also called a class variable or a member variable thus it is relevant to only one class. When you execute your code, you will have to run test1 first and then you will have to run test2 again. This will cause only the initial values of test1 be fetched into test2 when you do a syso(test1.a) , because these two classes are being executed separately.

So if you want to use a modified value of class test1 into another class of test2, you will have to call test1 from test2.

Public class test2 {
  Public static void main(String[] args) {
    Syso(“a in test2 “+test1.a);
    test1.connect();
    Syso(“modified a in test2 ”+test1.a);
  }
}

Hope It cleared your doubt.

hungr
  • 2,086
  • 1
  • 20
  • 33