java program to determine the length or size of an array 以下示例将帮助我们了解如何找到数组的大小。
example 1 的中文翻译为:示例 1the following example illustrates the use of length property with an array of type integer.
import java.util.*;public class example1 { public static void main(string[] args) { int[] aray = new int[5]; // declaring array of size 5 // initializing the array aray[0] = 11; aray[1] = 21; aray[2] = 13; aray[3] = 23; aray[4] = 30; // printing the elements of array system.out.println(elements of the given array: ); for(int elm : aray) { system.out.print(elm + ); } system.out.println(); // printing the length of array system.out.println(length of the given array: + aray.length); }}
outputelements of the given array: 11 21 13 23 30 length of the given array: 5
在上面的代码中,我们声明了一个大小为5的数组,这意味着它可以存储最多5个元素。然后,使用for-each循环,我们检索了所有的元素,并且借助length属性确定了给定数组的大小。
example 2 的中文翻译为:示例2in this example, we will declare and initialize a string array. then, using a for-each loop, we will print its element. in the end, with the help length property, we determine the size of given array.
import java.util.*;public class example2 { public static void main(string[] args) { // declaration and initialization of the array string[] aray = { tutorix, tutorials, point, simply, easy, learning }; // printing the elements of array system.out.println(elements of the given array: ); for(string elm : aray) { system.out.print(elm + ); } system.out.println(); // printing the length of array system.out.println(length of the given array: + aray.length); }}
outputelements of the given array: tutorix tutorials point simply easy learning length of the given array: 6
example 3this is another example where we will find the size of an array without using any in-built property or method of java.
方法声明并初始化两个数组。一个是字符串数组,另一个是整数数组
然后,定义两个整数类型的计数变量来存储两个数组的元素数量。
now, use the for-each loop to iterate and increment the counter variable by one with each iteration.
最后,打印结果并退出。
import java.util.*;public class example3 { public static void main(string[] args) { // declaration and initialization of the arrays string[] aray1 = { tutorix, tutorials, point, simply, easy, learning }; int[] aray2 = {58, 66, 74, 55, 62}; // initial counter variable to store the count of elements int countr1 = 0; int countr2 = 0; // printing the length of both arrays for(string elm : aray1) { countr1++; } for(int elm : aray2) { countr2++; } system.out.println(length of the string array: + countr1); system.out.println(length of the integer array: + countr2); }}
outputlength of the string array: 6length of the integer array: 5
结论在本文中,我们通过示例程序学习了使用length属性来确定给定数组的大小。此外,我们还讨论了一种在不使用任何内置方法和属性的情况下找到数组长度的方法。
以上就是如何确定java中数组的长度或大小?的详细内容。
