0

I want to use an Array variable, which is defined in one method, in another method of the same class.

I tried to directly use it but there is an error saying "cannot find variable". I tried to define the Array variable as static in the front but there is an error saying "Array constant can only be used in initializers".

Here is an example:

import java.io.*;
import java.util.*;
public class test{
    public static void name(){
        String[] list={"a","b"};
    }

    public static void main(String args[]){
        name();
        System.out.println(Arrays.toString(list));
    }
}

And what I want is just the array named list.

1
  • You need to read more about variable scopes! Commented Apr 6, 2019 at 12:33

2 Answers 2

1

I made list as a static variable and initialized array using initializer.

import java.io.*;
import java.util.*;
public class Test{
    static String[] list;

    public static void name(){

       list= new String[]{"a","b"};
    }

    public static void main(String args[]){
         name();
        System.out.println(Arrays.toString(list));
    }
}

output

Sign up to request clarification or add additional context in comments.

Comments

1

Return the value of list from the method name. That's it change the method signature from return type void to String[].

public class test {
    public static String[] name(){
        String[] list = {"a","b"};
        return list;
    }

    public static void main(String args[]){
        System.out.println(Arrays.toString(name()));
    }
}

On the other hand, you could create it as a variable inside test class, and then in main instantiate that class and call that member variable.

public class test {
    // not very safe! using public access modifier
    public String[] list = {"a","b"};
    public static void main (String[] args) {
        test instance = new test();
        System.out.println(Arrays.toString(instance.list));
    }
}

See demo

2 Comments

Thanks man. BTW, is this the only way to fix this? if not returing what can I do
You could create it as a variable inside test class, and then in main instantiate that class and call that member variable. Would you prefer better that option?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.