简体   繁体   中英

Scope of variable instantiated inside a method - Java

Is this code safe in 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.

Is the same code potentially unsafe in C?

The HelloWorld class has no fields, and is therefore immutable. 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.

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. 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.

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.

I suspect the confusion is from C (this type code works fine in C as well), but for pointers instead of primitives. Returning a result of malloc from a function in C can be "challenging" if you don't do it right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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