1

Possible Duplicate:
How do I compare strings in Java?

I'm new to programming, and I'm using java. Here's a program I wrote:

class HelloApp {

    static String hi;

    public static void main(String[] args) {
        int length = args.length;
        if (length > 0) {
            hi = args[0];
            sayHi();
        }
    }

    static void sayHi() {
        if (hi == "hello") {
            System.out.println("Hello!");
        }
    }
}

My question is: Why doesn't inputting "java HelloApp hello" make "Hello!" appear on the next line?

Community
  • 1
  • 1
Andrew0085
  • 85
  • 1
  • 4
  • 2
    Java requires .equals() method for String class equality test. == is used to compare if two classes refer to the same data. – Scooter Oct 14 '12 at 07:22
  • why was this migrated to programmers? there are a billion "comparing strings in java" threads on SO ..? – Thousand Oct 14 '12 at 10:49

5 Answers5

10
if (hi == "hello") {

should be:

if (hi.equals("hello")) {

== checks if the two references are pointing to same object in the heap, while equals() checks if the two String references are pointing to objects that having the same String value.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Using FindBugs, [you can automatically detect errors like these](http://findbugs.sourceforge.net/bugDescriptions.html#ES_COMPARING_STRINGS_WITH_EQ) – Janus Troelsen Oct 14 '12 at 10:56
2

you are comparing strings in a wrong way...

How do I compare strings in Java?

static void sayHi() {
    if (hi.equals("hello")) {
        System.out.println("Hello!");
    }
}

this should solve your problem..

Community
  • 1
  • 1
maxstreifeneder
  • 625
  • 1
  • 8
  • 19
2

== tests reference equality, not string equality. You want to use .equals instead:

if (hi.equals("hello")) {
    ...
}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
2

You are comparing Strings incorrectly. The proper way to check for string equality is via str.equals(anotherStr), or str.equalsIgnoreCase(anotherStr). The == operator checks if the strings point to the same memory location, not the contents.

neilvillareal
  • 3,935
  • 1
  • 26
  • 27
1

as neilvillareal said you can make use of str.equals(anotherStr), or str.equalsIgnoreCase(anotherStr) methods, Please refer following link for understanding difference between '==' & 'equals/equalsIgnoreCase'method : http://www.java-samples.com/showtutorial.php?tutorialid=221