-1

I wrote a Java program that should support English and German language. If a parameter is set and if it equals "english" or "English", it shall call a method that does the English version and if there is no parameter or it doesn't equal "English" or "english", it shall call the method for the German version. However, (args[0]=="english"||args[0]=="English") is false no matter what my parameter is, even if it should be true and I don't get why that's the case.

Here is the main method, the other ones aren't important, so I'll leave them away.

public static void main(String[] args){
boolean input=args.length==1;
System.out.println(input);
boolean mode = false;
if (input) mode=args[0]=="English"||args[0]=="english";
System.out.println(mode);
if(input&&mode) english();
else german();
}

Does anyone have a clue why it won't be true, regardless of my parameter?

Exabytez
  • 11
  • 2
  • The println calls are unnecessary, I just put them there to find out why the english method is never called. – Exabytez Oct 19 '13 at 17:40
  • This is most likely explained in any Java FAQ. Don't compare strings with == – Thorbjørn Ravn Andersen Oct 19 '13 at 17:41
  • This question has an extra dimension not covered by [How do I compare strings in Java](http://stackoverflow.com/questions/513832): locales. For natural language comparison the collation API should be used. – McDowell Oct 19 '13 at 18:00

3 Answers3

3

Use the equals() method for String value comparison.

args[0].equals("English")||args[0].equals("english")

or even better(in this case)

args[0].equalsIgnoreCase("English")

== is for object reference comparisons. Don't use it for comparing the values.

Rahul
  • 44,383
  • 11
  • 84
  • 103
0

Strings should not be compared with == but with equals method. Use

args[0].equalsIgnoreCase("English")

it will compare for both, "english" and "English".

better version is

"English".equalsIgnoreCase(args[0]);

this will make sure, if args[0] is null, i.e no argument in your case, it will not throw NPE.

Explaination : Because in Java, == compares objects not there values, i.e if two references are holding same object or not. Objects content are compared with equals method of Object class, which String class overrides.

codingenious
  • 8,385
  • 12
  • 60
  • 90
0

You can't compare strings in Java in this way because Java Machine compare pointers to the string objects. To make correct compassion use function equals:

if( "english".equalsIgnoreCase( args[0] ) ) {
    // English language
}
Nicolai
  • 5,489
  • 1
  • 24
  • 31