user2547306
user2547306

Reputation: 1

If I declare a variable in a java method, is that variable also accessible to any method called from the method in which it is declared?

If I declare a variable in a java method, is that variable also accessible to any method called from the method in which it is declared?

When I try the following, function2 does not recognise the variable variable1. Should this be the case?

public static void main(String[], args)
{
  int variable1
  function2();
}

Upvotes: 0

Views: 116

Answers (4)

iajrz
iajrz

Reputation: 789

Doesn't work, because of the way variable scoping works in java. This would work in JavaScript, though.

If you need a function to have data, you must give it to the function. Otherwise, have the data somwhere it can be read.

More info:

http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html http://www.cs.umd.edu/~clin/MoreJava/Objects/local.html

Upvotes: 0

Garrett Hall
Garrett Hall

Reputation: 30032

It will not be recognized unless you pass it as a parameter to function2.

E.g.

  int variable1;
  function2(variable1);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502835

When I try the following, function2 does not recognise the variable variable1. Should this be the case?

Yes. It's a local variable - local to the method in which it's declared. That method could be executing several times within the same thread (different stack levels) and on several different threads - each invocation of the method has a separate variable.

You should review the Variables section of the Java tutorial.

Upvotes: 4

Rogue
Rogue

Reputation: 11483

You would either have to have the variable be a field or pass it through the arguments of the function.

public static void main(String[] args) {
    int variable = 0;
    function2(variable);
}

public static void function2(int argument) {
    //argument is = variable
}

/* or ... */

private static int variable;

public static void main(String[] args) {
   variable = 0;
   function2();
}

public static void function2() {
    //variable is usable
}

Upvotes: 0

Related Questions