How to fill matrix in spiral order Java

public class SpiralMatrix {
    public static void main(String[] args) {
        int[][] matrix = new int[7][7];
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        int index = 1;

        while (left <= right && top <= bottom) {
            for (int col = left; col <= right; col++) {
                matrix[top][col] = index++;
            }

            top++;
            for (int row = top; row <= bottom; row++) {
                matrix[row][right] = index++;
            }

            right--;
            for (int col = right; col >= left ; col--) {
                matrix[bottom][col] = index++;
            }

            bottom--;
            for (int row = bottom; row >= top ; row--) {
                matrix[row][left] = index++;
            }

            left++;
        }


        for (int row = 0; row < matrix.length; row++) {
            for (int col = 0; col < matrix[0].length; col++) {
                System.out.printf("%02d ", matrix[row][col]);
            }
            System.out.println();
        }
        
        // result:
        // 01 02 03 04 05 06 07
        // 24 25 26 27 28 29 08
        // 23 40 41 42 43 30 09
        // 22 39 48 49 44 31 10
        // 21 38 47 46 45 32 11
        // 20 37 36 35 34 33 12
        // 19 18 17 16 15 14 13
    }
}