programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# array length

Ranch Hand
Posts: 255
If you have a two-dimensional array, how do you get the length of both dimensions? If I have

int a;
int b;
String[] [] twoD = new String[a][b];

int firstLength = twoD.length;

I can get the value of a. But how do I get the value of b? How do I get the size of the other dimension?

author
Sheriff
Posts: 23364
127

Originally posted by Kevin Tysen:
I can get the value of a. But how do I get the value of b? How do I get the size of the other dimension?

In your case, you are creating a "square 2D" array. This means that you may use any element of the array to get the "second" dimension...

int secondLength = twoD[0].length;

Henry

Ranch Hand
Posts: 1608
If you have a two-dimensional array, you're probably using COBOL, C# or some such - but definitely not Java.

Your code shows "an arrays of arrays" - this is very distinct from a two-dimensional array. In order to get the length of the array at index 0, you'd do this: array[0].length.

(instanceof Sidekick)
Ranch Hand
Posts: 8791
Continuing from the last two posts, Java 2D arrays are not necessarily "rectangular". Each array held along the first dimension might be a different length.

Wonder if that compiles. If not, consider it pseudo-code.

How was Tony's COBOL guess? Fixed size arrays were easier to figure out in COBOL for sure. But not as flexible or efficient with memory.

Ranch Hand
Posts: 65

Originally posted by Kevin Tysen:
int a;
int b;
String[] [] twoD = new String[a][b];

Just as an advice, be careful with the above code. The above code won't compile; the compiler will complain that you are using a and b without initializing them first. I know that you simply wrote this code as an example in free-style, but, it always better to stay alert.

Regards,
Abdul Rehman.

Tony Morris
Ranch Hand
Posts: 1608

Originally posted by Abdul Rehman:

Just as an advice, be careful with the above code. The above code won't compile; the compiler will complain that you are using a and b without initializing them first. I know that you simply wrote this code as an example in free-style, but, it always better to stay alert.

Regards,
Abdul Rehman.

Just some advice, think outside the square or in this case, the local context.

The following code compiles fine:

Kevin Tysen
Ranch Hand
Posts: 255
Thank you.

Abdul Rehman
Ranch Hand
Posts: 65

Originally posted by Tony Morris:
Just some advice, think outside the square or in this case, the local context.

Okay!

 Today you are you, that is turer than true. There is no one alive who is youer than you! - Seuss. Tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS