1

I'm trying to do a comparison in Java with 2 strings containing a extended ASCII character.

boolean result = "éasdfasdf".substring(0,1).equals("é");

Can somebody explain why this results false? I think it has something to do with character encoding, but I can't figure out what exactly the problem is here...

Update: ideone.com does successfully run these 2 lines, so the problem is locally in my box. I think I found some more proof of that:

System.out.println("éb".charAt(1) == 'b');

Does also fails... Can it be the problem of 2 different character encodings?

1 Answers1

2

Use

boolean result = "éasdfasdf".substring(0,1).equals("é")

And it will give expected result!

The reason is simple - using '==' you compare objects by reference, not by value. So equals() solves this problem

sberezin
  • 3,266
  • 23
  • 28
  • 1
    @VincentTeuben - Nope. It doesnt. It returns `true` – TheLostMind Nov 20 '14 at 14:10
  • Yes, sure, equals() doesn't fail:) – sberezin Nov 20 '14 at 14:12
  • Before you gave a answer, please try it, because there is something fishy going on here. System.out.println("éasdfasdf".substring(0,1).equals("é")); Fails on my Windows box – Vincent Teuben Nov 20 '14 at 14:39
  • Don't doubt - I've tried it. It goes ok on my system and, for example, here: http://ideone.com/ – sberezin Nov 20 '14 at 14:49
  • Indeed, ideone gives me true, I copied the exact sources from ideoone and tried it in IntelliJ14, JDK 1.7.0_51, Windows and that gives me a false. – Vincent Teuben Nov 20 '14 at 14:55
  • You say that it behaves different on different systems (doesn't work on Windows). It has never occurred to me. Suspect it happens due to unicode/locale settings. It deserves new question. If you get answer please let me know – sberezin Nov 20 '14 at 21:06