-1

I just started learning JAVA.
I am writing a very simple program to print something on based of command line argument.
but it is not working as expected.

Here is my program and output.

enter image description here

It should print "e" but it is printing "n".

please tell me where I am doing wrong.

Anurag Rana
  • 1,429
  • 2
  • 24
  • 48
  • Recommend using an IDE. Many would have flagged this for you. – vandale Oct 16 '13 at 00:23
  • Thanks vandale. But I think we should start with notepad. IDE will do all the correction for me and I will not be able to learn small small things. – Anurag Rana Oct 16 '13 at 01:34

2 Answers2

2

Strings must be compared with the String.equals(), because the == operator will only check whether the references point to the same object.

if ("e".equals(e)) {
  // they are equivalent strings
}
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
  • 1
    " the == operator will only check whether the references to the objects are equal" - nope! the `==` operator checks that the references point to the **same object**! – Nir Alfasi Oct 16 '13 at 00:13
0

Not to be picky about syntax of the answer of hexacyanide but as comparing a string to be equal to "e" the more logic and cleaner in my opinion is:

if (e.equals("e")) { /* e == "e" */ }

Because it says: If the string e that we found is what we are looking for, in this case "e", then do something.

Another reason is that "e" is just an array of characters at that point and e is a String already. Now i'm not 100% sure about this but i think that the equals method has some more efficient overriden method somewhere for character arrays. In the case you put "e" in front of .equals, "e" is first converted to a String and then evaluated, that is if the compiler doesn't optimize that.

fonZ
  • 2,428
  • 4
  • 21
  • 40