Results 1 to 4 of 4
  1. #1
    ben2470 is offline Member
    Join Date
    Aug 2014
    Rep Power

    Default How to pass array to method?

    so if i assigned values in arrays like the below:

    this is the method in main class:
    public static void trainer(){
    trainer[] trainerArr = new trainer[4];
    trainerArr[0] = new trainer("Ben Yap", "Male", "Kuala Lumpur", 10000, "Yoga");
    trainerArr[1] = new trainer("Wilson Ting", "Male", "Kuala Lumpur", 10001, "Kick-boxing");
    trainerArr[2] = new trainer("Fong Tan", "Female", "Johor Bahru", 10002, "Aerobics");
    trainerArr[3] = new trainer("Olivia Te", "Female", "Pulau Pinang", 10003, "Swimming");

    this is the trainer class:
    public class trainer extends person{
    String classType;

    public trainer(String name, String gender, String address, int id, String classType) {

    How can i pass these arrays into another method in the main class?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power

    Default Re: How to pass array to method?

    Simply pass the 'trainerArr' object; it's a simple reference just like all object variables, i.e.

    Java Code:
    // in main:
    // myMethod:
    private static void myMethod(trainer[] trainerArray) { ... }
    kind regards,

    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Rep Power

    Default Re: How to pass array to method?

    An issue you will have with the posted code is that the array is defined inside the trainer method. So it cannot be accessed anywhere else. You could return the array or declare it as an instance method.

    BTW classes should be capitalised. Also try and avoid calling methods the same as classes. Confusion ensues.

  4. #4
    javaone01 is offline Member
    Join Date
    Aug 2014
    Rep Power

    Default Re: How to pass array to method?

    Alternatively, you could also reverse it, and instead of putting your arrays in the main method, put them inside of your other class and run the class in your main.

Similar Threads

  1. How to pass data to the paintComponent method?
    By Tohron in forum Java Applets
    Replies: 7
    Last Post: 08-10-2012, 03:58 AM
  2. How to Pass a variable from method to method
    By Rahim2312 in forum New To Java
    Replies: 7
    Last Post: 05-07-2012, 10:08 PM
  3. Replies: 18
    Last Post: 04-18-2011, 05:39 AM
  4. pass value inside method A to method B
    By masokis in forum New To Java
    Replies: 5
    Last Post: 09-01-2010, 04:06 AM
  5. Pass String[] into method in different class
    By Swankee in forum New To Java
    Replies: 19
    Last Post: 09-28-2009, 05:30 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts