0

I was beginning to think I was getting the hang of the basics in Java, but then I found myself back in the dark. The code here is quite meaningless, but my question is; if I type in "yo" to the question "What is your name", in my mind, the program should print "yo man!", but instead it prints "lala".

Why? I don't understand.. :-/

import java.util.Scanner;

public class test {

public static void main(String[] args) {


    System.out.println("What is your name?");
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();

    System.out.println("Hello, "+ str);

    if (str == "yo"){
        System.out.println("yo man!");

    }
    else System.out.println("lala");
    sc.close();

}

}

  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Feb 25 '17 at 22:57
  • So not `if (str == "yo"){` but rather `if (str.equals("yo")) {` or `if (str.equalsIgnoreCase("yo")) {` – Hovercraft Full Of Eels Feb 25 '17 at 22:57
  • Thank you for answering. That really helped! – Newless_Cluebie Feb 25 '17 at 23:02

0 Answers0