DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2004

    Comparing a Scanner string to a manually typed string

    PHP Code:
    import java.util.Scanner;

    public class 
    test {

        public static 
    void main(String[] args) {
    String testOne "foo";
    String testTwo "foo";
    Scanner scan = new Scanner(System.in);
    System.out.print("Insert \"foo\" as a value for busted: ");
    String busted scan.next();
            if (
    testOne == busted)
    System.out.println("scanned string comparison is working");
            else if (
    testOne == testTwo)
    System.out.println("predefined string comparison is working");
    System.out.println("String comparison is completely busted");      

    When this is run and I enter "foo" for scanner the first if statement is false. Why does this happen?

  2. #2
    Join Date
    Mar 2004
    The "==" operator when used with strings, compares the memory location of the two strings, not the actual text. use the String's equal() method.

    if (testOne.equals(busted))

  3. #3
    Join Date
    Feb 2004
    if there is the possibility that one string will be null, either test for that null first, or swap the .equals clauses over:

    //test for null
    if(userInput!=null && userInput.equals("quit"){


    in the first case, if userInput is null the first condition is FALSE. false, ANDed with anything will always be false, so java gives up without testing the second part. order of evaluation is always left to right

    in the second case, "quit" is a string literal and will never be null. you can think of it like this if it helps:

    new String("quit").equals(userinput)

    if null is fed into .equals() then the result will always be false, as the only thing it could be true with, is another null (but that would cause an exception):

    String s = null;
    s.equals(null) //bang! nullpointer exception because s is null (cant call equals method)

    so.. er.. yeah.. 2 tips for avoiding problems
    The 6th edict:
    "A thing of reference thing can hold either a null thing or a thing to any thing whose thing is assignment compatible with the thing of the thing" - ArchAngel, www.dictionary.com et al.
    JAR tutorial GridBag tutorial Inherited Shapes Inheritance? String.split(); FTP?

  4. #4
    Join Date
    Oct 2004
    Appreciate the help. Thanks guys. Java is a whole new world for me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center