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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With