+ 1

Need some help with Java code

import java.util.Scanner; public class pomodoro_timer { public static void main(String args[]){ Scanner input = new Scanner(System.in); try { System.out.print("\nPress \'Enter\' to start or OR Type \'quit\' to quit the program: "); String start = input.nextLine(); if(start==""){ System.out.print("yes"); } else if(start=="quit"){ System.out.print("no"); } else{ System.out.print("\nINVALID INPUT. TRY AGAIN"); main(args); } } finally { input.close(); } } } It always executes the "else" statement. What's wrong with it? Thanks in advance.

7th Jul 2017, 5:23 AM
Alexander Lavrenko
Alexander Lavrenko - avatar
3 Answers
+ 2
The == operator in Java checks for reference equality: it returns true if the pointers are the same. It does not check for contents equality. Identical strings found at compile-time are collapsed into a single String instance, so it works with String literals, but not with strings generated at runtime. For instance, "Foo" == "Foo" might work, but "Foo" == new String("Foo") won't, because new String("Foo") creates a new String instance, and breaks any possible pointer equality. More importantly, most Strings you deal with in a real-world program are runtime-generated. User input in text boxes is runtime-generated. Messages received through a socket are runtime-generated. Stuff read from a file is runtime-generated. So it's very important that you use the equals method, and not the == operator, if you want to check for contents equality.
7th Jul 2017, 7:06 AM
Vahagn Lazyan
Vahagn Lazyan - avatar
+ 2
@Vahagn Lazyan , thank you!
7th Jul 2017, 1:09 PM
Alexander Lavrenko
Alexander Lavrenko - avatar
0
This is why Python is much more attractive than Java. (Because I've never had silly problems like this with Python).
7th Jul 2017, 5:33 AM
Alexander Lavrenko
Alexander Lavrenko - avatar