1

is it possible to use a reference and pass it to a method as a argument and do the initialization in the method body in java? what i mean is this: i have a method that get's a array as parameters:

public static void arrayreader(int [] [] m){
int rows,cols;
rows=input.nextInt();cols=input.nextInt();
m = new int [rows][cols];
for(int i=0;i<rows;i++){
    for(int j=0;j<cols;j++){
       m[i][j] = input.nextInt();
       }
   }
}

i want to do the initialization of array in the method body not in the main method but java dont allow that and says it's not initialized

4
  • No, you cannot do that, all variables should be initialized before using it Commented Dec 27, 2012 at 8:31
  • @PradeepSimha all local variables and final should be initialized before using them , not instance vars Commented Dec 27, 2012 at 8:32
  • @GanGnaMStYleOverFlowErroR..yes, but I think OP hasn't mentioned in question. Thanks.. :) Commented Dec 27, 2012 at 8:35
  • No you cannot do that. Because Java dosent know you are initializing in your passing method or not. Commented Dec 27, 2012 at 8:36

5 Answers 5

3

If you made that array a return value instead of a parameter, your main method can look like this:

int[][] m = arrayreader();
Sign up to request clarification or add additional context in comments.

Comments

1

You can't, because when you say:

m = new int [rows][cols];

You are effectively assigning a new array to "m" reference(pointer), thus you are losing the reference to the array passed as argument.

4 Comments

tnx but why this happening?u mean java will generate 2 reference's that the first one will be garbage collected and the 2nd one will be used?
Do you understand the notion of pointer (like in C language)? If so, "m" is a pointer. In main() you point m to a memory zone containing an array, but then in arrayreader() you point it to a new zone containing a new array. Thus, what you say it's true, the first array will be garbage collected if no one else "points" at it (if you, for example, have assigned it to a variable in main() it won't be garbage collected)
Also: parameters in Java are always passed by-value. When you pass a reference to an object (an array is also an object) you pass the reference by-value. That means, that if you assign something to the parameter, you are not reassigning the reference object, but the reference itself: you are pointing the reference to a new object inside the method, but that does not affect the outside-of-the-method world.
You could then mark the answer as the solution if you feel it is the valid one.
1

if you would like to initialise an array in the method, than there is no need to pass it as a parameter

you can do something like this instead

public static int[][] arrayreader()
{
   int rows,cols;
   int[][] result = new int[rows][cols];

   rows=input.nextInt();
   cols=input.nextInt();

   for(int i=0;i<rows;i++)
   {
       for(int j=0;j<cols;j++)
       {
           result[i][j] = input.nextInt();
       }
   }

   return result;
}

1 Comment

What is m in m[i][j]? And you forgot to return the array.
0

you can also create the array object in main like:

int rows,cols;
rows=input.nextInt();cols=input.nextInt();
m = new int [rows][cols];

and then can have the function like:

public static void arrayreader(int [] [] m, int rows, int cols){
 for(int i=0;i<rows;i++){
   for(int j=0;j<cols;j++){
      m[i][j] = input.nextInt();
   }
 }
}

5 Comments

Java doesn't pass an int as a reference, it uses values instead. I don't think your code is going to work... Unless you remove the "m" parameter from the second method and make the 1st initialisation of "m" as global
did you try the similar code (as I mention)? It'll work as we are just assigning the values to the same array object
then you don't need to pass it as a parameter
if both (main and this function) are not in the same class, we may need to pass it
or if array is declared in the main method, we do need to pass it
0

Taking into account that I spent one day due to errors like:

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:907)

I implemented all the ideas from above in the code bellow which works like a charm for matrix multiplication:

import java.util.*;

public class MatmultC
{
private static Scanner sc = new Scanner(System.in);
  public static void main(String [] args)
  {
    int m = sc.nextInt();
    int n = sc.nextInt();
    int a[][] = new int[m][n];
    arrayreader(a,m,n);
    printMatrix(a);

    int[][] b = readMatrix();
    printMatrix(b);

    int[][] c=mult(a,b);
    printMatrix(c);

  }

   public static void arrayreader(int [][] m, int rows, int cols) {
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
              m[i][j] = sc.nextInt();
           }
       }
   }


   public static int[][] readMatrix() {
       int rows = sc.nextInt();
       int cols = sc.nextInt();
       int[][] result = new int[rows][cols];
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
              result[i][j] = sc.nextInt();
           }
       }
       return result;
   }


  public static void printMatrix(int[][] mat) {
  System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
       int rows = mat.length;
       int columns = mat[0].length;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.printf("%4d " , mat[i][j]);
           }
           System.out.println();
       }
       System.out.println();
   }

   public static int[][] mult(int a[][], int b[][]){//a[m][n], b[n][p]
   if(a.length == 0) return new int[0][0];
   if(a[0].length != b.length) return null; //invalid dims

   int n = a[0].length;
   int m = a.length;
   int p = b[0].length;

   int ans[][] = new int[m][p];

   for(int i = 0;i < m;i++){
      for(int j = 0;j < p;j++){
         for(int k = 0;k < n;k++){
            ans[i][j] += a[i][k] * b[k][j];
         }
      }
   }
   return ans;
   }

}

where as input matrix we have inC.txt

4 3
1 2 3
-2 0 2
1 0 1
-1 2 -3 
3 2
-1 3
-2 2
2 1

in unix like cmmd line execute the command:

$ java MatmultC < inC.txt > outC.txt

and you get the output

outC.txt

Matrix[4][3]
   1    2    3 
  -2    0    2 
   1    0    1 
  -1    2   -3 

Matrix[3][2]
  -1    3 
  -2    2 
   2    1 

Matrix[4][2]
   1   10 
   6   -4 
   1    4 
  -9   -2 

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.