Dremendo Tag Line

Input a sentence and print the longest word in Java

String - Question 8

In this question, we will see how to to input a sentence and print the longest word in Java programming. To know more about string click on the string lesson.

Q8) Write a program in Java to input a sentence and print the longest word.

Program

import java.util.Scanner;

public class Q8
{
    public static void main(String args[])
    {
        String s,w="",lw="";
        int i;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a sentence");
        s=sc.nextLine();

        for(i=0; i<s.length(); i++)
        {
            if(s.charAt(i)!=' ')
            {
                //concatenates the character until we find a space
                w=w+s.charAt(i);
            }
            else
            {
                // check if word length is greater than longest word (lw)
                if(w.length()>lw.length())
                {
                    lw=w;
                }
                w="";
            }
        }
        System.out.println("Longest word = "+lw);
    }
}

Output

Enter a sentence
I am learning to code in Java
Longest word = learning
video-poster