ranjanarr
ranjanarr

Reputation: 153

How to share a variable across classes in Java, I tried static didn't work

class Testclass1 has a variable, there is some execution which will change value of variable. Now in same package there is class Testclass2 . How will I access updated value(updated by Testclass1) of variable in Testclass2. tried this didn't work

Note: Testclass1 and Testclass2 are two separate files in same package, I tried to run class1 first in eclipse and then class2. But class2 printed 0;

public class Testclass1 {
    public static int value;
    public static void main(String[]args)
    {
        Testclass1.value=9;
        System.out.println(value);
    }
}

----------------

public class Testclass2 {
    public static void main(String[]args)
    {
        System.out.println(Testclass1.value);
    }
}

Upvotes: 3

Views: 7594

Answers (3)

Swaranga Sarma
Swaranga Sarma

Reputation: 13413

You have to write something like this in your First Program

public class Testclass1 {
    public static int value;
    public static void main(String[]args)
    {
        try
        {
            Testclass1.value=9;
            System.out.println(value);
            new FileWriter("test.txt", false).append(String.valueOf(value));
        }
        catch(Exception ex)
        {
            //do something
        }            
    }
}

Then invoke your second program after this modification:

public class Testclass2 {
    public static void main(String[]args)
    {
        try
        {
            Scanner s = new Scanner(new File("test.txt");
            Testclass1.value = s.nextInt();
            System.out.println(Testclass1.value);
        }
        catch(Exception ex)
        {
            //do something
        }
    }
}

Couple of thing to take care:

  1. Make sure you run the programs from the same directory.
  2. You must have the .class File of TestClass1 in that directory before you run TestClass2.
  3. Also it would be a good practice to close the FileWriter once you are done.

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346270

Your problem is not sharing values across classes, you want to share values across subsequent program executions. To do that, you need to persist the value somewhere. Typically, files or databases are used for that.

Upvotes: 9

fastcodejava
fastcodejava

Reputation: 41097

If you can get main method of TestClass1 to execute, it will work. Reason it is not working, is because main method of TestClass1 never executed and so the value was never set.

Upvotes: 0

Related Questions