String comparison to constant error [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I have this code its working fine in retreiving the value from the url, but its not recognizing that the string is "True" is the toString() what I need or something else?
try {
URL url = new URL("http://www.koolflashgames.com/test.php?id=1");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc
.getInputStream()));
inputLine = in.readLine();
inputLine = inputLine.toString();
if(inputLine == "True") {
logger.info(inputLine);
player.sendMessage("Thanks");
}else{
logger.info(inputLine);
player.sendMessage("HAHAHA");
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}

You cannot use == to compare the content of Strings, as they are objects. You have to create a method to compare objects. In the case of strings, you can use stringName.equals(otherString).

I beg to differ. Use .equalsIgnoreCase() method to compare the string ignoring the case. This will match all cases, such as "True", "TRue", "tRue".. etc approximately 16 matches.

You must use equals to compare strings. Replace:
if(inputLine == "True") {
with:
if(inputLine.equals("True")) {
The operator == tells you if two references refer to the same object, not if the values are the same.

In order to compare String objects, use the equals() method.
The == operator checks whether the two Strings have the same reference.
See How do I compare strings in Java? for more info.

Related

can not match the String get from properties file in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have a line in file config.properties
clean=true
and use following code to get this property
private static String clean;
Properties prop = new Properties();
try {
prop.load(new FileInputStream("config.properties"));
clean = prop.getProperty("clean");
}
I use System.out.println(">"+clean+"<") to see the output and get ">true<", which indicates there is no blank, no \n
However, when I use
if (clean == "true") {
// program does not go here
}
else {
// program goes here
}
what is the possible reason?...
Try the following:
== checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
if (clean.equals("true")) {
// program does not go here
}
else {
// program goes here
}
The Problem is you are using equality operator which doesn't compare literal instead references. So you have to use equals method to do literal check
if ("true".equals(check)) {
// Now Program will go here
}
else {
// and now here
}

Why following code printing False? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Replace will create new object and both side this new will be compared. then why it showing false.
When exactly created new string will be added in string pool?
if("String".replace("g", "G") == "String".replace("g", "G"))
{
System.out.println("True");
} else {
System.out.println("False");
}
because replace() will always return a new String instance. So the 2 same calls to replace method will return 2 different instances with same value.
use equals() instead of == if you want to compare value
Use intern() on both replaced values if you want to add the string to the string constants pool (and are bent on using == :P)
if ("String".replace("g", "G").intern() == "String".replace("g", "G").intern()) {
System.out.println("True");
} else {
System.out.println("False");
}
}
OP :
true

Domino java example code does not work properly [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Check whether a String is not Null and not Empty
(35 answers)
Closed 8 years ago.
Here is a code from the Domino 8 designer help to get database categories.
The condition "if(cat != "") always return true though database category is empty or non-empty. What is catch?
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext =
session.getAgentContext();
// (Your code goes here)
Database db = agentContext.getCurrentDatabase();
String title = db.getTitle();
String cat = db.getCategories();
if (cat != "")//This condition does not work
System.out.println("Database \"" +
title + "\" has the categories: " + cat);
else
System.out.println("Database \"" +
title + "\" has no categories");
} catch(Exception e) {
e.printStackTrace();
}
}
}
Use this for the if condition
!"".equals (cat)
Direct equal checks for reference equality, not content equality.
Inverting cat and the empty string takes care of the null condition without any crutches since the empty string is never null.
I like to use Google's Guava for these kinds of things especially when dealing with String
In Guava there exist a Class Strings which provide
public static boolean isNullOrEmpty(#Nullable
String string)
Returns true if the given string is null or is the empty string.
so use Strings.isNullOrEmpty(cat)
It worked as if (!cat.isEmpty())!
Even without braces!

Java if Statement under enhanced for loop did not work [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is a code fragment that I am working with for a logon system using hashset Users.
I checked the enhanced for loop part it works but the if statement seems like it never works out, even if the values are equal.
if (comm.equals("Sign in")) {
user urs = new user(p_name, p_pass, p_id );
Iterator<user> iter = Users.iterator();
for(user obj : Users) {
if (p_u == obj.getUsername()&& p_pw == obj.getPassword ()&& p_sn== obj.getStudentID()) {
JOptionPane.showConfirmDialog(
jf,
"Success", "Success",
JOptionPane.DEFAULT_OPTION);
break;
} else {
log_in.setText("Try Again");
exit.setText("Create User");
}
Remember, in Java == operators test the equality of the value, in this case, two references. These two references do not point to the same memory location and therefore will never equate to true. Use the equals() method to test for equality of the values of strings.
I think you need to changed it to something like this:
if (comm.equals("Sign in")) {
user urs = new user(p_name, p_pass, p_id );
Iterator<user> iter = Users.iterator();
for(user obj : Users) {
if (p_u.equalsIgnoreCase(obj.getUsername())&& p_pw.equals(obj.getPassword())&& p_sn.equals(obj.getStudentID())) {
JOptionPane.showConfirmDialog(
jf,
"Success", "Success",
JOptionPane.DEFAULT_OPTION);
break;
} else {
log_in.setText("Try Again");
exit.setText("Create User");
}
Assuming that p_u, p_pw and p_sn are String object references the code below is checking whether those two objects are the same object (or whether their refences to the object's position in memory are the same) rather than whether the String objects share the same character sequence.
if (p_u == obj.getUsername()&& p_pw == obj.getPassword ()&& p_sn== obj.getStudentID())
Instead, to check whether their character sequence matches up you should use the .equals() method. Example below;
if (p_u.equals(obj.getUsername())&& p_pw.equals(obj.getPassword ())&& p_sn.equals(obj.getStudentID()))
I hope this helps.

Java contains doesn't work as expected because "someString" != "someString"

I want check whether a String value val is contained within a List of Strings lets call it stringList.
I am doing this
if(stringList.contains(val)){
System.out.println("The value is in there");
}
else{
System.out.println("There's no such value here");
}
But it always seems to be that the value is not included. Is this because two String values that have the same characters are not actually equal? For a "home-made" class I could implement hashCode() and equals() and fix this, what can I do for String data?
EDIT:
The way I am getting val is outlined here:
List<String> stringList = new ArrayList<String>();
stringList.add("PDT");
stringList.add("LDT");
stringList.add("ELNE");
String myFile = "/folder/myFile";
InputStream input = new FileInputStream(myFile);
CSVReader reader = new CSVReader(new InputStreamReader(input), ',','"', 1);
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
if (nextLine[6] != null){
String val = nextLine[6];
if(stringList.contains(val)){
System.out.println("Success");
}
}
}
}
ArrayList.contains() uses Object.equals() to check for equality (hashCode() is not involved in List). This works well for strings. Probably, your string really isn't contained in the list...
You've probably overlooked some whitespace or upper/lower-case or encoding difference...
More code please!
This works:
import java.util.*;
public class Contains {
public static void main(String[] args) {
List<String> stringList = new ArrayList<String>();
stringList.add("someString");
String val = new String("someString");
if (stringList.contains(val)) {
System.out.println("The value is in there");
} else {
System.out.println("There's no such value here");
}
}
}
That doesn’t sound right: contains uses equals rather than ==, so if the string is in the list, it should be found. This can be verified in the indexOf method of the superclass AbstractList used by ArrayList.
Following your edit, make sure you trim strings before doing contains, as otherwise they may contain the newline character(s).
Try the following, first make the check more concrete by iterating the list and checking each element separately. Than, when you hit the elements that you are expecting to be equal, This is what you are supposed to be looking at. Check to see if they are really equal. Maybe there is a case difference? (or some other elusive but plain difference like white space?)
Try to override equals(){}, so that you can specify which property needs to compare equality .... :P

Categories