Program fails to compare a String Token with a String.
I'll just post a portion of my code that I have a question about.
Code:
String strLine = null;
while ((strLine = br.readLine()) != null)
{
String outputLine1 = "";
String key = "";
String outputLine2 = "";
StringTokenizer st = new StringTokenizer(strLine, "<>", true);//System.out.println("yasar");
while(st.hasMoreTokens())
{
key = st.nextToken();System.out.println(key);
//String val = st.nextToken();
if(key == "<"){
outputLine1 += key;
outputLine2 += key;
String val = st.nextToken();
for ( int i = 0; i < val.length(); ++i )
{
char c = strLine.charAt(i);
int j = (int) c;
int k = j+1;
char d = (char) k;
outputLine1 += c;
outputLine2 += d;
}
}
else if(key == ">"){
outputLine1 += key;
outputLine2 += key;
}
}
output.write(outputLine2);
//System.out.println(outputLine1);
System.out.println(outputLine2);
}
It fails to compare the token named 'key' in the if-else if condition inside the nested while. As a result, code inside this if-else branch is never executed. Can anybody let me know why is that so? Maybe its something trivial that i'm missing..
Re: Program fails to compare a String Token with a String.
Don't compare two Strings for equality with the == operator; use the equals( ... ) method instead.
kind regards,
Jos
Re: Program fails to compare a String Token with a String.
Okay i figured out my problem. Strings (which are objects) can not be compared like primitive data types. I thought they can be compared the same way as i was doing in C++.
Re: Program fails to compare a String Token with a String.
Thanks Joe. Ur help is appreciated.
Re: Program fails to compare a String Token with a String.
Quote:
Originally Posted by
yasarqamar
Okay i figured out my problem. Strings (which are objects) can not be compared like primitive data types. I thought they can be compared the same way as i was doing in C++.
You can only do that in C++ because the == operator is overloaded for the 'string' type objects. Java doesn't have full blown operator overloading (praise the lord for that) ...
kind regards,
Jos