Length of Array in Java: Yes, it is much easier than in the C/C++. The array.length property in Java does this. It is not a method, it is property of arrays of any type. Therefore, determining array length of any type in Java is easy and you might have been in a fixed state, that you can do it. Right? So let's start it.
num.length, c.length: This is just a property, not a method. This property gives the no. of elements in the array which is pointed to.
You can also find length of the string, by converting into char array using toCharArray() method and then determining the length of the array as in the above example. Instead of doing all this, you can alternatively, do it using the method length() in the String class. Here is a tutorial about it.
------------------------------------
Output
------------------------------------
Length of int array in Java is: 10
10
20
30
40
50
60
70
80
90
100
a
b
c
d
e
f
g
h
i
j
k
Length of char array in Java is: 11
class JavaArrayLength
{
public static void main(String args[])
{
// Try with int array
int[] num={10,20,30,40,50,60,70,80,90,100};
// Print length of array
System.out.println("Length of int array in Java is: "+num.length);
// Print the array (optional)
for(int i=0;i<num.length;i++)
System.out.println(num[i]);
// Try with a char array
char[] c={'a','b','c','d','e','f','g','h','i','j','k'};
// Print the array (optional)
for(int i=0;i<c.length;i++)
System.out.println(c[i]);
// Print length of array
System.out.println("Length of char array in Java is: "+c.length);
}
}
num.length, c.length: This is just a property, not a method. This property gives the no. of elements in the array which is pointed to.
You can also find length of the string, by converting into char array using toCharArray() method and then determining the length of the array as in the above example. Instead of doing all this, you can alternatively, do it using the method length() in the String class. Here is a tutorial about it.
------------------------------------
Output
------------------------------------
Length of int array in Java is: 10
10
20
30
40
50
60
70
80
90
100
a
b
c
d
e
f
g
h
i
j
k
Length of char array in Java is: 11