Hey everyone,

my if-statements are working as expected. Actually, they are not working at all. The syntax is right but they are never run. The program terminates before it runs them.

public static void main (String args[]){
		Scanner input = new Scanner(System.in);
		
		Display fName = new Display(); // creating a new obj called fName
		System.out.println("Enter your first name: ");
		String name = input.nextLine();
		
		fName.greeting(name);
		
		
		Display howToDo = new Display();
		System.out.println("How are you," + name + " ?");
		
		
		String name1 = input.nextLine();

		
                if (name1 == "good"){
			System.out.println("We know that you're good. Keep it up!");
		}else if (name1 == "fine") {
			System.out.println("We know that you're fine.");
		}else if(name1 == "ok"){
			System.out.println("We know that you're ok. Improve it lol!");
		} 

 when I use defualt at the end of this blocks, the default condition works.

I tried using switch(name1) --> was giving me errors because of data type.

Thanks,

if (name1 == "good")

replace by this

if(name1.equals("good"))
{
}

likewise all if conditions.

Awesome. Cheers.

The thing is, when you do

if(string1 == string2){
// do something
}

you compare the places of the two strings in the memory, instead of the actual word.
If you use primitive data types such as int, byte, etc..you will not encounter this problem, but for all else, use object1.equals(object2) to compare their actual values.

if two compared string are initialized at the time of declaration and than compared it will work finely

String a="xyz";
String b="xyz";
if(a==b)
{
//executed
}

in this case String b will not take separate memory instead it will refer to same memory location referring by String a. if you will initialize any one of them at run time than it will never effect other one instead it will take separate space.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.