title: Write a program to find the second longest word without using array
body: <p>I need a java program to find the second-longest word in a sentence (without using an array).</p>
  <p>This is the code I have so far:</p>
  <pre><code>import java.io.*;
  class Second_longest_Trial {
    public static void main(String args[]) throws IOException {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      System.out.println(&quot;Enter the sentence&quot;);
      String s = in .readLine();
      s = s.trim() + &quot; &quot;;
      String longest = s.substring(0, s.indexOf(' '));
      String sec = longest;
      int l = s.length();
      String temp = &quot; &quot;, str = &quot; &quot;;
  
      for (int i = s.indexOf(' ') + 1; i &lt; l; i++) {
        char ch = s.charAt(i);
  
        if (ch != ' ')
          temp = temp + ch;
        else {
          if (temp.length() &gt; longest.length()) {
            sec = longest;
            longest = temp;
          } else if (temp.length() &gt; sec.length()) {
            sec = temp;
          }
          temp = &quot; &quot;;
        }
      }
  
      System.out.println(&quot;Longest word is &quot; + longest);
      System.out.println(&quot;Second Longest word is &quot; + sec);
    }
  }
  </code></pre>
  <p>When I am giving the input-</p>
  <blockquote>
  <p>Sayan goes home.</p>
  </blockquote>
  <p>This outputs-</p>
  <blockquote>
  <p>Longest word is Sayan
  Second Longest word is Sayan</p>
  </blockquote>
  <p>I should have got the output as follows-</p>
  <blockquote>
  <p>Longest word is Sayan
  Second Longest word is goes</p>
  </blockquote>