Coding enhancement

public static int[][] getArray(){
  return  new  int[5][6]; // no need of intermediate object
}

Optimizing speed : never have a computation or an evaluation at each loop, car be very heavy with great number

 for(int i = 0, n = array.lenght;  i < n ; i++) { ..

as init_array return array you can write directly :

printArray(init_array(getArray()));

Use :

  • System.getProperty("line.separator"); for all OS
  • StringBuilder then print out :

.

public static void printArray(int[][] array){
           String NEWLINE = System.getProperty("line.separator"); // You can put it 'public static' elsewhere
           StringBuilder sb = new StringBuilder(); // you can give the size of it between ()
           for(int i = 0; i< array.length;i++)
              for(int j =0; j< array[i].length;j++)
                  sb.append(array[i][j])
                  sb.append(NEWLINE);
              }
           }
           System.out.println(sb.toString());
        }
Answer from cl-r on Stack Exchange
🌐
Reddit
reddit.com › r/learnprogramming › [java] printing out a row in a 2d array
r/learnprogramming on Reddit: [Java] Printing out a row in a 2d array
January 7, 2021 -

Tried printing out the rows in a 2d matrix using this code:

class Main {  
  public static void main(String args[]) { 
    int[][]matrix = { {1,2,3},
                   {4,5,6},
                   {7,8,9},
                   {1,2,1} };
                   
                 
    for(int[] row: matrix){
        System.out.println(row);
    }

  } 
  
}

It doesn't work. I get this on the compiler:

[I@76ed5528
[I@2c7b84de
[I@3fee733d
[I@5acf9800

What's going on?

🌐
Codecademy
codecademy.com › learn › learn-java › modules › java-two-dimensional-arrays › cheatsheet
Learn Java: Two-Dimensional Arrays Cheatsheet | Codecademy
//Given a 2d array called `arr` which stores `int` values ... In Java, initializer lists can be used to quickly give initial values to 2D arrays.
Discussions

The best way to print a Java 2D array? - Stack Overflow
I was wondering what the best way of printing a 2D array in Java was? I was just wondering if this code is good practice or not? Also any other mistakes I made in this code if you find any. int row... More on stackoverflow.com
🌐 stackoverflow.com
Help with printing a two dimensional array

Is your issue with printing a matrix or table, or is your issue with the array index being out of bounds?

More on reddit.com
🌐 r/javahelp
3
9
September 6, 2020
[Java] Printing out a row in a 2d array
That’s how Java prints arrays. You’ll need to wrap the array in Arrays.toString(array) or alternatively loop over the array printing out results More on reddit.com
🌐 r/learnprogramming
2
1
January 7, 2021
How to print a 2-D array with initial values in a table-like ...
🌐 r/javahelp
🌐
Coderanch
coderanch.com › t › 650514 › java › Printing-Array-String-specific-format
Printing a 2d Array to String in specific format (Beginning Java forum at Coderanch)
May 27, 2015 - Don't call the String array; that is very confusing. Don't call the parameter m. That is a dreadful name. Why are you using System.out. when your method says it returns a String? Make the method return the String and do nothing else, least of all printing. You can always test it with System.out.println(MyArrayClass.toString(myArray)); Why are you using for loops when you can use for‑each loops?
🌐
FavTutor
favtutor.com › blogs › print-2d-array-in-java
Print a 2D Array or Matrix in Java: 4 Easy Methods (with code)
June 16, 2023 - In 2D arrays, arr.length returns the number of rows it has, and performing the same operation on any one of its indices (for example arr[0].length) will return the number of columns in the array. It’s great that now you know how to print matrices in Java, now you should also learn sorting algorithms in Java.
🌐
C# Corner
c-sharpcorner.com › article › printing-a-2d-array-in-java-with-code
Printing a 2D Array in Java with Code
January 23, 2025 - public class Print2DArray { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 0, 6}, {7, 8, 9} }; System.out.println("Printing 2D Array using For-Each Loop:"); for (int[] row : matrix) { // Iterate through each row for ...
Find elsewhere
🌐
Quora
quora.com › How-do-I-print-the-most-common-digit-in-a-2D-array-using-Java
How to print the most common digit in a 2D array using Java - Quora
Answer (1 of 4): How would you do it be hand? Pick a small array, 5x5 is large enough, and figure out what you would do to figure it out by hand. What would you keep track of? How would you know which digit to print? There are a whole lot of programming problems that are that easy (or that hard ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › multidimensional-arrays-in-java
Java Multi-Dimensional Arrays - GeeksforGeeks
... import java.io.*; class Main ... the Array for (int i = 0; i < 2; i++){ for (int j = 0; j < 2; j++) System.out.print(arr[i][j]+" "); System.out.println(); } } }...
Published   March 14, 2026
🌐
GeeksforGeeks
geeksforgeeks.org › java › print-2-d-array-matrix-java
Print a 2D Array or Matrix in Java - GeeksforGeeks
March 24, 2025 - // Java program to print the elements of // a 2 D array or matrix using toString() import java.io.*; import java.util.*; // Driver Class class Geeks { public static void print2D(int mat[][]) { // Loop through all rows for (int[] row : mat) // converting each row as string // and then printing in a separate line System.out.println(Arrays.toString(row)); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); } } ... Example 4: Using Arrays.deepToString(int[][]) converts the 2D array to a string in a single
🌐
Reddit
reddit.com › r/javahelp › help with printing a two dimensional array
r/javahelp on Reddit: Help with printing a two dimensional array
September 6, 2020 -

Hello everyone,

for a uni assignment I have to write a method that prints a grid view of a list of titles with three titles in a row. To achieve that, my idea is to first trim pr pad the titles so they have the same length, then create a two dimensional array with three titles in each subarray. Lastly, I want to loop through the array (of arrays) and print each subarray in one row. The padding and trimming works just fine, but there seems to be a problem with the creation of the 2D-array. When I try to print it, nothing happens. The code compiles just fine though. It looks like this:

    public void printGridView()
    {
        // First, get all currently stored titles and trim them to size

        String[] fittedTitles = new String[movies.size()];
        String fittedTitle = "";
        int index = 0;
        
        for (Movie movie : movies) {
            int len = movie.getTitleLength(movie.getTitle());

            if (len > 21){
                fittedTitle = movie.trimTitle(movie.getTitle());
            } else if (len < 21) {
                fittedTitle = movie.padTitle(movie.getTitle());
            }

            fittedTitles[index] = fittedTitle + " (" + movie.getYearOfRelease() + ")"; // add the year to the array for easier printing
            index++;
        }

        
        // Next, create an array for each row of threes to be printed

        int rest = fittedTitles.length % 3; // determine whether there is an array with less than 3 columns
        int chunks = fittedTitles.length / 3 + (rest > 0 ? 1 : 0); //adds an extra array if there is a rest
        String[][] arrays = new String[chunks][];
        

        for (int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++) {
            arrays[i] = Arrays.copyOfRange(fittedTitles, i * 3, i * 6); // Exception with copyOfRange: array building doesn't work correctly. 
        }

        if (rest > 0){
            arrays[chunks-1] = Arrays.copyOfRange(fittedTitles, (chunks-1) * 3, (chunks-1) *  (3 + rest)); // makes an extra array with less than three titles
        }
        
        // quick test if array was built correctly
        for (int i = 0; i < arrays.length; ++i) {
            for(int j = 0; j < arrays[i].length; ++j) {
                System.out.println(arrays[i][j]);
            }
        }
        
        // Finally, print each row of threes accordingly

        int i = 0;

        if (rest == 0) { // in case of even rows of threes
            for (i = 0; i < arrays.length; i++) {
                System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
                System.out.println("||                            ||                            ||                            ||");
                System.out.println("|| " + arrays[i][0] + " || " + arrays[i][1] + " || " + arrays[i][2] + " ||");
                System.out.println("||                            ||                            ||                            ||");
                System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
            }
        } else if (rest == 2) { // in case of uneven rows with 2 left
            String[] array = arrays[i]; 
            while (i < (arrays.length-1)) {
                System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
                System.out.println("||                            ||                            ||                            ||");
                System.out.println("|| " + array[0] + " || " + array[1] + " || " + array[2] + " ||");
                System.out.println("||                            ||                            ||                            ||");
                System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
                i++;
            }
            System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
            System.out.println("||                            ||                            ||");
            System.out.println("|| " + array[0] + " || " + array[1] + " ||");
            System.out.println("||                            ||                            ||");
            System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
        } else {
            String[] array = arrays[i]; 
            while (i < (arrays.length-1)) { // in case of uneven rows with one left
                System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
                System.out.println("||                            ||                            ||                            ||");
                System.out.println("|| " + array[0] + " || " + array[1] + " || " + array[2] + " || ");
                System.out.println("||                            ||                            ||                            ||");
                System.out.println("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
                i++;
            }
            System.out.println("||||||||||||||||||||||||||||||||");
            System.out.println("||                            ||");
            System.out.println("|| " + array[0] + " ||");
            System.out.println("||                            ||");
            System.out.println("||||||||||||||||||||||||||||||||");
        }

    }

When I try to print the 2D-array into the grid view, I get the exception

"java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0".

I have tried to recreate a case of 3 titles by hand and found no mistakes, I feel like it should work or at least give me the same errors for both ways of printing and I'm at my wits end.

Can somebody help please?

🌐
Medium
alokkumar-17171.medium.com › how-to-print-contents-of-2d-array-properly-without-loop-java-a548d723e396
How to print contents of 2D array properly without loop — Java | by Alok Kumar - Software Engineer - OPEN FOR WORK - | Medium
February 11, 2024 - package com.arrays; import java.util.Arrays; public class SortArray { public static void main(String[] args) { // TODO Auto-generated method stub int[][] arr = {{2, 5, 15},{1, 2, 8},{3, 5, 10},{4,4,20}}; Arrays.sort(arr,(x,y)->{ if(x[1]==y[1]) return x[2]-y[2]; return x[1]-y[1]; }); // Output - [[1, 2, 8], [4, 4, 20], [3, 5, 10], [2, 5, 15]] System.out.println(Arrays.deepToString(arr)); // Output - [[I@6ff3c5b5 System.out.println(arr); } } The above issue occurs not only with 2D array but also with normal array. ... package com.arrays; import java.util.Arrays; public class Print1DArray { public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = {34,12,11,89,42,67}; // Output - [34, 12, 11, 89, 42, 67] System.out.println(Arrays.toString(arr)); // Output - [I@4dc63996 System.out.println(arr); } }
🌐
Baeldung
baeldung.com › home › java › java array › print a java 2d array
Print a Java 2D Array | Baeldung
August 23, 2024 - The most straightforward method involves using nested loops to iterate through the rows and columns of the 2D array. This method is simple and intuitive, making it an excellent choice for basic array printing.
🌐
LeetCode
leetcode.com › problems › transpose-matrix
Transpose Matrix - LeetCode
Can you solve this real interview question? Transpose Matrix - Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. [https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png] Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: matrix = [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]] Constraints: * m == matrix.length * n == matrix[i].length * 1
🌐
Medium
medium.com › @amankseth › 2-d-array-in-java-5dc753a41c77
2-D Array Print in Java. Format to print | by Aman Kumar Seth | Medium
September 28, 2024 - But, wait we have something which is called as Arrays.deepToString() method, let’s see how it works: import java.util.Arrays; public class Array2D { public static void main(String[] args) { int[][] arr = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9} }; ...
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_indexing.asp
NumPy Array Indexing
import numpy as np arr = np.array([[1,2,3,4,5], [6,7,8,9,10]]) print('Last element from 2nd dim: ', arr[1, -1]) Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: ...
🌐
C# Corner
c-sharpcorner.com › article › 2d-array-take-input-and-print-output-same
2D array - Take Input and Print Output Same
May 10, 2024 - import java.util.*; // Online Java Compiler // Use this editor to write, compile and run your Java code online public class Main { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int m = scn.nextInt(); int [][] mat = new int [n] [m]; // System.out.println("rows " + mat.length); // System.out.println("column "+ mat[0].length); for (int i =0; i <n; i++) { for (int j =0; j < m ; j++) { mat[i][j]= scn.nextInt(); } // System.out.println(); } for(int i =0; i <n ; i++) { for (int j =0; j < m; j++) { System.out.print(mat[i][j]+" "); } System.out.println(); } } } Reading dimensions of the 2D array. ... These lines use the nextInt () method of the Scanner class to read two integers entered by the user, which represent the number of rows (n) and the number of columns (m) of the 2D array, respectively.
🌐
TutorialsPoint
tutorialspoint.com › print-a-2d-array-or-matrix-in-java
Print a 2D Array or Matrix in Java
September 14, 2023 - public class Print2DArray { public ... our matrix. for (int j = 0; j < matrix[i].length; j++) { //this equals to the column in each row. System.out.print(matrix[i][j] + " "); } System.out.println(); //change line on console as row comes to end in the matrix....
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › introduction-to-arrays-data-structure-and-algorithm-tutorials
Array Introduction - GeeksforGeeks
February 16, 2026 - Java · // Fixed sized array examples int[] arr1 = new int [5]; // Another way (Array creation and // initialization both) int[] arr2 = {1, 2, 3, 4, 5}; Python · # Create a fixed-size list of length 5, # initialized with zeros arr = [0] * 5 # Output the fixed-size list print(arr) C# // Fixed sized array examples int[] arr1 = new int [5]; // Another way (Array creation and // initialization both) int[] arr2 = {1, 2, 3, 4, 5}; 2.