Find Longest Word from the string using Java


 

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.

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){
if(st1.length()>st2.length()){
return st1;
}
else{
return st2;
}
}
LongestWord(){
String word = "";
for(int i=0;i<stringArray.length;i++){
if(i==0){
word = stringArray[0];
}
word = compare(word, stringArray[i]);
}
System.out.println("Longest word = " + word);
}
public static void main(String []args){
new LongestWord();
}
}

Output:

Longest word=intelligent

Ads