Reputation: 1
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?
Upvotes: 0
Views: 39
Reputation: 5763
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
.
Upvotes: 1