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.

Share:
28,518
Arnav Das
Author by

Arnav Das

Some random man, helping and seeking help here.

Updated on July 09, 2022

Comments

  • Arnav Das
    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 to method b without taking the help of parent class ?

    • Kayaman
      Kayaman about 8 years
      They're called method parameters.
    • Arnav Das
      Arnav Das about 8 years
      thanks a lot, excuse my poor grasp for technical terminology
    • Kayaman
      Kayaman about 8 years
      No, 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
      Thomas Böhm about 8 years
      Just 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
      Jesper about 8 years
      Learn how to declare method parameters and pass them when you call methods: see Defining Methods in Oracle's Java Tutorials.
    • Arnav Das
      Arnav Das about 8 years
      @ThomasBöhm... well am on that path now itself....
    • Arnav Das
      Arnav Das about 8 years
      @Jesper, thanks i will check that out
    • Arnav Das
      Arnav Das about 8 years
      @Kayaman...excuse me again...i now get you
    • Adriaan Koster
      Adriaan Koster about 8 years