Java code snippet logic - java

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.

Related

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 Does Not Equal (!=) Not Working? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Here is my code snippet:
public void joinRoom(String room) throws MulticasterJoinException {
String statusCheck = this.transmit("room", "join", room + "," + this.groupMax + "," + this.uniqueID);
if (statusCheck != "success") {
throw new MulticasterJoinException(statusCheck, this.PAppletRef);
}
}
However for some reason, if (statusCheck != "success") is returning false, and thereby throwing the MulticasterJoinException.
if (!"success".equals(statusCheck))
== and != work on object identity. While the two Strings have the same value, they are actually two different objects.
use !"success".equals(statusCheck) instead.
Sure, you can use equals if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:
if ("success" != statusCheck.intern())
intern method is part of standard Java String API.
do the one of these.
if(!statusCheck.equals("success"))
{
//do something
}
or
if(!"success".equals(statusCheck))
{
//do something
}
Please use !statusCheck.equals("success") instead of !=.
Here are more details.
You need to use the method equals() when comparing a string, otherwise you're just comparing the object references to each other, so in your case you want:
if (!statusCheck.equals("success")) {
you can use equals() method to statisfy your demands. == in java programming language has a different meaning!

Java compare char on string array

Imagine I have a String array like this:
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"};
If I do this:
for (int i = 0; i < fruits.length;i++){
System.out.println(fruits[i][0].charAt(1));
}
it will print:
r
p
r
And if I do this:
for (int i = 0; i < fruits.length;i++){
Character compare = fruits[i][0].charAt(1);
System.out.println(compare.equals('r'));
}
it will print:
true
false
true
So here is my question. Is it possible to use charAt and equals on the same line, I mean, something like this:
System.out.println((fruits[i][0].charAt(1)).equals("r"));
Regards,
favolas
Yes, provided you convert the result of charAt() to Character first:
System.out.println(Character.valueOf(fruits[i][0].charAt(1)).equals('r'));
A simpler version is to write
System.out.println(fruits[i][0].charAt(1) == 'r');
I personally would always prefer the latter to the former.
The reason your version doesn't work is that charAt() returns char (as opposed to Character), and char, being a primitive type, has no equals() method.
Another error in your code is the use of double quotes in equals("r"). Sadly, this one would compile and could lead to a painful debugging session. With the char-based version above this would be caught at compile time.
Certainly! Try this:
System.out.println((fruits[i][0].charAt(1)) == 'r');
We're doing a primitive comparison (char to char) so we can use == instead of .equals(). Note that this is case sensitive.
Another option would be to explicitly cast the char to a String before using .equals()
If you're using a modern version of Java, you could also use the enhanced for syntax for cleaner code, like so:
public static void main(String[] args) {
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"}};
for (String[] fruit: fruits){
System.out.println((fruit[0].charAt(1)) == 'r');
}
}
The char data type, which is returned from String.charAt() is a primitive, not an object. So you can just use the == operator to perform the comparison as it will compare the value, not the reference.
System.out.println((fruits[i][0].charAt(1) == 'r'));

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

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).

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