Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting method's local variable through another method

Tags:

java

oop

How to get a value which declared and initialized in another method without using parameter in java?

public class Value {
    void method1()
    {
        int demo=10;
        System.out.println("methd 1"+demo);
    }
    void method2()
    {
        System.out.println("method 2"+demo);
    }

    public static void main(String[] args) {
        Value obj = new Value ();
        obj.method1();
        obj,method2();
    }
}

Here the variable demo is declared in method1 and assigned a value now I need to get the value of demo in method 2 is this possible without any parameter, global declaration, and no getter setter method?

like image 895
Janarthanan Ramu Avatar asked Nov 22 '25 11:11

Janarthanan Ramu


1 Answers

No, it's not possible, because demo doesn't exist once method1 has returned. It's a local variable within method1.

...without any parameter,global declaration, and no getter setter method?

That pretty much rules everything out, if by "global declaration" you mean making demo an instance field (which isn't a global, but I think that's what you meant).

But just for completeness, here's demo as an instance field:

public class Value {
    private int demo;

    void method1()
    {
        this.demo = 10;
        System.out.println("method 1" + this.demo);
    }
    void method2()
    {
        System.out.println("method 2" + this.demo);
    }

    public static void main(String[] args) {
        Value obj = new Value ();
        obj.method1();
        obj.method2();
    }
}

You're not required to use this. when accessing it, but doing so makes it clear it's an instance field, not a local variable.

like image 92
T.J. Crowder Avatar answered Nov 25 '25 00:11

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!