Reputation: 3
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);}
}
}
Upvotes: 0
Views: 180
Reputation: 11117
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?
Upvotes: 4