Newbie question, but I have this code:
import java.util.*;
import java.io.*;
public class Welcome1
{
// main method begins execution of Java application
public static void main( String[] args )
{
String confirm = "y";
while(confirm=="y")
{
System.out.println( "Welcome to Java Programming!" );
System.out.println( "Print Again? (y/n)" );
Scanner input = new Scanner(System.in);
confirm = input.nextLine();
}
}
}
I just need to simply print the welcome message again when user input “y” when asked.
But it’s not working. Any ideas?
In Java, the primitive types (int, long, boolean, etc.) are compared for equality using
==, whereas the Object types (String, etc.) are compared for equality using theequals()method. If you compare two Objects types using==, you’re checking for identity, not equality – that is, you’d be verifying if the two objects share exactly the same reference in memory (and hence are the same object); and in general, what you need is just verifying if their values are the same, and for that you useequals().As a good programming practice, it’s better to compare Strings like this, flipping the order of the strings:
In this way, you can be sure that the comparison will work, even if
confirmwas null, avoiding a potentialNullPointerException.