This question has already been answered:

I'm still completely green in java, when you enter male, Ms (Miss / Missis) + nickname is still displayed, although Mr. should be displayed.

package com.company.Start; import com.company.objects.Visitor; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner n = new Scanner(System.in); System.out.println("What's your name?"); String name = n.nextLine(); Scanner s = new Scanner(System.in); System.out.println("What's your sex(male/female)? "); String sex = s.next(); Random rnd = new Random(System.currentTimeMillis()); int cash = rnd.nextInt(3000); Visitor join = new Visitor(name, sex); String mrs; if (sex == "male") mrs = "Mr "; else mrs = "Ms "; System.out.println("Hello, Dear " + mrs + name); } 

Marked as a duplicate by the participants Sergey Gornostaev , Regent , zRrr , Community Spirit 14 Feb '18 at 17:23 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    Strings must be compared using the equals method. - Regent

1 answer 1

To compare strings, use the equals method. If you use == , then the expression returns true only when stringVar == stringVar . In short, the comparison of the lines works differently.

And yet, it would be better to write:

 if (sex.equals("male")) mrs = "Mr "; else if (sex.equals("female")) mrs = "Ms "; else mrs = "UnknownSex"