-2

Possible Duplicate:
How do I compare strings in Java?

I don't really understand why the program below does not show anything when I write "y" and press enter.

import java.util.Scanner;

public class desmond {
    public static void main(String[] args){
        String test;
        System.out.println("welcome in our quiz, for continue write y and press enter");
        Scanner scan = new Scanner(System.in);
        test = scan.nextLine();
        if (test == "y") {
            System.out.println("1. question for you");
        }
    }
}
Community
  • 1
  • 1

3 Answers3

3

use equals() to compare String

like

test.equals("y")

even better

"y".equals(test)
Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
2

You (generally) need to compare strings with equals in Java:

if ("y".equals(test))
assylias
  • 321,522
  • 82
  • 660
  • 783
1

Can you compare String using == ? Yes. Works 100% of the time? No.

One of the first things I learned when I started programming in java was NEVER use == to compare Strings, but Why? Let's go to a technical explanation.

String is an object, the method equals (Object) will return true if both strings have the same object. The == operator will only return true if both references String references point to the same object.

When we create a String is literally created a pool of strings, when we create another String literal with the same value if the JVM demand already exists a String with the same value in the String pool, if any, does your variable to point to the same memory address.

For this reason, when you test the equality of the variables "a" and "b" using "==", could be returns true.

Example:

String a = "abc" / / string pool
String b = "abc"; / * already exists a string with the same content in the pool,
                                  go to the same reference in memory * /
String c = "dda" / / go to a new reference of memory as there is in pool

If you create strings so you are creating a new object in memory and test the equality of the variables a and b with "==", it returns false, it does not point to the same place in memory.

String d = new String ("abc") / / Create a new object in memory

String a = "abc";
String b = "abc";
String c = "dda";
String d = new String ("abc");


a == b = true
a == c = false
a == d = false
a.equals (d) = true
matheuslf
  • 309
  • 1
  • 9