Passing a whole array through a method

I need some quick help on how to pass a whole array through the method addCoins(). Here is the code:
public class Purse {
     private Coin[] coins;
     private int lastIdx;
public Purse() {
     coins = new Coin[100];
     lastIdx = 0;
public boolean addCoin(Coin b) {
     if (lastIdx < coins.length) {
          lastIdx++;
          coins[lastIdx] = b;
          return true;
     else {
          return false;
public boolean addCoins(Coin[] b) {
     if (lastIdx < coins.length) {
          for (b=0; b<99; b++) {
               coins[b] = b;
     else {
          return false;
}I figured passing the whole array would be "Coin[] b" but apparently Eclipse says that it can't convert from int to Coin[]. I have no idea what that means. Thanks in advance.

I need to create 3 classes, Coin, Purse, and TestPurse.
Coin code:
public class Coin {
     private String typeOfCoin;
     private double value;
public Coin(String t, double v) {
     typeOfCoin = t;
     value = v;
public String toString() {
     return typeOfCoin + value;
}Purse code:
public class Purse {
     private Coin[] coins;
     private int lastIdx;
public Purse() {
     coins = new Coin[100];
     lastIdx = 0;
public boolean addCoin(Coin b) {
     if (lastIdx < coins.length) {
          lastIdx++;
          coins[lastIdx] = b;
          return true;
     else {
          return false;
public boolean addCoins(Coin[] b) {
      if (lastIdx < coins.length) {
          for (int i=0; i<coins.length; i++) {
               coins[i] = b;
     else {
          return false;
public Coin getReverse() {
     coins = new Coin[0];
     lastIdx = 100;
}In the Purse class, I need methods addCoin and addCoins that need to return boolean.  addCoin is supposed to add the argument coin as an element of the coins array if there is space.  addCoins neds to add all the coins in the input argument as elements of the coins array if there is space.  I then have to create two methods, getReverse and getValue that take no argument and getReverse that returns an array of type Coin while getValue returns a double.  In getReverse, I create an array simlar to coins but this new array is reverse.  I started on this method but I first need to worry about the addCoin and addCoins method.  For the record, getValue needs to add up the values of all the coins in the purse and return it, which I have no idea how to do that.  That's my next question.
Edited by: quagmire87 on Dec 1, 2009 4:35 PM
fixed method addCoins                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Passing hard coded array to a method

    how to passing hard coded array to a method
    like method1("eee","eoe","eee",.....)
    which should populate a array of strings (say arr[]) for the method
    what can be done??

    or if you're using Java 5.0 declare the method aspublic void method(String... array) {
    }

  • Passing object reference array to a method

    Hi everyone,
    I'm new to the java programming language. I want to create create a array of 50 objects and pass them in to a method in other class.
    Can anyone help me on this problem........................
    Chathu.

    Object[] objectArray = new Object[50];
    objectArray[0] = "Hello World";
    objectArray[1] = new Integer(42);
    myClass.myMethod(objectArray);

  • NEED HELP! passing an object array to a method

    Hi, i need to make a method called public Server[] getServers() and i need to be able to see if specific server is available for use.
    I have this so far:
    public abstract class AbstractServer
    protected String serverName;
    protected String serverLocation;
    public AbstractServer(String name,String location)
    this.serverName=name;
    this.serverLocation=location;
    public abstract class Server extends AbstractServer
    public Server(String name,String location)
    super(name,location);
    public class CreateServers
    Server server[];
    public CreateServers()
    public Server create()
    for(int i=0; i<10; i++)
    server=new Server(" ", " "); //i was going to fill in something here
    return server;
    OK NOW HERE IS THE PROBLEM
    i have another class that is supposed to manage all these servers, and i dont understand how to do the public Server[] getServers(), this is what i have tried so far
    public class ServerManager()
    public Server[] getServers(Server[] AbstractServer)
    Server server=null; //ok im also confused about what to do here
    return server;
    in the end i need this because i have a thread class that runs the servers that has a call this like:
    ServerManager.getServers("serverName", null);
    Im just really confused because i need to get a specific server by name but i have to go through AbstractServer class to get it
    Any help?

    ok, right
    since i have to call this method in the thread class saying
    ServerManger.getServer(AbstractServer[]) //to see if i have all the servers i need to proceed
    im confused about how it should be declared in the actual ServerManager
    should it be like
    public Server[] getServers(AbstractServer[]) ???? and then have it return all the servers it has
    thats the part i dont get, because instead of saying ServerManager.getServer(string, string) i want it to go and find out if i have all the servers i need to continue
    does that make sense? sort of?

  • Pass chinese to c through native method

    Hi all:
    I used native method to pass some chinese character from java to c.I use
    (*env)->GetStringUTFChars() method.However , there isn't success.The characters output from c program are some charachers I can't understand.Can anyone tell me what happen???
    Thanks in advance

    Hi JackyWMK,
    I had a similar problem some time ago. I think the problem has to do with the UTF-8 encoding of the strings.
    I used the method copy_string() below you will manage to work around the problem.
    The method copies what is in the memory from java to c and does not care about the format of the encoding.
    Instead of using:
    const char* menuStr = env->GetStringUTFChars (menuText, NULL);use:
    const char* menuStr = copy_string(env, menuText);
    const char *copy_string(JNIEnv *env, jstring jstr)
      jclass cls = env->GetObjectClass(jstr);
      jmethodID mid = env->GetMethodID(cls, "getBytes", "()[B");
      jbyteArray jba = (jbyteArray)env->CallObjectMethod(jstr, mid);
      jboolean iscopy;
      jbyte *bytes = env->GetByteArrayElements(jba, &iscopy);
      jsize n = env->GetArrayLength(jba);
      char *unicodeString = (char *)malloc(n + 1);
      unicodeString[n] = '\0';
      memcpy((void *)unicodeString, (const void *)bytes, (size_t)n);
      if (iscopy == JNI_TRUE)
        env->ReleaseByteArrayElements(jba, bytes, 0);
      return (const char *)unicodeString;
    }

  • Passing an array to a method

    This is probably a really simple question - but I'm new to java!
    Object (is that the right word?) Car consists of some information about a car - registration number, engine size etc.
    I have defined an array of objects of type car, and I want to pass the whole thing to a method.
    Specifically...
    I want to pass an inputted search term - the registration number, to a search method to return the number of the element of the array in which that record is stored. Presumably I need to pass the whole array?
    I think what might be causing the problem is the definition of the method:
    private int searchCar(String regNumber, int records, Car carArray[]Also, I don't know how to refer to regNumber as stored in carArray. I'm guessing it's carArray[number].regNumber or something like that.
    Do I need to initialise the whole array before I use it?
    Thanks for any help - I'm clueless!

    You should provide in your class Car ,methods to get (and set if necessary) each of the instance variables associated with a Car object. For example your car class should look something like this:
    public class Car
    private String make, model, colour, regNumber;
    public Car(String a, String b, String c, String d)
    make = a;
    model =b;
    colour = c;
    regNumber = d;
    public String getModel()
    return model;
    public String getMake()
    { return make;
    public string getColour()
    return colour;
    public string getRegNumber()
    return regNumber;
    public string to String()
    return getMake() + " " + getModel() + " " + getColour() + " " + getRegNumber;
    }in your main method
    // create your Array of Car objects and the mthod as below.
    public int searchCar(Car [ ] cars, String reg)
    int found =-1;
    for (int counter = 0; counter < cars.length;  ++ counter)
    if (cars[counter].getRegNumber.equals(reg))
    found = counter;
    break;
    return found;
    }// end searchCarCall this method with something like:
    int index = carSearch(carArray, "SM51 KJL");
    if(index != -1)
    System.out.println("This full details of the requested car are : " + carArray[index].toString());
    else
    System.out.println("This car has not been recorded on our System");
    Haven't compiled this so aplogies for any typing errors.

  • How do I pass an array to a method?

    Hopefully you guys don't mind answering one of my stupid questions :o(
    I have problem passing an array to a method.
    //Here is the code that calls to the method:
    String[] Folder = new String[19];
    int cnt;
    for(cnt=0; cnt<20; cnt++){
    Folder[cnt] = request.getParameter("searchfolder_name" + (cnt + 1));
    ProcessNotify(Folder[cnt]);
    //================================================================
    //Here the the method that is supposed to take in the array
    private void ProcessNotify(String FolderName[]){
    FolderName = new String[19];
    int cnt;
    for(cnt=0; cnt<20; cnt++){
    System.out.println("Folder Name: " + FolderName[cnt]);
    I got an error that says java.lang.String[] can not be applied to java.lang.String
    I thought "String FolderName[]" is an array? Anyway... I'm confused. If you know the answer, plz let me know :o) big thx
    lil

    ProcessNotify(Folder[cnt]);
    Are you trying to pass the whole array or just one piece from it? What you coded, tried to pass just one piece by specifying a subscript. BTW variable cnt is a subscript out of range.
    If you meant to pass the whole array, just use it's name with no subscript.

  • How to pass a file into a java method

    I am trying to pass a file into a java method so I can read the file from inside the method. How can I do this? I am confident passing int, char, arrays etc into methods as I know how to identify them in a methods signature but I have no idea how to decalre a file in a mthods signature. Any ideas please ?
    Thanks

    Hi,
    Just go thru the URL,
    http://www6.software.ibm.com/devtools/news1001/art24.htm#toc2
    I hope you will get a fair understanding of 'what is pass by reference/value'.
    You can pass Object reference as an argument.
    What Pablo Lucien had written is right. But the ideal situation is if you are not modifying the
    file in the calling method, then you can pass the String (file name) as an argument to the called method.
    Sudha

  • Passing Array to Another Method

    Hello, I created a program with an array in one of the methods. I have been trying to figure out how to correctly pass the array to another method in the same class. I know my problem is in my method delcaration statements. Could someone please show me what I am doing wrong? Please let me know if you have any questions. Thanks for your help.
    import javax.swing.*;
    import java.util.*;
    class Bank1 {
         public static void main(String[] args) {
              Bank1 bank = new Bank1();
              bank.menu();
         //Main Menu that initializes other methods
         public void menu( ) {
              Scanner scanner = new Scanner(System.in);
              System.out.println("Welcome to the bank.  Please choose from the following options:");
              System.out.println("O - Open new account");
              System.out.println("T - Perform transaction on an account");
              System.out.println("Q - Quit program");
              String initial = scanner.next();
              char uInitial = initial.toUpperCase().charAt(0);
              while (uInitial != 'O' && uInitial != 'T' && uInitial != 'Q') {
                   System.out.println("That was an invalid input. Please try again.");
                   System.out.println();
                   initial = scanner.next();
                   uInitial = initial.toUpperCase().charAt(0);
              if (uInitial == 'O') newAccount();
              if (uInitial == 'T') transaction();
         //Method that creates new bank account
         public Person[] newAccount( ) {
              Person[] userData = new Person[1];
              for (int i = 0; i < userData.length; i++) {
                   Scanner scanner1 = new Scanner(System.in);
                   System.out.println("Enter your first and last name:");
                   String name = scanner1.next();
                   Scanner scanner2 = new Scanner(System.in);
                   System.out.println("Enter your address:");
                   String address = scanner2.next();
                   Scanner scanner3 = new Scanner(System.in);
                   System.out.println("Enter your telephone number:");
                   int telephone = scanner3.nextInt();
                   Scanner scanner4 = new Scanner(System.in);
                   System.out.println("Enter an initial balance:");
                   int balance = scanner4.nextInt();
                   int account = i + 578;
                   userData[i] = new Person( );
                   userData.setName               ( name );
                   userData[i].setAddress          ( address );
                   userData[i].setTelephone     ( telephone );
                   userData[i].setBalance          ( balance     );
                   userData[i].setAccount          ( account     );
                   System.out.println();
                   System.out.println("Your bank account number is: " + userData[i].getAccount());
              return userData;
              menu();
         //Method that gives transaction options
         public void transaction(Person userData[] ) {
              System.out.println(userData[0].getBalance());

    Thank you jverd, I was able to get that to work for me.
    I have another basic question about arrarys now. In all of the arrary examples I have seen, the array is populated all at once using a for statement like in my program.
    userData = new Person[50];
    for (int i = 0; i < userData.length; i++) In my program though, I want it to only fill the first array parameter and then go up to the main menu. If the user chooses to add another account, the next spot in the array will be used. Can someone point me in the right direction for doing this?

  • Problem passing oracle.sql.ARRAY to Oracle

    I am having ClassCastException when I try to pass a oracle.sql.ARRAY to a Oracle Package.
    Here is my code:
    PreparedStatement stmt = null;
    String strArray[] = { "1,2,3,4,5" };
    ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor( "TEST_PAC_1.TEST_COLL_2", dbConnection );
    //encounter Exception on the line below.
    ARRAY array_to_pass = new ARRAY( descriptor, dbConnection, strArray );
    String queryStr = "begin TEST_PAC_1.TEST_PROC_2(?); end;";
    stmt = dbConnection.prepareStatement(queryStr);
    stmt.setArray( 1, array_to_pass );
    stmt.execute();
    I understand that oracle.sql.ARRAY has been replaced by weblogic.jdbc.vendor.oracle.OracleArray in Weblogic.
    MY QUESTION IS: HOW DO I INSERT MY STRING ARRAY INTO THE OracleArray and pass it to the plsql.
    Really frustrated searching through the forums for the whole day,
    Thanks,

    Try this if you are at weblogic 8.1:
    Connection con = getConnectionFromDataSource();
    Connection vendorConnection = ((WLConnection)con).getVendorConnection();
    // use direct oracle connection.
    ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor( "TEST_PAC_1.TEST_COLL_2", dbConnection );
    vendorConnection.close();
    Beware that you should be very careful as you are going to use a direct vendor
    connection.
    The better aproach is to pass the string array as a delimited string to your storad
    procedure and parse it in the SP - then you don't have to mess up with vendor-specific
    handling.
    Hope this helps.
    Regards,
    Slava Imeshev
    "Daddy Daddy" <[email protected]> wrote in message news:24349835.1097143668312.JavaMail.root@jserv5...
    I am having ClassCastException when I try to pass a oracle.sql.ARRAY to a Oracle Package.
    Here is my code:
    PreparedStatement stmt = null;
    String strArray[] = { "1,2,3,4,5" };
    ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor( "TEST_PAC_1.TEST_COLL_2", dbConnection );
    //encounter Exception on the line below.
    ARRAY array_to_pass = new ARRAY( descriptor, dbConnection, strArray );
    String queryStr = "begin TEST_PAC_1.TEST_PROC_2(?); end;";
    stmt = dbConnection.prepareStatement(queryStr);
    stmt.setArray( 1, array_to_pass );
    stmt.execute();
    I understand that oracle.sql.ARRAY has been replaced by weblogic.jdbc.vendor.oracle.OracleArray in Weblogic.
    MY QUESTION IS: HOW DO I INSERT MY STRING ARRAY INTO THE OracleArray and pass it to the plsql.
    Really frustrated searching through the forums for the whole day,
    Thanks,

  • Error: Non-array passed to JNI array operations

    Can anyone see what I am doing wrong? I am trying to go through the array of objects example in the online JNI text book "The Java Native Interface Programmer's Guide and Specification" by Sheng Liang. The book and pertinent chapter can be found here:
    http://java.sun.com/docs/books/jni/html/objtypes.html#27791
    The error I received on running the program with the -Xcheck:jni switch is this:
    FATAL ERROR in native method: Non-array passed to JNI array operations
         at petes.JNI.ObjectArrayTest.initInt2DArray(Native Method)
         at petes.JNI.ObjectArrayTest.main(ObjectArrayTest.java:14)Without the xcheck switch, I get a huge error log file that I can reproduce here if needed.
    My c code with #ifdef _Debug statements removed for readability is listed below.  The location of the error (I believe) is marked:
    #include <jni.h>
    #include <stdio.h>
    #include "petes_JNI_ObjectArrayTest.h"
    //#define _Debug
    // error found running the program with the -Xcheck:jni switch
    //page 38 and 39 of The Java Native Interface Guide by Sheng Liang
    JNIEXPORT jobjectArray JNICALL Java_petes_JNI_ObjectArrayTest_initInt2DArray
      (JNIEnv *env, jclass class, jint size)
         jobjectArray result;
         jint i;
         jclass intArrCls = (*env)->FindClass(env, "[I");
         if (intArrCls == NULL)
              return NULL;
         result = (*env)->NewObjectArray(env, size, intArrCls, NULL);
         if (result = NULL)
              return NULL; 
         for (i = 0; i < size; i++)
              jint tmp[256]; // make sure it is large enough
              jint j;
              jintArray iarr = (*env)->NewIntArray(env, size);
              if (iarr == NULL)
                   return NULL; 
              for (j = 0; j < size; j++)
                   tmp[j] = i + j;
              (*env)->SetIntArrayRegion(env, iarr, 0, size, tmp);
              (*env)->SetObjectArrayElement(env, result, i, iarr); // ***** ERROR:  Non-array passed to JNI array operations
              (*env)->DeleteLocalRef(env, iarr);
         return result;
    }Here is my java code
    package petes.JNI;
    public class ObjectArrayTest
        private static native int[][] initInt2DArray(int size);
        static
            System.loadLibrary("petes_JNI_ObjectArrayTest");
        public static void main(String[] args)
            int[][] i2arr = initInt2DArray(3);
            if (i2arr != null)
                for (int i = 0; i < i2arr.length; i++)
                    for (int j = 0; j < i2arr[0].length; j++)
                        System.out.println(" " + i2arr[i][j]);
                    System.out.println();
            else
                System.out.println("i2arr is null");
    }Thanks in advance!
    Pete

    Niceguy1: Thanks for the quick reply!
    So far, I mainly see the usual differences between C and C++ JNI calls. Also, in the example you gave, they use a lot of casts, but that doesn't seem to make much difference to my output. Also, in the example, they create a 0-initilized int array, and use this class to initialze the class type of the Object array. I get the class type by a call to FindClass for a class type of "[I".  I'll try this their way and see what happens...
    Edit:  Changing the way I find the array element Object type did not help.  I still get the same error as previous.  Any other ideas would be greatly appreciated.
    Message was edited by:
            petes1234                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Passing values from HTML to JSP method,

    Hello:
    I am starting to wonder if what I am doing will ever work...
    Ok, I am trying to avoid javascript. I have a drop-down list named "year" and I wish to call a JSP method that is defined/declared in the same JSP.
    First, I want to pass the chosen option to the method and then store the name/value in a global variable.
    Second, depending on what the user selects, I will get values from an array defined/initialized on page load AND display those values in another drop-down list.
    As a test, and until now, I have done this. I am not passing anything yet, I just wanted to test this "fuzzy logic" I am having:
    <%!
    String currentYear;
    private void showDaysInDDList()
    currentYear = request.getparameter("year");
    %>
    Then on the HTML part of the page I have a drop-down list:
    <html>
    <head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body bgcolor="ffffcc">
    <form method="POST" name="form1" action="left.jsp">
    <select name="year" onchange="<%=showDaysInDDList()%>">
         <option></option>
         </select>
    I am getting the following errors:
    An error occurred at line: 105 in the jsp file: /p1/left.jsp
    request cannot be resolved
    ....and regarding to the onchange="<%=showDaysInDDList()%>"> part I am getting the following:
    An error occurred at line: 204 in the jsp file: /p1/left.jsp
    The method print(boolean) in the type JspWriter is not applicable for the arguments (void)
    In the action="left.jsp", left.jsp is the same page where the drop-down list and the method is. I am not sure if that is another error.
    I will continue here with my coffee ... any help will be extremely appreciated !!..
    I'll have to shut down my "asp.net mind" for a while..
    I'll reply later,
    MMS

    Ok, this is a bit messy here. I don't know how much you've read up on JSP but you seem confused about some fundamentals to me. However, you mention that you've worked with ASP .net so I'm going to assume you do have some notion of how thing should work in general.
    1. JSP is on the server-side and events like onchange that you've used take place on the client-side after the JSP/ servlet code has run and produced the HTML page. So calling your showDaysInDDList() will not work.
    2. Are you sure you know how the declaration tags ( <%! %> ) work? When you normally write JSP code without these tags, all that code gets compiled into the service method of the corresponding servlet that the JSP gets turned into. But, you can declare your own methods and variables outside the service method by using these tags.
    So what you're effectively doing is declaring
    private String/ void showDaysInDDList()
    }and followed by your usual _jspService()
    public void _jspService(HttpServletRequest request,
       HttpServletResponse  response)
         throws IOException, ServletException
    }Now it may be clear, that the request object is not available in the showDaysInDDList() method by default; you'll either have to declare it ( not sure if it's good programming practice or not ) or pass the required parameters in the call.
    3. Like you seem to have realized, that error about the printing of booleans was related to the return type of your method because <%= %> translates to out.println(); and since the argument was the method call, the return value was to be printed which here was a void ( not sure why it says boolean though :D ).
    Read up on this introduction to JSPs http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html, seems to be pretty good and covers everything in quick, short chunks.
    Hope this helps.

  • How can I use my array in another method.... Or better yet, what's wrong?

    I guess I'll show you what I am trying to do rather and then explain it
    public class arraycalc
    int[] dog;
    public void arraycalc()
    dog = new int[2];
    public void setSize(int size)
    dog[1] = size;
    public int getSize()
    return dog[1];
    This gives me a null pointer exception...
    How can I use my array from other methods?

    You have to make the array static. :)
    Although I must admit, this is rather bad usage. What you want to do is use an object constructor to make this class an object type, and then create the array in your main class using this type, and then call the methods from this class to modify your array. Creating the array inside the other method leads to a whole bunch of other stuff that's ... well, bad. :)
    Another thing: Because you're creating your array inside this class and you want to call your array from another class, you need to make the array static; to make it static, you must make your methods static. And according to my most ingenious computer science teacher, STATIC METHODS SUCK. :D
    So, if you want to stick with your layout, it would look like:
    public class arraycalc
         static int[] dog;
         public static void arraycalc()
              dog = new int[2];
         public static void setSize(int size)
              dog[1] = size;
         public static int getSize()
              return dog[1];
    }But I must warn you, that is absolutely horrible code, and you shouldn't use it. In fact, I don't even know why I posted it.
    You should definitely read up on OOP, as this problem would be better solved by creating a new object type.

  • Displaying array from another method

    Hello for this code I want to display the array from the first method in the second method although when I run it, it displays 6 times the whole array - well the the last iteration shows the whole array. I have only just started using different methods.
    Please could someone say why this is happening.
    Cheers
    John
    import java.util.*;
    public class Lottery
         public static void main(String[] argStrings)
              int[] lotteryArray = new int[6];
              for(int count = 0; count < 6; count++)
                   double randomNumber = Math.random();
                   double biggerRandom = (randomNumber * 50);
                   int integerNumber = (int)biggerRandom;
                   lotteryArray[count] = integerNumber;
                   displayNumbers(lotteryArray);
         public static void displayNumbers(int[] lotteryArray)
              System.out.println("Lottery numbers are:");
              for(int i = 0; i < lotteryArray.length; i++)
                   System.out.print(lotteryArray[i] + " ");
              System.out.println();
    }

    Well I know your right but actualy getting this to work for my program is proving hard. This is my progress so far:
    Cheers
    John
    public static void main(String[] argStrings)
              int[] lotteryArray = new int[6];
              int p = 0;
              boolean duplicate = false;
              while(p < 6)
                   for(int count = 0; count < lotteryArray.length; count++)
                        double randomNumber = Math.random();
                        double biggerRandom = (randomNumber * 50);
                        int integerNumber = (int)biggerRandom;
                        if (lotteryArray == lotteryArray[count])
                             duplicate = true;
                        if (duplicate == false) //not a duplicate
                             lotteryArray[++count] = integerNumber;
                   displayNumbers(lotteryArray);
         }

  • Filling empty java array in C method

    Hi everyone,
    I'm passing to a C method an empty byte array from the Java Side. I want the C method to fill the Java byte array and return it at the end of the method to the java side.
    in the Java side, I have my byte array :
    byte[] myArray = null;
    then I'm passing the array to the C method as
    myMethod(myArray)
    in the C method I'M trying to access the array as follow :
    myMethod(jbyteArray myArray)
    jbyte* tab = *env)->GetByteArrayElements(env, myArray, 0);
    I'm getting an error at runtime. Can somebody help me with that issue please ? Thanks
    Sebastien

    You are not passing a byte array, you are passing null.
    If you want to pass a byte array you first have to create it using the new operator:
    byte[] myArray = new byte[theSizeOfTheArray];
    myMethod(myArray);If you want the JNI code to create the array, that is fine also, but in that case the native method would probably have to return the array instead of void.

Maybe you are looking for