• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

2D array

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, another confusing (in the sense that I'm confused!) question from
Glenn, Mitchell. OCAJP Oracle Certified Associate Java SE 8 Programmer Practice Exams (Kindle Locations 11618-11624). Enthuware. Kindle Edition. :

Given:

The above program is compiled with the command line:
javac FunWithArgs.java and then run with: java FunWithArgs a b c What will be the output?
Select 1 option A. It will not compile. B. It will throw ArrayIndexOutOfBoundsException at run time. C. It will print b D. It will print null

Now, the correct answer is C.What I don't get here is the fact aht when we create a 2d array usually we declare it like this: String[][] newargs = {{"a","b","c"}};, with two sets of curly brackets,  whereas here we declare it like String[][] newargs = {args}, so where on earth is the second set of brackets coming from?!
 
Henry Wong
author
Marshal
Pie
Posts: 22094
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:What I don't get here is the fact aht when we create a 2d array usually we declare it like this: String[][] newargs = {{"a","b","c"}};, with two sets of curly brackets,  whereas here we declare it like String[][] newargs = {args}, so where on earth is the second set of brackets coming from?!


Well, obviously, there are many ways to declare arrays -- and this one seems to be different than what you are used to. Anyway, ...



On the left hand side, "newargs" is declared as an array to an array of String objects. On the right hand side, it is an array with a single element. And that single element is an array of String objects (see the declaration of the "args" variable). So, basically, the right side is also an array of array of strings.

Hope this helps,
Henry
 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah OK, so that's where the extra pair of brackets come from then...
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3817
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, a multi dimensional array is simply an array of arrays. So if you have a two dimensional array, each element of that array is a one dimensional array. args is a one dimensional array and by putting it inside { and }, you are creating a two dimensional array.

BTW, your doubt indicates to me that you haven't gone through a good book before attempting the mock exams. I would strongly advice you to first go through a book to learn the basics and then attempt mock exams to make the best out of them.

HTH,
Paul.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic