Array length in JAVA | How to Find Array Length in Java


Introduction to Array length in JAVA:

The length of the array describes the number of elements used in Java. As java is not a Size associated, so Array length helps to overcome it.

Here length applies to array in java, and Size applies to a Java   ArrayLISTcollection object.

Wish to make a career in the world of Java? Start with HKR’S  Java Training ! 

Java ‘Length’ Attribute:

The number of elements is used in the array during its declaration; we can call it as Size or length of the array. For example;

int len1 = myArray.length1;

The below program illustrate the length attributes of the Array elements in JAVA:

Import java.util.*; // built-in library

Class Main1

{

   Public static Void main1 (string [] args)

    {

      Integer [] intArray1 = {1, 3, 5, 7, 9}; // integer value

       String [] strArray1 = { “one”, “two”, “three”}; // string array elements

                   //Print each array and their corresponding length

        System.out.printIn (“integer array contents: “+ Array.to string (intArray1));

        System.out.printIn (“the length of the Integer array stored: “+intArray1.length);

       System.out.PrintIn (“string Array contents: “+ Arrays. ToString (strArray1));

       System.out.PrintIn (“The length of the String array: “+ strArray1. Length);

      }

}

 The output:

Integer Array Contents: {1, 3, 5, 7, 9}

The length of the Integer array: 5

String Array Contents: [one, two, three]

The length of the String array: 3
The above java program reads the length of the given elements and displays the length along with the contents of two different arrays (integers and strings).

Till now I have explained the simple program, now it’s time to learn how to use array in different situations.

They are:

·        Mainly to search for the specific element value in the array.

·        While searching for minimum or maximum values in the array.

Let’s discuss these two different situations in details:

Searching for a value using Length attributes:

As we discussed earlier, iterations can be done through an array using its length attributes. The loop condition in any program will iterate all the array elements one by one until it reaches (length-1) elements. (Since array count in java starts from 0).

Here we are going to use Loop condition to search if a specific value is present in the array or not. To do this, you need to traverse through the whole array until the loop reaches the last element. While performing traversing, each element in the condition will be compared with the existing value to be searched. If any value matches then loop traversing will be stopped as well as program will be terminated.

The below program explains the searching for a data value in an Array:

Import java.util.* ; //built-in library

Class Main

{

Public static void main (string [] args)

      {

         String[] strArray1 = { “UNIX” , “Python”, “ Ruby”, “ Java”, “C” }; // array of string

 

   // searching for the string using a search value function 

       

System.out.printIn (searchValue (strArray, “R”)?” value R found” : “value Java not found”);

 System.out.printIn (searchValue (strArray, “Ruby”)?” value Ruby found”: “value Ruby not found”);

}

 Private static Boolean search value (String [] search array, string lookup)

   {

    If (searchArray! = null)

          {

          int arraylength = searchArray. Length; // compute array length

             for (int i=0; I
                {

                    String value = searchArray[i];

                     If (value. Equals (lookup))

                             {

                                 Return true;

                             }

                    }

        }

 Return false;

       }

The Output:

Value R not found

Value Ruby found

Top 20 frequently asked EMC Interview Questions !

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

In the above program example, we have an array of a few programming language names. We have used the function “search value”, this function searches the particular programming language names. In this example, we have used the for loop in the search value function to iterate through the array and it will be searched for the specified names.

Once the correct name is found, then the SearchValue function returns true. If the name is not found then the SearchValue function returns false.

Related Article: Java Full stack Developer Skills !

Find the Minimum and maximum values in an Array:

In this section, here you can also traverse the array values using the attribute lengths and which enables you to find the minimum and maximum elements in an array.

As we know that the array may or may not be sorted. To perform this finding minimum and maximum the array elements, you have to do the comparison with each element once all the elements in an array get exhausted and at last, you can find the maximum or minimum elements in an array, the following programs explain the concept.

The below programming example is for minimum elements in an array.

Import java.util. *;

Class Main

 {

Public static void main (String [] args)

    {

      Int [] intArray1 = {72, 42, 21, 10, 53, 64};   //int array

          System.out.printIn (“the given array: “+ Arrays. ToString (intArray));

       Int min_val = intArray1 [0];            //assigning first element to min value

       Int length = intArray1. Length;

        For (int I = 1; I
       {

                Int value = intArray1 [i];

                 if (value
              {

               Min_val = value;

            }

   System.out.printIn ( “ the min value in the array: “ +min_Val);

 

       }

}

 

Output:

The given array: [72, 42, 21, 10, 53, 64]

The minimum value in the array is: 10

In the above programming example, we have the array elements as a reference element. Then we compare all the elements in a program one by one with the reference element which we have already mentioned in the program. The SearchValue function will be picking one by one until we reach the end of the array in a program.

The next program explains how to find the largest element in an array. The program logic is similar to the previous program, but instead of finding the element which is less than the reference element, we find the greater element than the reference.

The below program illustrates how to find the greater element;

Import java.util.* ; // built-in library

Class Main

   {

  Public static void main (String [] args)

   {

      Int [] intArray1 = {72, 42, 21, 10, 53, 64};  // inserting int array elements

      System.out.printIn (“the given array elements are: “ + Arrays.tostring (intArray1));

     int max_val = intArray1 [0]; //reference elements

     int length = intArray1.length;

     for (int i=1; I
    {

       Int value = intArray1 [i];

        If (value > max_val)

          {

                 Max_val = value;

           }

      }

      System.out.printIn (“the highest value in the array: “+max_val);

   }

 }

The output:

The given array elements are: [72, 42, 21, 10, 53, 64]

The highest value in the array: 72
In the array length, not only int elements, but we can also find the length of floating-point numbers and string elements.

The syntax is as follows:

Float size = array. Length []  // float value length

String size = array. Length [] // string values length

Acquire Liferay Fundamental certification by enrolling in the HKR Liferay Fundamentals Training program in Hyderabad!

Programming & Frameworks, array-length-in-java-description-0, Programming & Frameworks, array-length-in-java-description-1

Subscribe to our YouTube channel to get new updates..!

Programming example:

Public class test1

 {

Public static void main (string [] args)

  {

      Int [] array = new int [5]; //array name is of integer type

      Float [] array = new float [0.1]; //array name is of float type

         String [] array = new string [5]; // array name is of string type

          System. Out. PrintIn (“the size of “+ “the array is “+ array. Length);

         System. Out. PrintIn (“the size of “+ “the array is “+array. Length);

          System. Out. PrintIn ( “ the size of “+ the size of “ + “ the array is “ + array. Length);

 }

}

 

Output:

The size of the array is 4 // integer value

The size of the array is 0.09 // floating-point integer

The size of the array is [4] // string value
One important thing is that the array in java does not any methods to get the length of an element.

The following program illustrates the use of the function to get the length of an array.

Public class ArrayLengthJava

  {

  Private static void printArraylength (String [] myArray1)

  {

    If (myarray1 == null) // to find whether the array values are empty or not

    {

          System.Out.print (“the length of the array can’t be determined. “);

         }

    Else

{

    Int arraylength = myArray1. Length;

System. Out.printIn (“ the length of the array is: “ + arraylength);

  }

 }

 

Public static void main(String [] args)

  {

   String [] javaArray1 = { “ My”, “name”, “Adam”};

   String [] javaArray2 = { “K”, “A”};

String [] javaArray3 = {“1”, “2”, “3”, “4”};

String [] javaArray4 = { “Java”};

   PrintArrayLength (null);

   PrintArrayLength (JavaArray1);

   printArraylenghth (javaArray2);

PrintArraylength (javaArray3);

 PrintArraylength (javaArray4);

}

}

The output:

The length of the array can’t be determined.

The length of the Array1 is: 3

The length of the Array2 is: 2

The length of the Array3 is: 4

The length of the Array is: 1

If you want to access the length of an empty or any null object, a NullPointerException is raised.

Do you want to collaborate in the Java Spring world? Begin by learning Java Spring Training!

Java Certification Training

Weekday / Weekend Batches

Conclusion:

In this blog, I have explained the Array length in Java with a few programming illustrations. Array length in java is mainly used to find the number of elements used in the program. I hope this blog may help a few of you to learn the basic concepts of java and its examples.

Related Articles :



Source link

Leave a Reply

Subscribe to Our Newsletter

Get our latest articles delivered straight to your inbox. No spam, we promise.

Recent Reviews


What are Socket Programming in Java

Socket programming is a method where two nodes on a network can connect and communicate with one another. While another socket reaches out to the first socket to establish a connection, one socket (or node) listens on a specific port at an IP address.
While the customer reaches out for the server, the server creates the listener socket. For connection-oriented socket programming, the classes Socket and Server Socket are utilized.

Programming using Java Sockets can be either connection-oriented or connection-less. For connection-oriented socket programming, While the customer reaches out for the server, the server creates the listener socket. For connection-oriented socket programming, the classes Socket and Server Socket are utilized. and DatagramSocket classes are used, while Socket and ServerSocket are used for connection-less socket programming.

What Is Java Socket

A Java socket is one terminal of a 2-way networked communication relationship between two programs. For the TCP layer to recognize the program that data is intended to be transferred to, a socket is tied to a port number.

Java Socket

A port number and an IP address make up an endpoint. An implementation of one side of a 2-way connection between the Java program and another program on the network is made possible by the class Socket, which is part of the Java platform’s package. The class resides on top of the platform-specific implementation, shielding your Java program from the specifics of every given system. Your Java programs can interact over the web in a platform-independent manner by utilizing the class rather than depending on native code.

Client-Side Programming

When using the client side, in the programming, the client initially watches for the server to launch. The requests will be sent to the server once it is operational. The client will then watch for the server’s answer. So, this is how server and client communication functions overall. Let’s now go deeper into client-side and server-side programming.

For starting with the requests from the client-side, the user needs to process the following steps:

Establish a connection :

Creating a socket connection is the initial action. The socket connection signifies that the 2 machines are aware of each other’s IP address and TCP port on the network.

The following statement will let you construct a socket:

Socket s = new s(“127.0.0.1”, 5000)

The first input in this case denotes the server’s IP address.

The TCP Port is represented by the second parameter. (A number that indicates which server-side program should be running.)

Communication :

Streams are utilized for both data input and output when communicating via a socket connection. You must shut down the connection after opening it and sending the requests.

Closing the connection :
Once the message has been transmitted to the server, the socket connection will explicitly close.

Wish to make a career in the world of Java? Start with HKR’S Java Training !

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Server-Side Programming

In essence, the server will create its object and await a request from the client. The server will reply with the response once the client will send the request.
Two sockets are required in order to program the server-side application, and they are as follows:

When a client calls newSocket(), a ServerSocket that is waiting for the requests from the client is created. There is a straightforward socket for client communication.
Following that, you must inform the client of the outcome.

Communication

The output is sent across the socket using the getOutputStream() function.

Closing the connection

Once everything is finished, it’s crucial to shut off the connection by shutting the socket and any active input/output streams.

  • You can run the server-side program first after configuring the client and server ends. After that, you must transmit the request and start client-side software. The server will reply as the client sends the request. The image below shows the same.

Closing the connection

  • The client will establish a connection and enter the request as a string.

Closing the connection 2

  • The server will reply to the request sent by the client.

Closing the connection 3

You must run a Java socket program in the given manner. These programs can also be run via a command window or terminal. However, as Eclipse is very feature-rich, you can easily run both apps on a console.

Top 30 frequently asked JAVA Interview Questions !

HKR Trainings Logo

Subscribe to our YouTube channel to get new updates..!

Testing The Applications

The testing of applications is done using the IntelliJ application or any other IDE. 

  • Put the two programs together.
  • Start the client application after starting the server software.
  • Write a message in the client window, and the server window will simultaneously receive and display them.
  • Type BYE to leave.

This can be done using a command prompt also:

  • Create a new folder called project (this is the name of your package).
  • Place the project folder’s Server.java and Client.java files.
  • Go to the root path on the command prompt after opening it.
  • Run java project.Server first, then javac projectServer.java.
  • Use the same process to run the client and server programs.
  • Messages can then be typed in the window of the client.

The application can fail when a port has already been in use. Modify port no to a special number to resolve this problem.

Acquire Jenkins certification by enrolling in the HKR Jenkins Training program in Hyderabad!

Java Certification Training

Weekday / Weekend Batches

Conclusion

In this article, we have talked about socket and socket programming. Socket programming is a method where two nodes on a network can connect and communicate with one another. While another socket reaches out to the first socket to establish a connection, one socket (or node) listens on a specific port at an IP address. We have also discussed client-side and server-side along with testing the applications.

Related Article:

Drools Interview Questions



Source link