1

How do you return an array object in Java? I have an object that has an array in it and I want to work with it in my main class:

// code that does not work
class obj()
{
  String[] name;
  public obj()
  {
    name = new string[3];
    for (int i = 0; i < 3; i++)
    {
      name[i] = scan.nextLine();
    }
  }
  public String[] getName()
  {
    return name;
  }
}

public class maincl
{

  public static void main (String[] args)
  {
    obj one = new obj();
    system.out.println(one.getName());
  }

I am sorry if the answer is simple but I am teaching myself to code and I have no idea how you would do this.

5
  • 1
    What error message are you getting, if I may ask? Commented Apr 27, 2013 at 17:30
  • 1
    By returning an array, as your getName() method already does. Commented Apr 27, 2013 at 17:32
  • You say that your code don't work, could you be more accurate ? What don't work ? Have you an exception ? Commented Apr 27, 2013 at 17:33
  • 1
    Hi there, you're already returning an array in getName. Commented Apr 27, 2013 at 17:35
  • Please note that in Java, all class names should start with a capital letter. So obj should be Obj, or preferably a more descriptive name. The same is true for maincl. Commented Apr 27, 2013 at 17:49

3 Answers 3

2

You have to use the toString method.

System.out.println(Arrays.toString(one.getName()));

toString is a built-in function in Java (it might need library import; if you are using Netbeans, it will suggest it).

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

2 Comments

Yes, but the output would be ugly (e.g. [foo, bar, baz]).
ok, I usually use import java.util.*; I will see if that takes care of this
1

If the problem is to print it use

System.out.println(Arrays.toString(one.getName()));

//note System, not system

Comments

1

When you do getName() you are returning a reference to an array of strings, not the strings themselves. In order to access the individual strings entered, you can use the array index String enteredName = name[index] format.

From your program, it looks like you want to print each item entered. For that, you could use a method like the following

  public void printName() {
      // for each item in the list of time
      for(String enteredName : name) {

        // print that entry
        System.out.println(enteredName);
      }
  }

Comments

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.