1

Possible Duplicate:
How do I compare strings in Java?

I am trying to make it so that when I type hope, b will save hope and then it will recognize c == b, and you get the picture. What do I do? I am new to Java and I apologize if this is a no brainer.

package encryption;
import java.util.Scanner;

public class Encrypt


{


public static void main (String[] args)

{

Scanner scan = new Scanner(System.in);

String test1 = new String("Enter now: ");
String d = new String("Success!");
String e = new String("Failure");
String b = new String();
String c = "hope"


System.out.print("Enter text: ");
b = scan.next();

if (b == c)
System.out.println("\"" + d + "\"");
else
    System.out.println("\"" + e + "\"");

}}
Community
  • 1
  • 1
Michael Ward
  • 23
  • 1
  • 5

7 Answers7

8

Use if b.equals(c) because b==c compares references in java. It tells that if both the objects are referring to same memory locations or not.

So, if you need to check whether their values are equal always use equals method.

RanRag
  • 48,359
  • 38
  • 114
  • 167
2
if (b == c)

Use equals instead to compare strings:

if (b.equals(c))

== compares the references, not the values so you're getting false every time. Equals compares the values.

This link provides a good explanation between ==, equals, compareTo, ...

J. Maes
  • 6,862
  • 5
  • 27
  • 33
1

To test the equivalence of Strings in Java you want to use the equals method:

if(c.equals(b)) {
    ...
}

The == operator tests to see if both variables point to the same place in memory. You have two Strings that have the same "value" (read:text), but are stored in two different places in memory.

RHSeeger
  • 16,034
  • 7
  • 51
  • 41
1

c == b tests reference equality -- i.e. do the references point to the same object. You want equals as in b.equals(c)

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0

Two things:

  1. Don't compare Strings using a == b, use a.equals(b). The == operator asks if two Strings are the same physical chunk of memory; the equals() method asks if they contain the same characters. You want that second one!
  2. You never need to -- nor should you -- use new String() in Java; just a double-quoted string like "hope" is a String object. Using new String() just creates unneeded objects and bogs things down.
Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
0

b==c checks whether b and c reference the same string, while b.equals(c) check whether their values are equal, which is what you're trying to do.

dorsh
  • 23,750
  • 2
  • 27
  • 29
0

Your problem is not proper reading documentation. Use String.equals() instead.

Tony Frolov
  • 213
  • 1
  • 9