args.length() in Java

Before we start off, it’s very important for us to understand what are command-line arguments. So in this tutorial, we are going to understand what are Command Line Arguments first. Then we understand the difference between the two most popular command-line arguments and finally implement one of them.

What are Command-Line Arguments?

Command-Line is a screen, a user-interface which allows the user to navigate through the interface using commands. Two relevant examples of Command-Lines are the Command prompt in Windows and Terminal in Ubuntu. Command-line arguments are hence, the arguments which are passed through the command lines at the time of running the compiled/interpreted file.

In Java, while declaring the main( ) method, we generally pass an array of string in it, which is String args[ ]. Here it creates an array of Strings named args, each index of this array holds the strings passed through the command line. length and length( ) are two very much popular operations used here.

The Big Difference

args.length: This is a final variable. It calculates the size of the array. This is not applicable to String objects, rather only applicable to the array.
args.length( ): This is a method which calculates the length of the Strings inside the array. This is not applicable to the array, rather applicable only to String Objects.

Implementation of args.length( )

import java.util.*;
public class Test {
  public static void main(String[] args){
    for(int i = 0; i < args.length; i++){
      System.out.println(args[i].length());
    }
  }
}

For input “Welcome to Codespeedy”

OUTPUT:
7
2
10

If we look closely into the code, we see that there are length used in lin #4, and length( ) used in line#5. In line#4, the length variable is used to check, here traverse the entire args[ ] array. In line#5 args.length( ) method is used to calculate the length of the string in each index of the array. In another way, the length variable operates on the array, while length( ) method operates on the String objects inside the array.

The following are the steps to run this code:

  1. Open Command-Prompt in Windows or Terminal in Ubuntu.
  2. Assuming the file name to be same as the class name, type in :
    javac Test.java

    java Test Welcome to Codespeedy

So, here’s the tutorial on args.length( ) in Java.

Also, see: How to count the number of words in a string in Java

Leave a Reply

Your email address will not be published. Required fields are marked *