Java Programming Exercies

Java Exercises: Find the longest word in a text file

Java Input-Output: Exercise-18 with Solution

Write a Java program to find the longest word in a text file.

Sample Solution:

Java Code:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Exercise18 {
     public static void main(String [ ] args) throws FileNotFoundException {
              new Exercise18().findLongestWords();

     public String findLongestWords() throws FileNotFoundException {

       String longest_word = "";
       String current;
       Scanner sc = new Scanner(new File("/home/students/test.txt"));

       while (sc.hasNext()) {
          current = sc.next();
           if (current.length() > longest_word.length()) {
             longest_word = current;

            return longest_word;

Sample Output:



Flowchart: Find the longest word in a text file

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to read first 3 lines from a file.
Next: Java Collection Exercises

What is the difficulty level of this exercise?

New Content: Composer: Dependency manager for PHP, R Programming