How can we pass variables from one method to another in the same class without taking the help of parent class?
28,518
Solution 1
You can declare b method with two parameters, as following example:
public class Dope
{
public void a()
{
String t = "my";
int k = 6;
b(t, k);
}
public void b(String t, int k)
{
System.out.println(t+" "+k);
}
public static void main(String Ss[])
{
}
}
Solution 2
Change the signature of your method from b()
to b(String t,int k)
public void b(String t, int k)
{
System.out.println(t+" "+k);
}
and give a call to b(String t,int k)
from method a()
By using these method parameters you need not change the scope of the variables.
But remember when ever you pass something as a parameter in Java it is passed as call by value.
Comments
-
Arnav Das almost 2 years
let's take a simple program like this :
public class Dope { public void a() { String t = "my"; int k = 6; } public void b() { System.out.println(t+" "+k);/*here it shows an error of not recognizing any variable*/ } public static void main(String Ss[]) { } }
although i can correct it by just resorting to this way :
public class Dope { String t; int k ; public void a() { t = "my"; k = 6; } public void b() { System.out.println(t+" "+k); } public static void main(String Ss[]) { } }
but i wanted to know if there's any way in my former program to pass the variables declared in
method a
tomethod b
without taking the help of parent class ?-
Kayaman about 8 yearsThey're called method parameters.
-
Arnav Das about 8 yearsthanks a lot, excuse my poor grasp for technical terminology
-
Kayaman about 8 yearsNo, I mean the technique that you can use is method parameters. You'll need to modify
b()
to take parameters of course. -
Thomas Böhm about 8 yearsJust define parameters for your method b and pass t and k? That's easiest Java, please try to learn Java first, by reading a book or doing a tutorial!
-
Jesper about 8 yearsLearn how to declare method parameters and pass them when you call methods: see Defining Methods in Oracle's Java Tutorials.
-
Arnav Das about 8 years@ThomasBöhm... well am on that path now itself....
-
Arnav Das about 8 years@Jesper, thanks i will check that out
-
Arnav Das about 8 years@Kayaman...excuse me again...i now get you
-
Adriaan Koster about 8 years
-