Take the 2-minute tour ×

So I want to use the same object that I used in my main method to be able to accessed by all other classes. How can I do this?

share|improve this question

5 Answers 5

The object must be declared outside main method as static. With this all the classes can access the same instance of the object, because it can only be one in the same JVM. Take a tour on the Oracle tutorials.

share|improve this answer
thanks! very helpful –  Ankur Sharma Aug 2 '12 at 9:57
If this answer sufficiently answered your question then you should accept it as the answer. –  minhaz1 Aug 9 '12 at 20:14

You should create a static field in any class.

share|improve this answer

You can make it static outside of the main method or you can pass it to the constructor of the other class.

share|improve this answer

You could also use a Singleton pattern which in the simplest (and thread-safe) form looks like

public class Single {
    private static final INSTANSE = new Single();
    //disallow instantiation outside
    private Single() {
    public Single getInstance() {
         return INSTANCE;
share|improve this answer

You can't declare it in the main method. You have to declare it as a static variable under the class.


public class Temp
    public static String a = "";
    public static void main(String[] args)
        a = "asdf";

Now, you can access the variable a anywhere by calling Temp.a

share|improve this answer

Your Answer


