java 中的动态作用域变量? (又名每个方法执行一个变量)

发布于 2024-08-07 19:14:08 字数 108 浏览 5 评论 0原文

我想知道在java中是否可以声明方法执行的本地变量。

例如,如果我正在做一些递归的事情,并且我想保留特定于该方法的一个特定执行的各种计数器。

我不知道正确的英文表达...

I would like to know if it's possible in java to declare a variable local to the execution of the method.

For instance, if i'm doing some recursive stuff and i want to keep various counters specific to one particular execution of the method.

I don't know the correct english expression for that...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

琴流音 2024-08-14 19:14:08
void method()
{
     int i = 0;  // this int is local to 'method'
}
void method()
{
     int i = 0;  // this int is local to 'method'
}
清浅ˋ旧时光 2024-08-14 19:14:08

这就是 Java 默认的工作方式。例如,在以下方法中:

void recursive(int i) {
  int localI = 6;
  i-= 1;
  if (i > 0) {
    recursive(i);
  }

localI 将保留在该方法当前执行的本地位置。

This is how Java works by default. For example, in the following method:

void recursive(int i) {
  int localI = 6;
  i-= 1;
  if (i > 0) {
    recursive(i);
  }

localI will stay local to the current execution of the method.

无语# 2024-08-14 19:14:08

方法内的普通局部变量正是您的意思。这些局部变量是在堆栈上分配的。每次调用该方法时,无论是否以递归方式,都会创建变量的新副本。

A normal, local variable inside a method is exactly what you mean. Those local variables are allocated on the stack. Each time you call the method, whether it's in a recursive manner or not, a new copy of the variable is created.

流年里的时光 2024-08-14 19:14:08

我认为您可能正在谈论静态变量。
如果声明静态变量,它将在方法执行之间保存它的值。

I think you might be talking about static variables.
if you declare a static variable it will save it's value between executions of the methods.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文