-4

I am very new to Java and would ask you for help. I have this:

public class Person {

String name;
String gender;

public static void main(String[] args) {
    Person person = new Person();
    person.name("Max");
    person.gender = "male";
    
    Person person2 = new Person();
    person2.name = "Lea";
    person2.gender = "female";
}

What should be the correct syntax for the following method? Should I convert String to boolean?

if (String = male) {
    System.out.println("You are man!")
} else{
    System.out.println("You are woman!")
   

Thank you!

2 Answers2

0

The correct way would be

if (person.gender.equals("male")) {
    System.out.println("You are man!")
} else{
    System.out.println("You are woman!")
}

Where you can replace the String with the variable you would like to compare.

BlueFox
  • 17
  • 5
Vishal Gada
  • 201
  • 3
  • 12
0

if (String = male) is not valid syntax and won't even compile. You need to access the field, you need to compare it to a string (male is not a string, "male" is), = assigns a value but you want to compare for equality... If you are ever tempted to compare strings with == don't. String comparisons are done with the equals() method. And if you are going to compare a variable with a constant string value, call equals on the constant string value, because the variable can be null and you don't want to trigger a NullPointerException. So, to sum up: if ("male".equals(myPerson.gender)), assuming the gender field is accessible.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24