0

How can I print the values in main method? How ca convert multidimensional array to string.

How can I iterate the multidimensional array ?

public class Javaclass {


    public Object[][] method4(){
         String [][]type={{"prasad","manju","kishor","vinod"},
                {"aaa","bbb","ccc","ddd"}};
        return type;
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Javaclass jc = new Javaclass();

        System.out.println(Arrays.toString(jc.method4()));
    }

}
Vinod
  • 2,263
  • 9
  • 55
  • 104
  • How did you want to format it? You can use a [for-each loop](http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html) and print each array however you want. – Elliott Frisch Apr 18 '14 at 12:51

2 Answers2

3

You could use deepToString

System.out.println(Arrays.deepToString(javaClass.method4()));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • How can I iterate the 2D Array – Vinod Apr 18 '14 at 12:51
  • unless you require particular formatting for the output deepToString will display the contents of the 2D array. Given that Java provides this functionality out the box you don't need to iterate :) – Reimeus Apr 18 '14 at 13:18
0

Simple one-line formatting

System.out.println(Arrays.deepToString(method4()));

Simple 2-dimensional print

If you want a 2-dimensional print, you might need to iterate over the first dimension and use Arrays.toString() for the second:

for (Object[] line : method4()) {
    System.out.println(Arrays.toString(line));
}

Custom display (iteration on the array)

Use nested for loops, and do anything you want. For instance:

for (Object[] line : method4()) {
    for (Object cell : line) {
        System.out.print(cell.toString());
    }
    System.out.println();
}

Note: this is probably too simple, every cell would be printed next to each other without separator. But I think you got the idea, and you can add whatever complexity you need.

Joffrey
  • 32,348
  • 6
  • 68
  • 100