Java Does Not Equal (!=) Not Working? [duplicate] - java

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!

Related

Simple Java password entry verification won't work [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I don't know what's going on with it. Code below. I'm not trying to get anyone to code the whole thing for me, just don't know what's wrong and would like a little help
private void javabutton1(java.awt.event.ActionEvent evt) {
String testa= new String (jPasswordField2.getPassword());
String testb= new String (jPasswordField3.getPassword());
if (testa.toString() == testb.toString()){
JOptionPane.showMessageDialog(this, "Success");
}
}
When I replace testa.toString() == testb.toString()) with "A" == "A".
The messagebox "Success" is achieved but this entry comparison won't work
Also: The text entered in both jPasswordField2 and jPasswordField3 are the same.
You should try:
testa.equals(testb)
And there is no point of doing this:
String testa = getSomething();
String temp = testa.toString();
// becasue
testa.equals(temp) // always true
If you would have something like:
String a = getSomething();
String b = a;
a == b // now this is true, because they have the same reference/pointer
Use .equals() when comparing strings.
Try with String.equals()
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.
Fix your issue by using String.equals(string) like this
String testa= new String (jPasswordField2.getPassword());
String testb= new String (jPasswordField3.getPassword());
if (testa.equals(testb)){
JOptionPane.showMessageDialog(this, "Success");
}
Basically, you should never use == to compare Strings, instead use equals(), so for you:
testa.equals(testb)
The difference is that == is used to compare references, it is saying: "Do these two String references point to the same String object in memory?"...this is unpredictable due to how Java stores Strings, which basically accounts for why "A" == "A" returns true...not something to go into here.
The equals() method is more what you would expect, in the Java Class String, this method basically checks whether or not each character in the String is the same, and returns true if they do.
If it's an object, you should use equals() to compare, if its a primitive data type, such as an int (or you are checking if a reference is null) then use ==.
While I agree with Takendarkk that answer duplicate questions promotes their repeated posting, I think there is at least one issue that should be noted which has not been mentioned. StephenTG asked a poignant question in the comments: "Why do you need to convert your Strings to Strings?"
Given the name of your variables, if you are indeed using the swing JPasswordField, then the getPassword() method returns a char[] array. You don't need to convert this to a string, you can compare them using java.utils.Arrays#equals(char[]. char[]) to get the result you desire. Your code might look like this:
private void javabutton1(java.awt.event.ActionEvent evt) {
char[] testa = jPasswordField2.getPassword();
char[] testb = jPasswordField3.getPassword();
if (Arrays.equals(testa, testb)){
JOptionPane.showMessageDialog(this, "Success");
}
}

Get the position of a given item in an ArrayList [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have an ArrayList of type Vertex. Vertex is my own class which contains only one data member of String type. It has a member function getName() which returns the name of the Vertex.
I want to get the position in the ArrayList, if a particular string is given. I've written the below code to do it. But it always returns -1, which is the initial value. What is the problem with my code?
public int map(String vname)
{
int pos=-1;
for(int i=0;i<nodes.size();i++)
{
if(nodes.get(i).getName()==vname)
{
pos=i;
break;
}
}
return pos;
}
In the above code, nodes is an ArrayList of type Vertex.
Use String#equals: nodes.get(i).getName().equals(vname) instead. == in Java compares address of the
string.
== compares references not the content.
Use String#equals() if case is important otherwise use String#equalsIgnoreCase().
In Java == is for object equality, string1.equals(string2) is for string equality
You String comparison is wrong...
if(nodes.get(i).getName()==vname)
Should be
if(nodes.get(i).getName().equals(vname))
Replace it with
if(nodes.get(i).getName()==vname)
to
if(nodes.get(i).getName().equals(vname))
for comparing String with the case And for Comparing vname without case use
if(nodes.get(i).getName().equalsIgnoreCase(vname))

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.

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

is there a Java equivalent to null coalescing operator (??) in C#? [duplicate]

This question already has answers here:
How to get the first non-null value in Java?
(13 answers)
Closed 5 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Is it possible to do something similar to the following code in Java
int y = x ?? -1;
More about ??
Sadly - no. The closest you can do is:
int y = (x != null) ? x : -1;
Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.
Guava has a method that does something similar called MoreObjects.firstNonNull(T,T).
Integer x = ...
int y = MoreObjects.firstNonNull(x, -1);
This is more helpful when you have something like
int y = firstNonNull(calculateNullableValue(), -1);
since it saves you from either calling the potentially expensive method twice or declaring a local variable in your code to reference twice.
Short answer: no
The best you can do is to create a static utility method (so that it can be imported using import static syntax)
public static <T> T coalesce(T one, T two)
{
return one != null ? one : two;
}
The above is equivalent to Guava's method firstNonNull by #ColinD, but that can be extended more in general
public static <T> T coalesce(T... params)
{
for (T param : params)
if (param != null)
return param;
return null;
}
ObjectUtils.firstNonNull(T...), from Apache Commons Lang 3 is another option. I prefer this becuase unlike Guava, this method does not throw an Exception. It will simply return null;
No, and be aware that workaround functions are not exactly the same, a true null coalescing operator short circuits like && and || do, meaning it will only attempt to evaluate the second expression if the first is null.

Categories

Resources