How to determine the length or size of an array in Java?
In Java, one of the convenient ways to determine the length or size of an array is by using its length property. It counts the number of stored elements in an array and returns the count . Finding the length of an array is one of the common yet crucial operation as it is used to find the number of elements of an array, append new elements into it and retrieve stored items. This article aims to explain the various ways to get the length or size of an array.
Java Program to determine the length or size of an Array
The following example will help us understand how to find the size of an array.
The Chinese translation ofExample 1
is:Example 1
The 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); } }
Output
Elements of the given array: 11 21 13 23 30 Length of the given array: 5
In the above code, we have declared an array of size 5, which means it can store up to 5 elements. Then, using a for-each loop, we retrieved all the elements and determined the size of the given array with the help of the length property.
The Chinese translation ofExample 2
is:Example 2
In 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); } }
Output
Elements of the given array: Tutorix Tutorials Point Simply Easy Learning Length of the given array: 6
Example 3
This is another example where we will find the size of an array without using any in-built property or method of Java.
method
Declare and initialize two arrays. One is a string array and the other is an integer array
Then, define two count variables of integer type to store the number of elements of the two arrays.
Now, use the for-each loop to iterate and increment the counter variable by one with each iteration.
Finally, print the results and exit.
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); } }
Output
Length of the String array: 6 Length of the integer array: 5
in conclusion
In this article, we learned to use the length property to determine the size of a given array through a sample program. Additionally, we also discussed a way to find the length of an array without using any built-in methods and properties.
The above is the detailed content of How to determine the length or size of an array in Java?. For more information, please follow other related articles on the PHP Chinese website!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
