0

I have entered the string abc def and the equals() has returned true while comparing the entered string with the given string abc.

import java.util.Scanner;

class StringManipulation
{
    public static void main(String args[])
    {
        Scanner s = new Scanner(System.in);
        System.out.println("enter username");
        String a = s.next();                   // abc def
        System.out.println(a.equals("abc"));   // return true at execution time
    }
}
Pshemo
  • 113,402
  • 22
  • 170
  • 242
Sai Kiran
  • 66
  • 5
  • 1
    `s.next()` reads a single token (i.e. until a white space or new line is encountered). Therefore `a` contains "abc". Use `s.nextLine()` if you wish to read the entire line. – Eran Jan 15 '18 at 19:48
  • That's expected, given what Scanner.next() does. Read its documentation. It does not do the same thing as nextLine(). – JB Nizet Jan 15 '18 at 19:48
  • `next()` takes only one token. Tokens are separated by delimiters which for scanner is set as *one or more whitespace* so here next token is only `abc`. If you want to read entire line use `nextLine()` – Pshemo Jan 15 '18 at 19:49
  • Please take the time to format your code correctly and remove unnecessary whitespace for your next post. – takendarkk Jan 15 '18 at 19:51
  • yea sure :) @csmckelvey – Sai Kiran Jan 15 '18 at 19:52

0 Answers0