Java: Jagged Arrays

By Xah Lee. Date: . Last updated: .

You can create a 2D array with m rows and each row have different number of slots.

public class Aj {
    public static void main(String[] args) {

        int[][] myA = { { 3, 4, 5 }, { 77, 50 }};

        for (int i = 0; i < myA.length; i++) {
            for (int j = 0; j < myA[i].length; j++) {
                System.out.print(myA[i][j] + " ");
            }
            System.out.println();
        }
    }
}

// prints
// 3 4 5 
// 77 50

Normally, array creation takes 3 steps in java:

There's a irregular syntax that does all the above steps in one, like this: int[][] myA = { { 3, 4, 5 }, { 77, 50 }};.

Note: even though the leafs of a array can be jagged, but not any middle level nodes. So, arbitrary tree cannot be created as array. For example, you cannot create a array with a shape like this: { { 3, 4, 5 }, { 77, 50, {1, 2} }}

Java

  1. Install
  2. javac java jar javadoc

Java Basics

  1. Print String
  2. Strings
  3. Power Function
  4. Java Types and Type Conversion
  5. Function
  6. Arrays

Class, Inheritance

  1. extends
  2. Constructor
  3. Constructor Return Type
  4. Extending a Class that has Explicit Constructors
  5. static
  6. this
  7. super
  8. Access Specifiers

Abstract class, Interface

  1. abstract
  2. Interface

Package

  1. Package

Misc

  1. Collection, Map
  2. Read/Write File
  3. Convert File Encoding
  4. Complex Numbers in Java
  5. Unicode
  6. Number Literals