imulsion
imulsion

Reputation: 9040

Finding the size of a char array in Java

I'm making a calculator and I have converted a String to a char array using

char[] b = inputString.toCharArray();

(inputString is my String variable)

Because the String is an input I don't know how large the array will be. Is there an inbuilt method that allows you to find the number of elements in the array? Thanks in advance.

Upvotes: 10

Views: 127657

Answers (6)

Erfan Ahmed
Erfan Ahmed

Reputation: 1613

b.length; is very much handy and very much useful to find the length of char[] array:)

Upvotes: 0

user2850208
user2850208

Reputation: 1

Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayRefVar.length. For example, myList.length returns 10.

Upvotes: 0

obataku
obataku

Reputation: 29636

Don't listen to any of these guys, here, try this!

static int length(final char[] b) {
  int n = 0;
  while (true) {
    try {
      int t = b[n++];
    } catch (ArrayIndexOutOfBoundsException ex) {
      break;
    }
  }
  return n;
}

(Just kidding... try b.length.)

Upvotes: 17

alexgerst
alexgerst

Reputation: 155

The above answers work. Also, if for some reason you need to know the array size before you actually create the array (for pre-processing or some such activity), you can get the string's length (which will be equal to that of the array).

inputString.length()

Upvotes: 0

kosa
kosa

Reputation: 66637

b.length is the way to find length of array

length property determines size of the array.

Upvotes: 2

SomeKittens
SomeKittens

Reputation: 39512

You can use b.length to find out how many characters there are.

This is only the number of characters, not indexing, so if you iterate over it with a for loop, remember to write it like this:

for(int i=0;i < b.length; i++)

Note the < (not a <=). It's also important to note that since the array isn't a class, .length isn't a function, so you shouldn't have parenthesis afterward.

Upvotes: 25

Related Questions