0

I am having trouble with a piece of my program, shown here:

String degree1 = degree.getText();

if(degree1 == ""){
   degree1 = "Undergrad";}

I want the program to get the text in a textField into a variable, and if that field is blank, to change the contents of the variable to 'Undergrad'

Whenever I test my program, it returns a blank instead of 'Undergrad'

2 Answers2

0

It is because you are using == for string comparison. Use if ("".equals(degree1)) instead.

Operator == compares references, i.e. it returns true for the same object only. If 2 objects are equal but not identical == returns false. This is why class Object contains method equals() that can (and typically should) be overridden by subclasses.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

In Java strings are compared using equals method of String class not == operator

Artur
  • 7,038
  • 2
  • 25
  • 39