0

What I basically want to do is that I first write a char "123" to the file test2.txt. Then I read it, store the read value in the variable z(char datatype) and compare it with "123" in the (if) part. But it returns NO MATCH... Even though the value of variable z is "123"(System.out.println(z) prints 123 on the screen). Why is it happening this way? Also I checked out the test2.txt file. It contains 123 with a small L behind the 123(caused due to what? unicode conversion or something??) , which i consider the root if the problem. Please help. Thanks in advance.

Source Code:

import java.io.*;

public class readWrite
{
    public static void main(String[]args)
    {
        RandomAccessFile file=null;
        try{
            file=new RandomAccessFile("test2.txt","rw");
            file.writeUTF("123");
            file.seek(0);
            String z=file.readUTF();
            if (z=="123")
            {
                System.out.println("MATCH");
            }
            else
            {
                System.out.println("NO MATCH");
            }
        }
        catch(IOException e){System.out.println(e);}
    }
}
TheEwook
  • 11,037
  • 6
  • 36
  • 55

1 Answers1

4

z is a string and it should be compare using equal() method

Try doing this instead:

    if ("123".equals(z))
    {
        System.out.println("MATCH");
    }
    else
    {
        System.out.println("NO MATCH");
    }

More information here to compare a string:

How do I compare strings in Java?

Community
  • 1
  • 1
TheEwook
  • 11,037
  • 6
  • 36
  • 55
  • 1
    Yes. The program works now. Thank you. By the way its if("123".equals(z)) [no offence.. mentioning just in case some other person looks for reference] Could you help me out with the "small L part" which is behind the string 123 in the test2.txt file? Would be happy if you can. Thanks again! – user3050178 Dec 04 '13 at 15:18
  • @user3050178 Ooops! Thanks noticing it ;) – TheEwook Dec 07 '13 at 11:08