2

Given a class named ThisClass that contains only this:

public static void main(String[][] args) {
    System.out.println(args[0][1]);
}
public static void main(String[] args) {
    ThisClass app = new ThisClass();
    String[][] newargs = {args};
    app.main(newargs);
}

If you compile it and then run it with java ThisClass a b c it prints: b

...so it's taking the first array and automatically wrapping it to fit the 2d array?? That is weird. Can someone break down what is going on here? I'm pretty sure I'm missing something.

user447607
  • 5,149
  • 13
  • 33
  • 55
  • 2
    There really aren't any '2d' arrays in java, just arrays of arrays. There's no automatic wrapping, you took an array and then stuck it inside another array using the array literal syntax. Thus you made an array of arrays. – pvg May 28 '17 at 01:46

2 Answers2

1

In System.out.println(args[0][1]);, the args[0] is the same String[] as in

public static void main(String[] args) {
    ThisClass app = new ThisClass();
    String[][] newargs = {args};
    app.main(newargs);
}

Because newargs contains one element, the String[] args. Thus, you are printlng args[1] which is b.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

The second main function is being called (the one that takes String[] as an argument).

In this function, you create newArgs to be a 2D array that contains only one element and this element is the array {a, b, c}.

Therefore, when you print args[0][1], you print the element at index 1 of the array {a, b, c}, which is b!

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118