Length attribute in Java: Finding the size of an array


You might already know from the previous blogs that an array is a list or collection of homogeneous elements or a collection of elements of the same data type, So in this tutorial, we will look into how to find the length of an array and few useful practice programs for you where you will need to use the length of the array.

So let us with this table of content…
How to find the length of an array in java using the length field
Searching for a value in array using length field in java
Searching for the minimum value from the array using the length field in java
Searching for the maximum value from the array using the length field in java
Let us now jump into finding the length of an array using the length field in java.

How to find the length of an array in java using the length field

The length field or attribute in java returns the size or the number of elements present in the array, irrespective of the index of the last element in the array since the indexing starts at 0.

Let me show you an example

import java.util.*;
// Example program for finding the length of an array
public class Main {
public static void main(String[] args) {
String[] strArr = { "Get", "The", "Best", "Java", "Training", "At", "FITA", "Academy" };
int arrLen = strArr.length; // array length field
System.out.println("length of the array strArr: " + arrLen);
}
}
Output for the above program will be

length of the array strArr: 8
You might get confused with the length method. The length variable works on arrays to return size such as an array.length whereas the length() method works with strings to return the size of the string. Let me clear with an example

import java.io.*;
 
// Example
class Main {
// driver method
public static void main(String args[]) {
String strArr[] = { "Get", "The", "Best", "Java", "Training", "At", "FITA", "Academy" };
System.out.println("Length of string array strArr" + strArr.length);
String str = "Get The Best Java Training At FITA Academy";
System.out.println("Length of string str" + str.length());
}
}
Output for the above program will be

Length of string array strArr: 8
Length of string str: 42

Check out this Complete Online Java Course by FITA. FITA provides a complete Java course including core java and advanced java J2EE, and SOA training, where you will be building real-time applications using Servlets, Hibernate Framework, and Spring with Aspect-Oriented Programming (AOP) architecture, Struts through JDBC bundled with, placement support, and certification at an affordable price with an active placement cell, by expert software developers with over 10 years of working experience to make you an industry required certified java developer.

Using the length field on uninitialized arrays would throw you a compiler error and if you try to find the length of a null array it will throw a java.lang.NullPointerException. To avoid this, let us modify our program to find the length of the array without errors.

import java.io.*;
 
// Example program for finding the length of an array
public class Main {
private static void arrayLength(String[] strarr) {
if (strarr == null) {
System.out.println("Length cannot be determined for the array, "+strarr);
} else {
int arrLen = strarr.length;
System.out.println("The length of the array is: " + arrLen);
}
}
 
public static void main(String[] args) {
String[] myArr_1 = { "F","I","T","A", "A","c","a","d","e","m","y" };
String[] myArr_2 = { "Java", "T","r","a","i","n","i","n","g" };
String[] myArr_3 = { "123", "1", "2", "3", "5432" };
String[] myArr_4 = { "Java","Training" };
arrayLength(null);
arrayLength(myArr_1);
arrayLength(myArr_2);
arrayLength(myArr_3);
arrayLength(myArr_4);
}
}
  Output for the above program will be

Length cannot be determined for the array, null
The length of the array is: 11
The length of the array is: 9
The length of the array is: 5
The length of the array is: 2

After learning how to find the length of an array in Java, let us now learn how to search for a value in an array using the length field in java.

Searching for a value in array using length field in java

For searching a specific value in the array, we will loop through all the elements of the array, and compare each value with the specific value, and break out of the loop if the value is found else, print that the value is not found in the array.

We will need to have the length of the array to use for loop for determining how many times we will need to loop.

Here is a program for it.

import java.io.*;
 
// searching for a specific value using length of the array, and a for loop
public class Main {
private static boolean Search(String[] strArr, String input) {
if (strArr != null) { // check if array is nul
int arrLen = strArr.length
for (int i = 0; i <= arrLen - 1; i++) 
String value = strArr[i]
if (value.equals(input)) { // comparing with each elemen
return true;
 
}
}
}
return false;
 
}
 
public static void main(String[] args) {
String StringArray[] = { "Get", "The", "Best", "Java", "Training", "At", "FITA", "Academy" };
String searchfor[] = { "Worst", "FITA", "BEST","java","Java","Get" };
for (int i = 0; i <= searchfor.length -1; i++) {
boolean x=Search(StringArray, searchfor[i])
if (x) {
System.out.print("found your string "+searchfor[i]+" in my array");
} else {
System.out.print("Cannot find your "+searchfor[i]+" string in my array");
}
System.out.println();
}
}
}
Output for the above program

Cannot find your Worst string in my array
found your string FITA in my array
Cannot find your BEST string in my array
Cannot find your java string in my array
found your string Java in my array
found your string Get in my array

After learning how to search for a value from an array in Java, let us now learn how to search for the least value in an array using the length field in java.

Searching for the minimum value from the array using the length field in java

Let us write a program for finding the minimum value of elements in the array, by comparing each value with the other, and using the length of the array and a for loop.


import java.io.*;
// example program for searching for the minimum value from the elements of an array.
public class Main {
private static int minimum(int[] myArr) {
int minVal = myArr[0];
int arrLen = myArr.length;
for (int i = 1; i <= arrLen - 1; i++) {
int element = myArr[i];
if (element < minVal) {
minVal = element;
}
}
return minVal;
}
public static void main(String[] args) {
int[] inArr = { 20, 0, 0, 80, 12, 1, 4, 45, 78, 98 };
int inArrLen = inArr.length;
System.out.print("Elements in the array: ")
System.out.println();
for (int i = 1; i <= inArrLen - 1; i++) 
System.out.print(inArr[i]+" ");
}
System.out.println();
System.out.println("The Minimum element from the above array: " + minimum(inArr));
}
Output for the above program

Elements in the array:
0 0 80 12 1 4 45 78 98
 
The minimum element from the above array: 0

After learning how to search for the least value from an array in Java, let us now learn how to search for the highest value in an array using the length field in java.

Searching for the maximum value from the array using the length field in java

Let us write a program for finding the minimum value of elements in the array, by comparing each value with the other, and using the length of the array and a for loop.

import java.io.*;
 
// Example program for searching for the minimum value from the elements of an array.
public class Main {
private static int minimum(int[] myArr) {
int maxVal = myArr[0];
int arrLen = myArr.length;
for (int i = 1; i <= arrLen - 1; i++) {
int element = myArr[i];
if (element > maxVal) {
maxVal = element;
}
}
return maxVal;
}
 
public static void main(String[] args) {
int[] inArr = { 20, 0, 0, 80, 12, 1, 4, 45, 78, 98 };
System.out.println("The min element in the myArr: " + minimum(inArr));
}
}
Output for the above program

The min element in the myArr: 98

This was all about finding the length of arrays in java, finding the minimum and maximum value or an input value by the user from the array using the length field in java, along with few practice problems. To get in-depth knowledge of core Java and advanced java, J2EE and SOA training along with its various applications and real-time projects using Servlets, Spring with Aspect-Oriented Programming (AOP) architecture, Hibernate Framework, and Struts through JDBC you can enroll in Certified Java Training in Chennai or Certified Java Training in Bangalore by FITA or a virtual class for this course, at an affordable price, bundled with real-time projects, certification, support, and career guidance assistance and an active placement cell, to make you an industry required certified java developer.

FITA’s courses training is delivered by professional experts who have worked in the software development and testing industry for a minimum of 10+ years, and have experience of working with different software frameworks and software testing designs.



Recent Post:


Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai

  93450 45466

Bangalore

 93450 45466

Coimbatore

 95978 88270

Online

93450 45466

Madurai

97900 94102

Pondicherry

93635 21112

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


Read More Read less

FITA Academy Branches

Chennai

Bangalore

Coimbatore

Other Locations

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office and Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

Read More Read less
  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!