So i wanted to create a simple if statement in which if the name imputed is “jose”, the true would print (hello jose) and if it was false, it would say “hello stranger” pretty straightforward, but when i try to do that, it runs just fine with no errors, but no matter what i type in as the name… it prints the false statement
package test;
import java.util.Scanner;
public class testingif {
public static void main(String\[\] args) {
Scanner scan = new Scanner(System.in);
String name;
System.out.println("Enter name");
name = scan.nextLine();
System.out.println(name);
if (name == "jose") {
System.out.println("Hello Jose!! =D");
}else{
System.out.println("Why hello there stanger =3");
You’re right and this is the expected output. This is because you’re using the wrong equality.
In Java, the == is testing for reference equality. Are they the same object?
An example of this would be
String name = scan.nextLine();
String newName = name
if (name == newName) {
System.out.println("This will work!")
}
Now, there’s a super duper secret thing called .equals() which is testing for value equality. That’s the key ingredient for why your problem isn’t working.
Reading your current if statement it’s asking is the name object equal to the “jose” object. Which we know is not the case. If we said
if (name.equals("jose")) {
. . .
}
We will get the output that you are expecting. This if statement is asking us: does name have the same value as “jose”.
Hopefully this will make more sense to you. I tried explaining it to the best of my ability.