Share on Google+Share on Google+

Find Longest Word from the string using Java

In this section, you will learn how to get the longest word from the string using Java Programming.

Find Longest Word from the string using Java

Here we are going to find the longest word from the string. For this, we have specified the string which is then splitted into string array using  split() method. Then we have created a method compare(String st1,String st2)  that will compare the two strings and allow the longest word to display.

Here is the code:

import java.util.*;

class LongestWord
String str = "Ram is intelligent boy";
String stringArray[] = str.split("\\s");
public String compare(String st1, String st2){
return st1;
return st2;
String word = "";
for(int i=0;i<stringArray.length;i++){
word = stringArray[0];
word = compare(word, stringArray[i]);
System.out.println("Longest word = " + word);
public static void main(String []args){
new LongestWord();


Longest word=intelligent


Posted on: October 24, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.