Program to display longest and shortest words from an array (Java)


Welcome friends to Blogger Codemaster. This is our another post. So in this post, I would like to give you a Java program to display longest and shortest words from an array.

So let's get started with our today's topic - PROGRAM TO DISPLAY LONGEST AND SHORTEST STRINGS.

 

QUESTION

Write a Java Program to input 10 strings into an array and display the longest and shortest strings along with their lengths.


FULL CODE

import java.util.*;

public class LongestShortest

{

    public static void main(String args[])

    {

        Scanner in=new Scanner(System.in);

        

        // Declaration of the array

        String arr[] = new String[10];

        

        // Initialization of the elements of the array

        System.out.println("Enter 10 strings: ");

        for(int i=0;i<10;i++)

        arr[i] = in.nextLine();

        

        // Declaration of longest and shortest variables.

        String longest="", shortest=arr[0];

        

        //

        for(int i=0;i<10;i++)

        {

           if(arr[i].length()>longest.length())

           longest=arr[i];

           if(arr[i].length()<shortest.length())

           shortest=arr[i];

        }

        

        // Prints the words.

        System.out.println("Longest Word: "+longest+" (Length: "+longest.length()+")");

        System.out.println("Shortest Word: "+shortest+" (Length: "+shortest.length()+")");

    }

}






 

VARIABLE DESCRIPTION

Variable Data Type Description
arr[] String Array of Strings.
longest String Longest Word Stored.
shortest String Shortest Word Stored.
i int Loop Variable.


 

OUTPUT



Here, we come to the end of our another post. We will discuss various other interesting topics in our upcoming posts. 

So uptil then I bid you a goodbye😇. 

Please follow our 👉blog and comment💬 below for any queries.



Post a Comment

Previous Post Next Post