#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0

    Help with compare strings


    Code:
    public class CompareInputToString {
        public static void main(String[] args) {
            String city = "Lancaster";
            String state = "Ohio";
    
            try {
                \\if (city == args[0] && state == args[1]) {
                if (city.equals(args[0]) && state.equals(args[1])) {
                    System.out.println("Input is the same as \nCity:" + city + "\nState:" + state);
                } else {
                    System.out.println("Not the same as \nCity:" + city + "\nState:" + state);
                    System.out.println("Args[0] is: " + args[0]);
                    System.out.println("Args[1] is: " + args[1]);
                }
            } catch (Exception e) {
                //
            }
        }
    }
    Can anyone tell my why the if statement did not work with the two ==. It works now if you change the two == to .equals.
    The two args i put in at the command line are java options.CompareInputToString "Lancaster", "Ohio"
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    103
    Rep Power
    3
    You can't compare Strings using the "==" operators. You need to use the equals method.

    e.g.
    String1.equals("Hello");
    String1.equals(String2);

    I can give you a more detailed explanation about why if you are interested.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0
    OK thank you.
    That did help.

IMN logo majestic logo threadwatch logo seochat tools logo