Results 1 to 4 of 4
  1. #1
    aznprdgy is offline Member
    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Default Why aren't my arrays equal?

    I'm writing a code and one of the problems I came across is that reading from a file and actually imputing values will not give the same result. I created this code to simulate my problem:

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    
    public class test {
    	 public static void main (String [] args)throws IOException{
    	 File filename = new File(args[0]); //I created a file "data" that contains "Hi"
    	 Scanner scan = new Scanner(filename);
    
    	 String []test1 = new String [1];
      	 String []test2 = new String [1];
    
      	 for(int i=0;i<test1.length;i++)
      		 test1[i]=scan.next();
      	 test2[0]="Hi";
      	 if(test2[0]==test1[0])
      		 System.out.println("Hi");
      	 else
      		 System.out.println("fail");
      	 
    	 }
     }

    OUTPUT
    fail

    I'm not exactly sure why this is so if someone could tell me why it's like this and how to fix this problem i would appreciate it.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Why aren't my arrays equal?

    Strings - and other objects - should be compared using the equals() method and not ==.

    The point is that all classes define "equals" in a way that makes sense for them. In the case of strings what you want to do is see if they are made up of the same characters in the same order, which is what test2[0].equals(test1[0]) does. This is not the same thing as ==, which is more like "identical". For instance, the third word in this sentence is equal to the 12th but they are not identical because the sentence contains twenty eight words not twenty seven.

  3. #3
    aznprdgy is offline Member
    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Default Re: Why aren't my arrays equal?

    Ah thank you so much I completely forgot about the equals() method!

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

Similar Threads

  1. comparing 2 arrays to see if they're equal
    By Get_tanked in forum New To Java
    Replies: 2
    Last Post: 02-17-2011, 07:59 AM
  2. Downloaded images aren't viewable
    By pietertje in forum New To Java
    Replies: 12
    Last Post: 07-05-2010, 03:56 PM
  3. so whats going on? (things aren't showing up)
    By Adrien in forum AWT / Swing
    Replies: 9
    Last Post: 02-20-2010, 08:22 PM
  4. Replies: 4
    Last Post: 02-17-2010, 11:17 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •