Get Char Array's Length in Java

Mohammad Irfan Dec 25, 2020
  1. Get the Length of a Char Array in Java Using the length Property
  2. Get the Length of a Char Array Using the Custom Code in Java
Get Char Array's Length in Java

This article introduces how to get the length of a char array in Java.

In Java, an array that contains char values is known as a char array. In this article, we will use the built-in property length and custom code to get the array’s length. Let’s see some examples.

Get the Length of a Char Array in Java Using the length Property

In this example, we create a char array ch that contains 4 char values. We know the length of the char array by seeing the source code, but in programming, we can do it by using the length property that returns the length of the array. See the example below.

public class SimpleTesting{
    public static void main(String[] args) {
        try{
            char[] ch = {'c','b','d','e','f','g'};
            int length = ch.length;
            System.out.println("Array Length = "+length);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Array Length = 4

Get the Length of a Char Array Using the Custom Code in Java

In this example, we create a char array ch containing 4 char values and our own method length() that returns the passed array’s length. We call that method and stored the result into a variable. See the example below.

public class SimpleTesting{
    public static void main(String[] args) {
        try{
            char[] ch = {'c','b','d','e','f','g'};
            int length = length(ch);
            System.out.println("Array Length = "+length);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    static int length(final char[] b) {
        int n = 0,t=0;
        while (true) {
            try {
                t = b[n++];
            } catch (ArrayIndexOutOfBoundsException ex) {
                n--;
                break;
            }
        }
        return n;
    }
}

Output:

Array Length = 4

Related Article - Java Array