0

Is there a way i can pass a variable from one class with main to another one with main method. For example

class A
{

    public static void main(String [] args)
    {

         int num = 5;
    }
}

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

Is there a way Class B can access int num from class A without getting null value?

1 Answer 1

1

num is a variable with scope only in the main() method. It effectively disappears once the method finishes up. This is true even considering that main() is static.

You can do this however:

class A {
    public int num = 5;
    public static void main(String[] args) {
    }
}

class B {
    public static void main(String[] args) {
        System.out.println(new A().num);     // should print '5'
    }
}

Notice that you need to create a new instance of A in order to access num, since num is an element of the object A.

Sign up to request clarification or add additional context in comments.

2 Comments

It would be worth explaining how to make a variable scoped to the class, and how to make or prevent its accessibilty.
Heh. I must have posted just before you submitted your edit. Well, you already had my upvote ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.