Need to change ResultSet.getString(Value)---- conditionally - java

I have a query and a resultset
I do this
while (rs.next())
{
String string = rs.getString(ColumnName);
if (String == "certainvalue")
{
//perform action
}else {
//do nothing
}
My problem is that the if condition doesn't seem to be working.... even though I know "certainvalue" is in the result set, it never evaluates to true, and it never performs the action---- I am confused as to why that is...
is it because i am using a while loop?? or is it because resultsets are just wierd,, ,what is going on???

Java can't compare strings with ==. What you have to do is use the equals method of the String.
if (string.equals("certainvalue")) {
perform action
}

It looks you're using Java. In that case, the == operator compares if the two objects are the same, not if they represent the same value.
Rewrite the test :
if ("certainvalue".equals(string)) { doStuff(); }
(You might consider "a".equals(b) to be equivalent to b.equals("a"), but the first form protects you from a NullPointerException if there is no value for the row in the database.)

String is an object. You can't do a comparison that way (you are trying to compare object reference).
If you are use java(aren't you?) try:
String string = rs.getString(columnName);
if (string.compareTo("anotherString") == 0){
}
You can use operator == just for primitive types (like int).

Related

What happens when you compare two of the same type objects using ==, >, <, etc, in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference Between Equals and ==
For example, if I have
MyClass foo = new MyClass();
MyClass bar = new MyClass();
if (foo == bar) {
// do something
}
if (foo < bar) {
// do something
}
if (foo > bar) {
// do something
}
how do foo and bar get compared? Does Java look for .compareTo() methods to be implemented for MyClass? Does Java compare the actual binary structure of the objects bit for bit in memory?
Very simply the arithmetic comparison operators == and != compare the object references, or memory addresses of the objects. >, and < and related operators can't be used with objects.
So ==, != is useful only if you want to determine whether two different variables point to the same object.
As an example, this is useful in an event handler: if you have one event handler tied to e.g. multiple buttons, you'll need to determine in the handler which button has been pressed. In this case, you can use ==.
Object comparison of the type that you're asking about is captured using methods like .equals, or special purpose methods like String.compareTo.
It's worth noting that the default Object.equals method is equivalent to ==: it compares object references; this is covered in the docs. Most classes built into Java override equals with their own implementation: for example, String overrides equals to compare the characters one at a time. To get a more specific/useful implementation of .equals for your own objects, you'll need to override .equals with a more specific implementation.
You didn't try it yourself, apparently, because <, >, <= and >= do not work on Objects.
However, == compares the left and right operand. When they are binary the same, it results in true. In the case of objects, in compares the pointers. So which means that this will only result in true if the Object is left and right the very same object in memory.
Other methods, like compareTo and equals are made to provide a custom method of comparing to different objects in memory, but which might be equal to each other (i.e. the data is the same).
In case of Strings, for example:
String str0 = new String("foo");
String str1 = new String("foo");
// A human being would say that the two strings are equal, which is true
// But it are TWO different objects in memory. So, using == will result
// in false
System.out.println(str0 == str1); // false
// But if we want to check the content of the string, we can use the equals method,
// because that method compares character by character of the two objects
String.out.println(str0.equals(str1)); // true
String.out.println(str1.equals(str0)); // true
No it doesn't. It compares whether the two variables are references to the same objects.
Unless you're dealing with types which are subject to autoboxing, such as Integer, you can't use > and < with objects at all.
In the case where you are using an autoboxed type, java doesn't look for specific methods, but will auto-unbox the variables, turning them into primitives - but this isn't the case for the equals operator. The == operator will always compare objects as references, even when comparing autoboxed objects:
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
if(i1 < i2) { // evaluates to false!
System.out.println("i1 is less than i2");
}
else if(i1 > i2) { // evaluates to false!
System.out.println("i1 is greater than i2");
}
else if(i1 == i2) { // evaluates to false!
System.out.println("i1 and i2 are equal");
}
else {
System.out.println("Um... well that's just confusingi");
}
It compares the reference value and will only return true if foo and bar point to the same object.
In Java, "==" compares the object identity. "new" is guaranteed to return a new object identity each time.
I'd actually love if "==" would call compareTo. Alas, it doesn't.

Strings look the same but test says they are different

I have some code which is effectively the following:
String a;
String b;
a = get_string_from_complex_procedure_1();
b = get_string_from_complex_procedure_2();
if (a != b)
{
put_up_error_dialog("["+a+"] != ["+b+"]");
}
The code is designed such that a and b should end up identical, and indeed most of the time they are, but occasionally I get the error dialog appearing. The confusing thing though, is that the two strings appear identical to me when reported by the dialog. I'm wondering what sort of things can cause this problem?
Rewrite like this:
String a;
String b;
a = get_string_from_complex_procedure_1();
b = get_string_from_complex_procedure_2();
if (!a.equals(b))
{
put_up_error_dialog("["+a+"] != ["+b+"]");
}
The == and != operators compare references, not values.
You cannot use == and != on Strings. To compare two Strings use a.equals(b) and !a.equals(b)
Use of == or != in case of String compares reference (memory location) so better you use equals() method.
use
a.equals(b); or a.equalsIgnoreCase(b) to compare String.

Java code snippet logic

I cannot see what I am doing wrong here. Here is the code I am having trouble with :
String tempSummaryString = "SUMMARY:";
for(int z = 0; z<attributeList.size() ; z++)
{
System.out.println(attributeList.get(z).substring(0,tempSummaryString.length()));
if(attributeList.get(z).length() > tempSummaryString.length() &&
attributeList.get(z).substring(0,tempSummaryString.length() == tempSummaryString)
{
event.setTitle(attributeList.get(z).substring(tempSummaryString.length(),attributeList.get(z).length()));
}
}
Now my problem is that the program never goes into the if (does not execute the event.setTitle method). When I print the value of
attributeList.get(z).substring(0,tempSummaryString.length())
I get the following:
SUMMARY:
So I am stumped about why it is not entering the if! I don't get it!
Hopefully someone can point out a stupid mistake I am making because I really dont know what else to do
You've fallen for the old == vs equals() problem. You are using ==, which unlike javascript, does an identity comparison (ie are these the same objects).
Try this:
attributeList.get(z).substring(0,tempSummaryString.length())
.equals(tempSummaryString) // equals() not ==
Also, you should consider using the foreach syntax for your loop:
for (String attribute : attributeList) {
if (attribute.substring... // forget about attributeList.get(z) and even z
}
Don't compare strings using the == operator (as in attributeList.get(z).substring(0,tempSummaryString.length()) == tempSummaryString), use the String.Equals method instead.
Your problem is this: attributeList.get(z).substring(0,tempSummaryString.length())== tempSummaryString. You compare references, not string contents. Use String.equals(otherString) to that end.
You should compare the Strings with equals().
attributeList.get(z).substring(0,tempSummaryString.length()).equals(tempSummaryString)
You're comparing strings with ==, while you should use the String class' .equals() method.

Search method always null

I'm having issues with a method I've written to search a class called Item. No matter what I search, it is returning null. I believe I'm having issues with variable scope:
public Item search(String itemSearch) {
Item search = null;
for(Item i : items){
if (i.getName() == itemSearch){
search = i;
}
}
return search;
}
The getName method returns the name attribute of the item. No matter what the Item search is always null, I'm guessing this is due to variable scope and it is not assigning in the for each loop? Why is this method always null?
Thank you
You can't use the == to compare the content of two strings in java. You need to use the .equals() method
Using the == will only compare the adress of the two strings, while equals will compare their values.
You are comparing strings using ==. You should instead use equals() method. E.G
i.getName().equals(itemSearch)
Also instead of looping the entire loop use return i in the if statement, instead of assigning i to search and then returning search.

Dynamic if statement evaluation problem with string comparison

I tried the example given in this thread
to create if statement dynamically using BeanShell. But it is not working fine. Instead of using "age" variable as integer, i have used string in the below example. I am getting "fail" as answer instead of "success".
Can anyone help me?
/*
To change this template, choose Tools | Templates
and open the template in the editor.
*/
import java.lang.reflect.*;
import bsh.Interpreter;
public class Main {
public static String d;
public static void main(String args[])
{
try {
String age = "30";
String cond = "age==30";
Interpreter i = new Interpreter();
i.set("age", age);
System.out.println(" sss" + i.get("age"));
if((Boolean)i.eval(cond)) {
System.out.println("success");
} else {
System.out.println("fail");
}
}
catch (Throwable e) {
System.err.println(e);
}
}
}
Thanks,
Mani
You have to choose either numeric comparison or String comparison. This requires using a compatible condition and type for age.
Numeric:
int age = 30;
String cond = "age==30";
String:
String age = "30";
String cond = "age.equals(\"30\")";
When you compare two objects with the == operator, you're comparing two references. You're essentially asking whether two different names refer to the same object in memory.
To compare the actual values of objects, you need to use the equals() method. This is something that's very important to understand about Java.
#Matthew Flaschen is correct. As an aside, you can simplify your output as follows:
System.out.println(cond + " is " + i.eval(cond));
which produces
age == 30 is true
You are using == to compare string types. Try using age.equals("30") instead.
EDIT: to show it working
If you use this as the definition of cond:
String cond = "age.equals(\"30\")";
Output:
sss30
success
In response to the question about using =="30" instead, here is the answer to that:
If your String age is interned, because it is a compile-time constant for example, then it could be true.
final String age = "30";
However if you explicitly new the String or it is otherwise not interned, then it will be false.
String age = new String("30");
You can run both examples to see this in effect. Possibly - you may get fail for both.
Now, just because interning exists doesn't mean one should ever rely on it for comparing String types. The == operator should only be used to compare primitives to each other, and to compare reference types to see if they point to the same object, so for reference types we could say it is seeing if two objects are identical instead of equal.
Sometimes through the magic of the JVM and JDK, String and other primitive wrappers like Integer may be comparable with ==, but the situations for this are limited and not reliable.
The string compare with "==" in the bsh interpreter is not working like expected.
It is working like that: (copied from the link bellow)
Beanshell handles '==' like java and not e.g. like JavaScript. That means you've got to use "equals" to compare instances.
bsh % "abc" == "abc"; => true
bsh % "abc" == new String("abc"); => false
bsh % "abc".equals("abc"); => true
bsh % "abc".equals(new String("abc")); => true
further information here: https://code.google.com/p/beanshell2/issues/detail?id=86
So you have to use the ".equal()", or compile your own bsh version, like i did it.
(read the complete issue above)

Categories

Resources