Question on System.arraycopy method and multidimensional array

I'm trying to copy from single dimensional to multidimensional array using System.arraycopy method. The following is my problem.
1) I need to specify the index of the multidimensional array while copying. Can I do that ? If yes , how???
eg ; int a[] = new int[3];
int b[] = new int[3][2]; I need to copy from a to b
I tired the following and I'm getting an error.
System.arraycopy(a,0,b[][1],0,3);
How Can I achieve the above?? PLease Help --------------

Java doesn't have multidimensional arrays. When you see an int[][] it's an array of arrays of ints. The arrays of ints might have different lengths like this one:int[][] arr =
{{1,2,3,4},
{1,2,3},
{1,2},
{1}
};Do I need to say that arraycopy as you see it would fail in this case?
If you know what kind of arrays you'll have you can simply implement your own arraycopy method (but it will not be as effecient as System.arraycopy) with a simple for-loop.

Similar Messages

  • The System.arraycopy Functionality and copying array question

    When created arrays such as String[] myStringArray (for example), is it general good practice to use the System.arraycopy function to copy the array?
    Why isn't it good practice to use equal instead? Would this work just as well?
    String[] myStringArray = new String[] { "My", " Test"};
    String[] myStringArrayCopy = new String[myStringArray.length};
    myStringArrayCopy = myStringArrayCopy;Or is that just going to make them the same element in memory and if I change myStringArray in antoher part of the program that means myStringArrayCopy will change as well since it is the same thing?

    Youre right, the equals sign just assigns the new array same reference in memory as the old array so they are pointing to the same data.
    Im 90% sure of that.
    If you want to work with an array without changing the original array id suggest using the System.arraycopy method. If you dont mind the contents changing then use the = sign..(but then why use a new array at all?)
    Hope this helps, if not theres loads of more experienced people on the boards...
    Ocelot

  • Using System.arraycopy to copy an array into itself.

    I was wondering if there are any potential problems with using code similar to below?
    System.arraycopy(Global.queueUrgent, 1, Global.queueUrgent, 0, Global.queueUrgent.length-1); I have an array which works as a job queue. Another thread looks at this queue and then acts on it according to the data held in Global.queueUrgent[0]. Once this task has been accomplished, the first job is removed and the rest of the queue is brought forward one (and hence the code sample).
    I understand the risks of a race condition which might occur in my application and can prevent it as much as possible but I was wondering if there were any other concerns I should address. It's important that I use an array such as this for my project.
    I haven't tried to implement the code as of yet as I would like to hear your thoughts on it first.
    Regards,
    Robert (1BillionHex).

    user13702320 wrote:
    "If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array. "
    Yeah I understand that. I was just wondering if there was anything that I was missing.
    It says "as if" it is copied to a temporary array. Does it actually do this? If so and if I use a large array, would this have an impact on memory usage?It doesn't matter if it actually does it using a temporary array. The point is, it is safe to use the same array for src and dest. Note that java.util.ArrayList's 'remove' method uses exactly the code that you are using. I don't know about memory usage effects. If you do this manually, you do need to set Global.queueUrgent[Global.queueUrgent.length-1] to null to ensure that the objects will be able to be garbage-collected properly when it is time (see what ArrayList.remove does). If you don't, then if you had a 5-element array and remove all 5 elements, you will end up with 5 references to what was originally only in queueUrgent[4], and the object won't be eligible for garbage-collection.
    I did have the same question as Kayaman--why not use a real queue? There are several built-in classes that you can use, instead of using an array directly. You claimed that "It's important that I use an array such as this for my project.", but you didn't explain why you think you must use an array.

  • System.arrayCopy method

    Can someone explain why arrayCopy method is part of the System Class and not a part of the java.util.Arrays class?

    arrayCopy is a method that benefits from native implementation, so it is better placed in the System class.

  • Question about System.in, FileoutputStream and blocking

    Hello everybody,
    I have written a simple java program that read the System.in and append it to file (which is the first argument of the program).
    Here is the context: my client launch several instance of this program at the same time, with the same file passed in argument. In a first time, I did not use the FileChannel.lock() method because I didn't know there will be several instance, but this is not the question.
    The problem is simple: sometime, I can't figure why (and this is why I'm here to ask you), one of the process block, and stay like this until my client kill it.
    So why? It has something to do with the absence of FileChannel.lock()?
    My client is on Solaris, don't know which version, with a JDK 1.5.0_04
    Here is the code:
    InputStream is = System.in;
    InputStreamReader ir = new InputStreamReader(is, encodingMode);
    BufferedReader reader = new BufferedReader(ir);
    FileOutputStream fos = new FileOutputStream(args[0], true);
    String lineSeparator = System.getProperty("line.separator");
    String buf = null;
    while ((buf = reader.readLine()) != null) {
         fos.write(buf.concat(lineSeparator).getBytes(encodingMode));
    }I think the FileChannel.lock on the output file will solve the problem, but I'm just curious about that odd issue.
    Thanks for help, and excuse me for my bad english.

    Ok, I try to launch 20 occurences at the same time on opensolaris 2009.06 and here is what I've got:
    Error occurred during initialization of VM
    Could not reserve enough space for object heap
    # An unexpected error has been detected by Java Runtime Environment:
    # java.lang.OutOfMemoryError: requested 32756 bytes for ChunkPool::allocate. Out of swap space?
    #  Internal Error (allocation.cpp:120), pid=1603, tid=2
    #  Error: ChunkPool::allocate
    # Java VM: Java HotSpot(TM) Client VM (11.3-b02 mixed mode solaris-x86)
    # An error report file with more information is saved as:
    # /export/home/eric/SocGen/hs_err_pid1603.log
    # If you would like to submit a bug report, please visit:
    #   http://java.sun.com/webapps/bugreport/crash.jsp
    Error occurred during initialization of VM
    java/lang/ClassNotFoundException: error in opening JAR file /usr/jdk/instances/jdk1.6.0/jre/lib/rt.jarI've also got a nice core file and a hs_err_pid1603.log ( here: http://pastebin.com/m513df649
    Funny think is that I can't reproduce it on AIX.
    Hope that can help you helping me.
    Edited by: Eric-Fistons on 13 oct. 2009 13:43
    Edited by: Eric-Fistons on 13 oct. 2009 13:45

  • JNI and multidimensional arrays

    Hi
    the last days i spent searching information on how to process larger multidimensional primitive arrays ([5][300][300]) with JNI but i failed to find stringent proof for it is possible or not. Maybe somebody her can help:
    i want to pass a 3D array of ints to a c-function and do excessive manipulation there, then pass the array back. Possible? where can i find sources on that?
    Thanks for any help
    Shin

    Yes.. this is quite possible. To take your example, you would access foo[1][2][3] like this:jojbectArray middleArray = static_cast<jobjectArray>( env->GetObectArrayElement( fooArray, 1 ) );
    jintArray endArray = static_cast<jobjectArray>( env->GetObjectArrayElement( middleArray, 2 ) );
    int element = env->GetIntArrayElement( endArray, 3 );God bless,
    -Toby Reyelts
    Check out the free, open-source JNI toolkit, Jace - http://jace.reyelts.com/jace

  • Performance of System.arraycopy and Arrays.fill

    I have some code where I call a function about 1,000,000 times. That function has to allocate a small array (around 15 elements). It would be much cheaper if the client could just allocate the array one single time outside of the function.
    Unfortunately, the function requires the array to have all of its elements set to null. With C++, I would be able to memset the contents of the array to null. In Java, the only methods I have available to me are System.arraycopy() and Arrays.fill().
    Apparently, Arrays.fill() is just a brain-dead loop. It costs more for Arrays.fill() to set the elements to null than it does to allocate a new array. (I'm ignoring possible garbage collection overhead).
    System.arraycopy is a native call (that apparently uses memcpy). Even with the JNI overhead, System.arraycopy runs faster than Arrays.fill(). Unfortunately, it's still slower to call System.arraycopy() than it is to just allocate a new array.
    So, the crux of the problem is that the heap allocations are too slow, and the existing means for bulk setting the elements of an array are even slower. Why doesn't the virtual machine have explicit support for both System.arraycopy() and Arrays.fill() so that they are performed with ultra-efficient memsets and memcpys and sans the method call and JNI overhead? I.E. something along the lines of two new JVM instructions - aarraycpy/aarrayset (and all of their primitive brethern).
    God bless,
    -Toby Reyelts

    A newly allocated array begins its life with null in its elements. There is no need to fill it with null.
    As Michael already stated, I'm not redundantly resetting all of the elements to null. Here's some code that demonstrates my point. You'll have to replace my PerfTimer with your own high performance timer. (i.e. sun.misc.Perf or whatever) Also note that the reason I'm only allocating half the array size in allocTest is to more accurately model my problem. The size of the array I need to allocate is variable. If I allocate the array outside of the function, I'll have to allocate it at a maximum. If I allocate inside the function, I can allocate it at exactly the right size.import java.util.*;
    public class AllocTest {
      private static final int count = 100000;
      public static void main( String[] args ) {
        for ( int i = 0; i < 10; ++i ) {
          allocTest();
        double allocStartTime = PerfTimer.time();
        allocTest();
        double allocTime = PerfTimer.time() - allocStartTime;
        for ( int i = 0; i < 10; ++i ) {
          copyTest();
        double copyStartTime = PerfTimer.time();
        copyTest();
        double copyTime = PerfTimer.time() - copyStartTime;
        for ( int i = 0; i < 10; ++i ) {
          fillTest();
        double fillStartTime = PerfTimer.time();
        fillTest();
        double fillTime = PerfTimer.time() - fillStartTime;
        System.out.println( "AllocTime (ms): " + allocTime / PerfTimer.freq() * 1000 );
        System.out.println( "CopyTime (ms): " + copyTime / PerfTimer.freq() * 1000 );
        System.out.println( "FillTime (ms): " + fillTime / PerfTimer.freq() * 1000 );
      private static void allocTest() {
        for ( int i = 0; i < count; ++i ) {
          Object[] objects = new Object[ 8 ];
      private static void copyTest() {
        Object[] objects = new Object[ 15 ];
        Object[] emptyArray = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          System.arraycopy( emptyArray, 0, objects, 0, emptyArray.length );
      private static void fillTest() {
        Object[] objects = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          Arrays.fill( objects, null );
    }I getH:\>java -cp . AllocTest
    AllocTime (ms): 9.749283777686829
    CopyTime (ms): 13.276827082771694
    FillTime (ms): 16.581995756443906So, to restate my point, all of these times are too slow just to perform a reset of all of the elements of an array. Since AllocTime actually represents dynamic heap allocation its number is good for what it does, but it's far too slow for simply resetting the elements of the array.
    CopyTime is far too slow for what it does. It should be much faster, because it should essentially resolve to an inline memmove. The reason it is so slow is because there is a lot of call overhead to get to the function that does the actual copy, and that function ends up not being an optimized memmove. Even so, one on one, System.arraycopy() still beats heap allocation. (Not reflected directly in the times above, but if you rerun the test with equal array sizes, CopyTime will be lower than AllocTime).
    FillTime is unbelievably slow, because it is a simple Java loop. FillTime should be the fastest, because it is the simplest operation and should resolve to an inline memset. Fills should run in single-digit nanosecond times.
    God bless,
    -Toby Reyelts

  • System.arraycopy and Objects

    Hi,
    I currently have a 100 objects created in my program. Each object has a number of double arrays assosiated with it.
    During my code I use the System.arrayCopy method to copy the arrays from the best 50 objects into the worst 50 objects.
    This seems to work fine. However someone has told me that when u use the arrayCopy method instead of the array being copied a pointer is just created pointing to the original array ?? . So that if I then modify one of the values in the original array the copied array will also be changed .
    Is this correct ??? if it is how can I get around this problem ??
    Thank you
    Craig

    Why don't you try for yourself?int[] a = new int[] {
        1,
        2
    int[] b = new int[a.length];
    System.arraycopy (a, 0, b, 0, a.length);
    b[1] = 3;
    System.out.println (a[1]);Kind regards,
    Levi

  • How to change System Input Method ?

    I tried to write multilingual program.
    I have system input method and specific input method code (lib/ext).
    How to change System Input Method from a code ?
    or
    How to handle an event when i chage system input method in the Windows.
    (My OS is Windows XP).
    I tried to do (for example):
    java.awt.im.InputContext ic = this. getInputContext ();
    ic.selectInputMethod(new Locale ("ru"));
    It doesn't help.

    up

  • System.arraycopy (2 dim array) and growth of 2 dim array

    Hi everybody
    I am working on a program which contains a module that can perform Cartesian product on number of sets.
    The code I have developed so far is :
    import java.lang.reflect.Array;
    public class Cart5 {
    public static void main(String[] args) throws Exception
    int pubnewlength;
    // declare SolArray
    int[][] solArray;
    // initialize solArray
    solArray=new int[1][4];
    // Use for method
    for (int ii=0 ; ii<4 ; ii++)
    solver(solArray,ii);
    // Print the array ?
    System.out.println("\n  The array was changed ... " );
    }  // End main
    public void solver(int Solarray2[][] , int abi)
    int[][]  A  =  {  {1,2,3,5},
                      {4,6,7},
                      {11,22,9,10},
                      {17,33}
      jointwoArrays(solarray2,A,abi);
    // some other operations
    } // End Solver method
    public void jointwoArrays(int solarray3[][] , int aArray[][],int indexA)
    int y,u;
    int[][] tempArray;
    // calculate growth of rows:
    pubnewlength=solArray3.length * aArray[indexA].length;
    //Fill TempArray
    y=solArray3[0].length;
    u=solArray3.length;
    tempArray=new int[u][y];
    // Use system.arraycopy to copy solArray3 into tempArray -- How ?
    // Change the size of arrow to proper size -- How ?
    solArray3 = (int[][]) arrayGrow(solArray3);
    // Join operation - Still under construction
    for(int i = 0, k = 0; i < tempArray.length; i++)
                   for(int j = 0; j < set3.length; j++)
                                     for (q=0;q<=2;q++)             
                                      { solArray3[k][q] = tempArray[i][q];}
                                     solArray3[k][q]= aArray[indexA][j];
                                     ++k;
    } // End jointwoArrays method
    // This module is from http://www.java2s.com/ExampleCode/Language-Basics/Growarray.htm
        static Object arrayGrow(Object a) {
        Class cl = a.getClass();
        if (!cl.isArray())
          return null;
        Class componentType = a.getClass().getComponentType();
        int length = Array.getLength(a);
        int newLength = pubnewlength;
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(a, 0, newArray, 0, length);
        return newArray;
    } // End ClassI deeply appreciate your help with these 3 questions :
    1. How can I use system.arraycopy to copy my two dimensional array? I have searched but examples seem to be about one dim arrays.
    2. How can I change the "static Object arrayGrow(Object a)" , to grow my two dimensional array ?
    3. If you know any codes or articles or java code regarding cartesian products , please tell me.
    Thank you
    Denis

    1. How can I use system.arraycopy to copy my two
    dimensional array? I have searched but examples seem
    to be about one dim arrays.That's because you can't do it in one call. You need to create a loop which copies each 'row".
    >
    2. How can I change the "static Object
    arrayGrow(Object a)" , to grow my two dimensional
    array ?Why do you make it so complicated (generic). Make it take an int[][] array instead, and see the answer from above.
    >
    3. If you know any codes or articles or java code
    regarding cartesian products , please tell me.There are probably lots of them if you google.
    Kaj

  • Multidimensional array and chars

    Hi again,
    My apologies in advance if i can't word my question that well, i will try and be as clear and succinct as possible and hopefully for this newbie you can apprehend what i'm trying to figure out if i come up short.
    I'm trying to write a rather large control statement with a while loop and several nested ifs inside it that ultimately returns a single character after all is said and done, and then continually concatenates that character to a string which will eventually be output to a file. The part i'm stuck at is after i've changed the two letter characters into their ASCII values. I need to make the program take those two ASCII values and use them as a reference to a character in a multidimensional array of alphabetic characters, and then that character will be what is returned at the end.
    Here's the method, thanks in advance for your time.
    public String encode( String cipherKey )
            String textToEncode = input.next();
            String encodedText = " ";
            cipherKey = cipherKey.toUpperCase();
            textToEncode = textToEncode.toUpperCase();
            openFiles();
            int numberOfChars = textToEncode.length();
            int cipherPos = 0;
            int cipherLength = cipherKey.length();
            while (input.hasNext())
                for ( int count = 0; count < numberOfChars; count++ )
                    if (Character.isLetter(textToEncode.charAt(count)))
                        cipherPos %= cipherLength;
                        int xChar = (int) textToEncode.charAt(cipherPos);
                        int yChar = (int) textToEncode.charAt(count);
                        xChar -= 65;
                        yChar -= 65;
                        if ((xChar >= 0) && (xChar <= 25))
                            if ((yChar >= 0) && (yChar <= 25))
                        return ' ';
                     encodedText = encodedText +
        return encodedText; 
        }As you can see towards the end there are some incomplete statements where i became lost.

    its there, i couldnt c&p the whole program because it went over my character limit. Yeah it did compile but couldn't invoke my encode method without a NullPointerException.
    Here are the other methods in the class....
        public String setSource( String in )
            source = in;
            return source;
         Sets the value of the output file
         * @param out A <code>String</code> value representng name of output file.
         * @see #setSource
        public String setDestination( String out )
            destination = out;
            return destination;
         * Method to open both input and output files, and to test for exceptions
         * @see #encode
         * @see #decode
        private void openFiles()
        File inputFile = new File(source);  //Creates new file object from source file
        File outputFile = new File(destination);  //Creates new file object from destination file
            /* Tests whether input file exists and if so enables the Scanner
             * to read the data in from the source file. Catches SecurityException and
             * FileNotFoundException amd prints appropriate messages to user.
            if (inputFile.exists())
                try
                    input = new Scanner( new File( source ) );
                    FileReader reader = new FileReader(inputFile);
                    BufferedReader BufferIn = new BufferedReader(reader);
                catch ( SecurityException securityException )
                    System.err.println("You do not have read access to this file.");
                    System.exit( 1 );
                catch ( FileNotFoundException filesNotFoundException )
                    System.err.println("Error: File does not exist.");
                    System.exit( 1 );         
            /* Tests whether output file exists and if it does enables Formatter
             * to write encoded output to file. Catches SecurityException and
             * FileNotFoundException and prints appropriate message to user.
            if (outputFile.exists())
                try
                    output = new Formatter( new File( destination ) );
                catch ( SecurityException securityException )
                    System.err.println("You do not have write access to this file.");
                    System.exit( 1 );
                catch ( FileNotFoundException filesNotFoundException )
                    System.err.println("Error: File does not exist.");
                    System.exit( 1 );
         * Closes both input and output files after output file has been written
         * to.
         * @see #openFiles
        private void closeFiles()
            if ( output != null )
                input.close();
                output.close();
        }Edited by: fearofsoftware on Apr 17, 2009 8:35 PM

  • JNI multidimensional Array and OpenCV

    Hello everybody,
    my first post, so lets go..
    At the moment I am writing my thesis in the filed of automatic image classification. The project is written in Java, but I wanna use the OpenCV library from Intel (http://sourceforge.net/projects/opencvlibrary/) for facedetection.
    So far I managed to call the native method from Java. What I do I parse the path of the image to be analyzed as a string to my C++ programm. The faces are being detected and written into a so called CvSeq (http://www.comp.leeds.ac.uk/vision/opencv/opencvref_cxcore.htm#cxcore_ds_sequences) which holds the coordinates of the rectangles surrounding the found faces. Until now I can only call cvSeq->total which gives me the total number of faces as ints. That integer I return to my java api.
    What I don't know is, how to return a multidimensional array (2 dimensions) where the first dim contains the path as a string to the file and the second dimension 3 integers for x,y coordinates and the lenght of each rectangle.
    Or better, I might know how to return that Array, but not how to create it.
    I know this is somewht OpenCV specific, but maybe someone knows anything. Any little help would be greatly appreciated. Thanks a lot!!!!
    Regards
    Carsten
    attached: JNI source code
    /////////////////////////////////////////// source code ///////////////////////////////////////////////
    #include "cv.h"
    #include "highgui.h"
    #include "cxcore.h"
    #include "cxtypes.h"
    #include "cvaux.h"
    #include "org_kimm_media_image_data_JNIOpenCV.h"
    #include <stdio.h>
    JNIEXPORT jint JNICALL
    Java_org_kimm_media_image_data_JNIOpenCV_getFaces(JNIEnv *env, jobject object, jstring path)
    //declarations
    CvHaarClassifierCascade *pCascade = 0;
    CvMemStorage *pStorage = 0;
    CvSeq *pFaceRectSeq;
    int scale=1;
    jobjectArray recPoints;
    const char *str = env->GetStringUTFChars(path, 0);
    //initializations
    IplImage* pInpImg = cvLoadImage(str, CV_LOAD_IMAGE_COLOR);
    IplImage* small_image = pInpImg;
    pStorage = cvCreateMemStorage(0);
    pCascade = (CvHaarClassifierCascade *)cvLoad
         (("C:/OpenCV/data/haarcascades/haarcascade_frontalface_default.xml"),0, 0, 0 );
    //validaste that everything initilized properly
    if( !pInpImg || !pStorage || !pCascade)
         printf("Initialization failed: %s \n",
              (!pInpImg) ? "didn't load image file" :
              (!pCascade) ? "didn't load Haar Cascade --"
                   "make sure Path is correct" :
              "failed to allocate memory for data storage");
         exit(-1);
    //performance boost through reducing image size by factor 2          
              small_image = cvCreateImage( cvSize(pInpImg->width/2,pInpImg->height/2), IPL_DEPTH_8U, 3 );
    cvPyrDown( pInpImg, small_image, CV_GAUSSIAN_5x5 );
    scale = 2;
    //detect faces in image
    pFaceRectSeq = cvHaarDetectObjects(small_image, pCascade, pStorage,
                                            1.1,                                        //increase search scale by 10% each pass
                                            6,                                        //drop group of fewer than three detections
                                            CV_HAAR_DO_CANNY_PRUNING,          //skip regions unlikely to contain faces
                                                 cvSize(50,50));                         //use XML default for smallest search scale
    //initialize array for location of the faces (HERE IS WHERE I GET INTO TROUBLE!!!!!)
    int x = pFaceRectSeq->total;
    jclass intArrCls = env->FindClass ( "[I" ) ;
    recPoints = env->NewObjectArray ( x, intArrCls, NULL ) ;
    //for(int j = 0; j <= x; j++) {
    //   recPoints[j] = (jintArray)env->NewIntArray(3);
    for(int i=0;i<(pFaceRectSeq ? pFaceRectSeq->total:0); i++)
                                       CvRect* r = (CvRect*)cvGetSeqElem(pFaceRectSeq, i);
                                       CvPoint pt1 = {(r->x)*scale, (r->y)*scale};
                                       CvPoint pt2 = {(r->x + r->width)*scale, (r->y + r->height)*scale};
    //env->SetObjectArrayElement(recPoints,i, pt1.x);
    return pFaceRectSeq->total;
    }

    Any Java array you can consider like one-dimensional array of arrays n-1 dimension. For example, you have a 3 dim. array of objects:
    Object[][][] arr = new Object[1][2][6]; It can be considered as a set of one-dimensional arrays:
    ==========================================
    |  dim   |           Type
    ==========================================
      0          1 element, an array of type �[[Ljava/lang/Object;�
      1          1 x 2 elements , an arrays of type �[Ljava/lang/Object;�
    So you can convert three-dimensional array to one-dimensional array like in C++:
    |�[Ljava/lang/Object;� | �[Ljava/lang/Object;� | �[Ljava/lang/Object;�
         6 objects                 6 objects                 6 objects

  • System.arraycopy for arrays of  2 dimensions?

    Can it be used for 2 dimensional arrays? How? My problem becomes more specific what the length parameter concerns.
    Thanks
    static void      arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    That means, that if i want to create a deep copy of a 2dimensional array, i have to:
    -either create a new array, scan the first one and place the values in the new one
    -or do something like this:
        Object[][] gameBoardCopy()
            Object[][] cloneBoard=new Object[8][8];
            System.arraycopy(this.board, 0, cloneBoard, 0,  8);
            for (int i=0; i<8; i++)
                System.arraycopy(this.board, 0, cloneBoard[i],0, 8);
    What do you suggest?

  • A question on methods and parameters.

    Hey guys, it's my first time posting here. I'm very new to Java, and did a bit of C++ prior to Java. I had a question on methods and parameters. I don't quite understand methods; I know that they can be repeated when called, but thats almost about it. I also know that a program must have one class that holds the main method. What I truly, truly don't understand about methods is what parameters are. I know they go in the parentheses, and that's it. Could you please explain what they are? I truly appreciate it. Thanks to all in advance. Regards, Michael

    Taking an example :
    Suppose you are calculating area of rectangle you need two inputs one is length and breadth.Area = l X b where l = length, b = breadth
    So your method, say, calculateAreaOfRectangle(int length, int breadth) will have two input parameters as arguments.
    System.out.println("Area of rectangle:"+calculateAreaOfRectangle(40,30);
    public int calculateAreaOfRectangle(int length, int breadth) {
    int Area;
    Area = length * breadth;
    return Area;
    So if you call this method then the output will be returned as 120.
    Parameters of a method are just the input variables needed for the method to process for any calculations or anything useful.
    And we cant have methods inside main method in Java. It is against the java syntax and if you do, it will throw a syntax error.

  • HT201363 I but a reedem card of $15 dollars I put the code and star asking security questions I put the answer and the systems tell me is incorect. I need help

    I but a reedem card of $15 dollars to buy music and I put the code and star asking security questions I put the answer and the systems tell me is incorect. I need help

    Click here for information. If you can't reset them through the method described in that article or by sending yourself a rescue email(the email may take a few hours to arrive), contact the iTunes Store staff via the link in the 'Additional Information' section.
    It isn't possible to create a rescue email address without correctly answering two of the questions.
    (99350)

Maybe you are looking for