0

A.java

public Class A
{

        String a,b;
        public static void setArray(String[] array)//This is where i want the array to come
        {
               array[0]=a;
               array[1]=b
        }
}

B.java

public class B
{

        String[] arr1 = new String[2];
        arr1[0]="hello";
        arr1[2]="world";
        public static void main(String[] args)
              {
                A a = new A();
                a.setArray(arr1);//This is from where i send the array
              }
}

I am trying to send an array from one class to another class

dcsohl
  • 7,186
  • 1
  • 26
  • 44
Syed Sami
  • 19
  • 1
  • 3

2 Answers2

1

I've edited your code a bit. Your main problem was in class A, where you were assigning values backwards. See the updated class A. I also added a constructor to your class, but this isn't strictly necessary.

public Class A {

  String a,b;

  // A public method with no return value
  // and the same name as the class is a "class constructor"
  // This is called when creating new A()
  public A(String[] array) 
  {
    setArray(array) // We will simply call setArray from here.
  }

  private void setArray(String[] array)
  {
    // Make sure you assign a to array[0],
    // and not assign array[0] to a (which will clear this array)
    a = array[0];
    b = array[1];
  }
}

public class B {
  String[] arr1 = new String[2];
  arr1[0]="hello";
  arr1[2]="world";
  // A a; // You can even store your A here for later use.
  public static void main(String[] args)
  {
    A a = new A(arr1); // Pass arr1 to constructor when creating new A()
  }
}
Michael Fulton
  • 4,608
  • 3
  • 25
  • 41
0

You were getting a NULL value because your String variables in class A were not initialized.

In class A you need to remove the STATIC from the method, and initialize the String a and b with something, like this:

public class A {
    String a = "bye";
    String b = "bye";

    public void setArray(String[] array) {
        array[0] = a;
        array[1] = b;
    }
}

In class B you should add STATIC to your array (you cannot reference a non-static variable within a static method).

public class B {
    static String[] arr1 = {"hello", "world"};
    public static void main(String[] args) {
        A a = new A();
        a.setArray(arr1);//This is from where i send the array
        System.out.println(arr1[0] + " " + arr1[1]);
    }
}

Also, if you want to initialize something the way you did (outside a method):

String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";

you have to put the initialization within a block, like this:

String[] arr1 = new String[2];
{
    arr1[0] = "hello";
    arr1[2] = "world";
}

Hope this helps you

AlexMelgar
  • 86
  • 5