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.

1
  • 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. Commented May 28, 2017 at 1:46

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.