File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Number of Columns Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Number of Columns" Watch "Number of Columns" New topic

Number of Columns

Harish Venkatachalam

Joined: Jul 15, 2003
Posts: 3
What is the function or method which gives me the no of columns(elements) an array contains? For e.g if I have an array called
TestArray[] testArray
I think testArray.length or testArray.length will give me the no of rows the array contains. But I want the nr of columns, is there a method of function I can use? Thanks.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

A Java array is always a linear, one-dimensional thing. The .length member tells you how long it is.
Now, you can simulate multi-dimensional arrays by having an array that contains other arrays,and the Java language by using special notation for arrays of arrays -- i.e., an "int[][]" is an array of arrays of integers. The interesting thing about this arrangement is that every one of the nested arrays can have a different length -- i.e.,

If you want to know the length of one particular "column" of "matrix", you can ask for it specificially: matrix[0].length is 3, matrix[1].length is 2, etc. But it doesn't make any sense to ask matrix itself for the size of its second dimension overall, you see?
If you know that you created an array "squareMatrix" such that every sub-array is the same length, then squareMatrix[0].length will give you that length; there's no other way to do this.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Number of Columns
It's not a secret anymore!