简体   繁体   English

在方法内部实例化的变量范围-Java

[英]Scope of variable instantiated inside a method - Java

Is this code safe in Java? 此代码在Java中安全吗?

public class HelloWorld {

    public static void main (String args[]) {
        HelloWorld h = new HelloWorld();
        int y = h.getNumber(5);
        int z = h.getNumber (6);
        if (y == 10)
            System.out.println("true"); 
    }

    public int getNumber(int x) {
        int number = 5;
        number = number + x;
        return number;
    }

}

My co-worker says that int number will be placed on the stack and when getNumber returns it will be popped off and could potentially be overwritten. 我的同事说,int数字将放置在堆栈中,当getNumber返回时,它将弹出并有可能被覆盖。

Is the same code potentially unsafe in C? 同一代码在C语言中可能不安全吗?

The HelloWorld class has no fields, and is therefore immutable. HelloWorld类没有字段,因此是不可变的。 You can call your getNumber(x) function as many times as you'd like, from any thread, using the same object, and it will always give the same result for the same argument. 您可以使用相同的对象从任意线程中多次调用getNumber(x)函数,并且对于相同的参数,它将始终提供相同的结果。

Maybe your co-worker is recalling horror stories in C where you can have something like static int number , which "belongs" to the method and which would get overwritten. 也许您的同事正在回想起C语言中的恐怖故事,您可以在其中得到一些像static int number这样的东西,它“属于”该方法,并且将被覆盖。 Or maybe she's thinking about "return by reference"; 或者,也许她正在考虑“参考归还”; even if it were, you'd be referencing a brand-new object every time because number is newly instantiated for every method call. 即使是这样,您也会每次都引用一个全新的对象,因为对于每个方法调用, number都是新实例化的。

Your coworker is correct, sort of, but they apparently misunderstand what is going on. 您的同事是正确的,但是,他们显然误解了正在发生的事情。

    public int getNumber(int x) {
        int number = 5;
        number = number + x;
        return number;
    }

Yes the value of 5 + 5 or 5 + 6 will be placed on the stack, but there is no danger of them being overwritten, they will properly be placed into y or z. 是的,将5 + 5或5 + 6的值放在堆栈上,但是不存在覆盖它们的危险,可以将它们正确地放在y或z中。

I suspect the confusion is from C (this type code works fine in C as well), but for pointers instead of primitives. 我怀疑混淆来自C(这种类型的代码在C中也能正常工作),但是对于指针而不是基元。 Returning a result of malloc from a function in C can be "challenging" if you don't do it right. 如果操作不正确,从C中的函数返回malloc的结果可能会“具有挑战性”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM