It seems to me that this if statement is not working.
I'm new in java, but i know C# and C++ pretty well, but I've never seen such a thing before:
today=edit[0].substring(0,10);
if (today == edit[0].substring(0,10))
{
pars_prog.addView(name_prog[i]);
}
And it doesn't get into the IF function?
Are if statements different in Java (Android)?
When you use == for any object references (whether strings or any other non-primitive type) it simply compares whether the references are equal - i.e. whether they refer to the exact same object, or whether they're both null.
In this case, you want to determine whether the strings are equal - i.e. whether they represent the same sequence of characters. You should use the equals method for that:
if (today.equals(edit[0].substring(0,10)))
However, in general when doing this you should be careful that the target of the equals call is non-null, or you'll get a NullPointerException.
Note that C# is similar - except that the == operator can be overloaded, and is overloaded for string. If the compile-time types of the operands aren't both string, you'll still get reference comparison:
object text1 = new StringBuilder("hello").ToString();
object text2 = new StringBuilder("hello").ToString();
Console.WriteLine(text1 == text2); // False
You are trying to compare strings with ==, which is identity comparison - it will check if the two are the same instance (in the JVM) rather than comparing their contents.
Use today.equals(..) instead.
That said, if appears you are working with dates, so a String is not the best way to handle this. Use Calendar, Date (a bit obsolete) or joda-time DateTime
You have to use the equals method when comparing strings.. Right now you are comparing references and thats why you never enter the if block
Related
In java we need to compare objects using .equals() instead of ==. But why can't the compiler do this for us? For example:
if (myString == myOtherString){
doSomething();
}
why cant the compiler go "oh, we're comparing objects!", and change it to this:
if (myString.equals(myOtherString))
Why do we do this manually?
Edit - Guys, I know the difference between == and .equals(). You can stop telling me how ignorant I am. My question was why not just substitute .equals() since its what you want 99% of the time. I have learned that there are cases where knowing if two objects are truly the same reference is useful.
The == operator and equals() often do quite different things. It's only the default implementation of equals() inherited from Object that reverts to using ==. (String is a good example: strings that are equal() are often not ==.) Also, the first example in your code will execute fine if myString is null, while the second will throw an exception.
Sometimes you really just want to know if two object references are to the same object, not whether they refer to objects that have "the same contents" (the meaning of which is usually what equals() implements). Automatically converting == to equals() would be a bad idea.
There is a difference. equals(Object) checks if two objects are equal - i.e., have the same state. The == operator checks if two references indeed point to the same object. It isn't a common usecase, but it definitely has its usages - e.g., to borrow from IdentityHashMap's documentation:
A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.
Is there a reason the java compiler cannot just substitute .equals for == when comparing objects?
Java uses both equals() and ==
When you use == to compare objects, you are comparing whether the 2 objects reference the same instance.
When you use .equals(), most of the time you will be comparing one or some of the attributes of the 2 objects. (Comparing the 2 objects' content)
Example for use of == in optimization
public boolean equals(square s){
if(this == s){ //If s and this object is the same instance
return true; //return true straight away, no further checking needed
}
return (this.length == s.getLength() && this.breadth == s.getBreadth());
}
In Java, if one is to check if two Strings are equal, in the sense that their values are the same, he/she needs to use the equals method. E.g. :
String foo = "foo";
String bar = "bar";
if(foo.equals(bar)) { /* do stuff */ }
And if one wants to check for reference equality he needs to use the == operator on the two strings.
if( foo == bar ) { /* do stuff */ }
So my question is does the == operator have it's use for the String class ? Why would one want to compare String references ?
Edit:
What I am not asking : How to compare strings ? How does the == work ? How does the equals method work?
What I am asking is what uses does the == operator have for String class in Java ? What is the justification of not overloading it, so that it does a deep comparison ?
Imagine a thread-safe Queue<String> acting as a communication channel between a producer thread and a consumer thread. It seems perfectly reasonable to use a special String to indicate termination.
// Deliberate use of `new` to make sure JVM does not re-use a cached "EOT".
private static final String EOT = new String("EOT");
...
// Signal we're done.
queue.put(EOT);
// Meanwhile at the consumer end of the queue.
String got = queue.get();
if ( got == EOT ) {
// Tidy shutdown
}
note that this would be resilient to:
queue.put("EOT");
because "EOT" != EOT even though "EOT".equals(EOT) would be true.
What use is there for it? Not much in normal practice but you can always write a class that operates on intern()-ed strings, which can then use == to compare them.
Why it isn't overloaded is a simpler question: because there is no operator overloading in Java. (To mess things up a bit, the + operator IS sort of overloaded for strings, which was done to make string operations slightly less cumbersome. But you can argue that's just syntactic sugar and there certainly is no operator overloading in Java on the bytecode level.)
The lack of an overloaded == operator made the use of the operator much less ambiguous, at least for reference types. (That is, until the point autoboxing/unboxing was introduced, which muddies the waters again, but that's another story.) It also allows you to have classes like IdentityHashMap that will behave the same way for every object you put into it.
Having said all that, the decision to avoid operator overloading (where possible) was a fairly arbitrary design choice.
The == operator compares the reference between two objects. For example, if String x and String y refers to two different things, then the == operator will show false. However, the String.equals() method compares not if they refer to each other, but if the values (ex. "Hello", "World", etc.) are the same.
// A.java
String foo1 = "foo";
// B.java
String bar1 = "foo";
All String literals realized at compile time are added to String Constant Pool. So when you have two different String declarations in two different classes, two String objects will not be created and both foo1 & bar1 refer to the same String instance of value foo. Now that you have same String reference in two different variables, you can just check if those two strings are equal just by using == which is fast because all it does is compare the bit pattern, where as in equals() method, each character is compared and is generally used for two different String instances but same content.
In fact, if you look at equals() implementation in String class, the first check they do is Reference comparison using == because they might seem as different instances to you, but if they're String literals or if they're interned by someone else already, then all you have is a Single reference in two variables.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
// remaining code
}
Also, == is not just for Strings, it's used to compare any two bit patterns, be it primitives or references
1."=="operation of comparison are the values of the two variables are equal, for a reference type variables is expressed by the two variables in the heap memory address is the same, namely the stack have the same content.
2."equals"Whether the two operation variables represent references to the same object in the heap, i.e. whether the contents of the same.
String s = "string1"; creates 1 reference and 1 object in pool String
s1 = "string1"; creates just 1 reference and points to what s is
pointing to.
s == s1 // true
String s2 = new String("string1"); creates 1 object in heap, one in
pool and one reference.
//Since, s2 is pointing to different object so,
s2 == s // false
s1 == s // false
Problem :
So, suppose We want to check, how many unique String object is created and stored in pool by the application while it is running,
We can have a singleton object which can have all the String references stored in an array.
From the previous examples of s, s1 and s2, finally for s and s1, 1 object is created and for s2, 1 object (in total 2).
//If we use equals method, all
s.equals(s1) // gives true
s1.equals(s2) // gives true
//So, number of references present in the array of singleton object will be our
//total number of objects created which equals to 3 // doesn't match actual
//count which is 2
we can use == to check for equality of reference, so if reference is equal, we will not increment our count of unique String object in pool, and for every non equal result, we will increment the count.
here,
for
s // count = 1
s1 == s // count remains same
s2 == s // false, so count = 1 + 1 = 2
//We get total number of unique String objects created and got stored in pool using ==
Simple answer...
Why would one want to compare String references ?
Because they want to compare String values in a very fast way.
Strings are not always interned(). String constants are, but it is possible that the string was created manually on the heap. Using the intern() on a manually created string allows us to to continue using reference comparison on our strings for value comparison.
What is the justification of not overloading it, so that it does a deep comparison ?
Because Java does not have operator overloading as a design decision
Operator '==' is a reference operator always, and equals() is a value method always. In C++ you can change that, but many feel that simply obfuscates the code.
Checking references is Faster compared to checking the entire Strings' equality.
Assume you have Large Strings (URLs or DBMS queries), a have multiple references to them. To check if they are equal, either you can check character by character or you can check if they both refer to the same object.
In fact, equals method in java first checks if the references are same and only if not goes ahead and checks character by character.
Java is full of references and hence, you might need a case where you need to check if two variables are referring to the same String/Object rather than both having each copy of the same String so that you can update string at one place and it reflects in all variables.
To do so, equals method does not help as it checks the copies to be equal as well. you need to check if they both refer to the same object and hence == comes into picture.
It seems that this was asked before and received quite a popular answer here:
Why didn't == operator string value comparison make it to Java?
The simple answer is: consistency
I guess it's just consistency, or "principle of least astonishment".
String is an object, so it would be surprising if was treated
differently than other objects.
Although this is not the fundamental reason, a usage could be to improve performances: before executing a heavy computation, "internalize" your Strings (intern()) and use only == for comparisons.
What I am asking is what uses does the == operator have for String class in Java ?
What is the justification of not overloading it, so that it does a deep comparison ?
== and equals have altogether different uses.
== confirms if there is reference-equality
Equals confirms if the objects contains are same.
Example of reference-equality is IdentityHashMap.
There could be a case in which Only the object inserting something to IdentityHashMap has the right to get/remove the object.
overloading reference-equality can lead to unwanted complexity for java.
for example
if (string)
{
do deep equality
}
else
{
do reference-equality
}
/*****************************************************************/
public class IdentityHashMap extends AbstractMap implements Map, Serializable, Cloneable
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.
This code is not working:
String name = "Bob";
String name1 = "Anne";
if name = name1;
System.out.println ("Hello");
I am a beginner in Java, please help we with this code. I am trying to compare two strings.
You want:
if (name.equals(name1))
Note that you don't want
if (name == name1)
which would be syntactically correct, but would compare the two string references for equality, rather than comparing whether the objects involved represent the same sequence of characters
Further, note that even the top version will simply perform an ordinal comparison of the UTF-16 code units in the string. If the two strings logically represent the same characters but are in different forms, you may not get the result you expect. If you want to do a culture-sensitive comparison, you should look at Collator.
Additionally, I'd recommend that if you're really new to Java, you start off with console apps and/or unit tests to explore the language instead of JSP - it'll give you a much smoother cycle while you're learning the basics, and a simpler environment to work in.
Even more additionally, the code given at the top will throw a NullPointerException if name is a null reference. You should consider what you want to happen at that point - if the string being null would represent a bug anyway, then the exception is probably appropriate; otherwise, you might want to change the code. One useful method in Guava (which is chock full of good stuff) is Objects.equal:
if (Objects.equal(name, name1))
The method return true if both arguments are null, false if exactly one argument is null, and the result of calling equals() if they're both non-null. Very handy.
Your Mistakes :
You are using "=" operator to compare strings. It is not a conditional operator, it is an Assignment operator. The conditional operator in Java is "==" which is used to compare two values if they are equal or not. You even cannot use this one for Strings.
You are writing like this :
if name = name1;
System.out.println ("Hello");
You have put a semi-colon at the end of if statement. So it will do nothing (if your condition is supposed to be right, which is not in this case) however the condition is true or not.
You are missing parantheses around the condition given in if statement.
Synatx of if statement is : if(condition)
So it is must to write "()" around your condition.
Now, for comparing Strings, String class gives us methods like :
stringOne.equals(stringTwo)
It checks for exactly the same string.
or
stringOne.equalsIgnoreCase(stringTwo)
It will ignore Caps-Small letter case.
You must compare the two variables like this
if (name.equals(name1))
This should work and not the way you did it!!!
if(name.equals(name1))
System.out.println("Hello");
== works only when you compare primitives like int or long.
If you want to compare String you have to use either equals() or compareTo(). Single = is an assignment not comparison by doing name=name1 you essentially assign string name1 to variable name.
Your posted code isn't really Java. In addition, you don't compare '==' with the assignment operator '='. Finally, to do proper comparison of 'Object's or anything descended from Objects you need to use the .equals(...) method.
Comparing with == means "is the same object", not "is an object with the same value". The difference seems to be small; but, if you opt to compare objects by their value, it is not small at all. Two Objects can be created with identical "values", and only .equals(...) allows you to consider those two Objects to be the same.
I found this java code on a java tutorial page:
if ("progress" == evt.getPropertyName())
http://download.oracle.com/javase/tutorial/uiswing/examples/components/index.html
How could this work? I thought we HAVE TO use the equals() method for this situation (string.equals("bla"))? Could we use equals() here too? Would it be better? Any ideas?
Edit: So IF equals() would be better, then I really don't understand why a serious oracle tutorial page didn't use it? Also, I don't understand why it's working because I thought a string is an object. If I say object == object, then that's a big problem.
Yes, equals() would definitely be better and correct. In Java, a pool of string constants is maintained and reused intelligently for performance. So this can work, but it is only guaranteed if evt.getPropertyName() is assured to return constants.
Also, the more correct version would be "progress".equals(evt.getPropertyName()), in case evt.getPropertyName() is null. Note that the implementation of String.equals starts with using == as a first test before doing char-by-char comparison, so performance will not be much affected versus the original code.
Which demo are we looking at?
This explains equals() vs ==
http://www.java-samples.com/showtutorial.php?tutorialid=221
It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:
So in your particular example, it is comparing the reference to see if they are the same reference, not to see if the string chars match I believe.
The correct version of this code should be:
if ("progress".equals(evt.getPropertyName()))
This could work because of the way that the JVM handles string constants. Each string constant is intern()ed. So if evt.getPropertyName() is returning a reference to a string constant than using == will work. But it is bad form and in general it will not work.
This only would work if evt.getPropertyName() returns a constant string of value "progress".
With constant string, I mean evaluated at compile-time.
In most cases, when comparing Strings, using equals is best. However, if you know you'll be comparing the exact same String objects (not just two strings that have the same content), or if you're dealing entirely with constant Strings and you really care about performance, using == will be somewhat faster than using equals. You should normally use equals since you normally don't care about performance sufficiently to think about all the other prerequisites for using ==.
In this case, the author of the progress demo should probably have used equals - that code isn't especially performance-critical. However, in this particular case, the code will be dealing entirely with constant strings, so whilst it's probably not the best choice, especially for a demo, it is a valid choice.
I am trying to return a toString if something is true.
I have this code:
public void printoutsailings() {
for (Sailing s:sailings) {
String hamburg = ("Hamburg");
if ((s.getDeparturePort()) == hamburg) {
System.out.println(s.toStringAdjusted());
}
}
}
However I get nothing when I run the method (when I should be getting something). I assume that I have somehow messed up the logic or not understood =,== and eq properly, I'm not too sure.
There is nothing wrong with the toString or the for loop, and I'm not getting any compiler or run time errors. It's just that the logic is wrong.
If someone could put me right that'd be appreciated. Thanks.
You should be using .equals() instead of == to check String equality. Try the following:
if ((s.getDeparturePort()).equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
In short, == checks to see if two strings are the exact same reference, and .equals() checks to see if two strings look the same.
It should also be said that you need to use .equals() for checking the equality of any Object type, not just strings. Only primitive types (int, double, char) should use == for equality.
To compensate for the fact that the departure might be null, simply switch the condition around. It would read - hamburg.equals(s.getDeparturePort())
Yup, you're relying on == comparing for equality rather than identity. Change the code to:
if (s.getDeparturePort().equals("hamburg")) {
System.out.println(s.toStringAdjusted());
}
For reference types, == in Java always means "compare the two references for equality". In other words, it returns whether two references refer to the same object.
You want to check whether the two strings are equal instead - i.e. whether they contain the same sequence of characters. That's what the overridden equals method is for.
(To give a real-world demonstration of this, I catch a number 36 bus every morning. To me those buses are equal because they take me on the same route, but I know there are several number 36 buses - I don't get on the exact same physical bus every day.)
Note that the code above will throw a NullPointerException if s.getDeparturePort() returns null. There are two ways of avoiding this. First, you can use a known-to-be-non-null reference as the target of the method call:
if ("hamburg".equals(s.getDeparturePort()))
Alternatively, you can perform an explicit nullity check:
String port = s.getDeparturePort();
if (port != null && port.equals("hamburg"))
Or you can leave it to throw an exception, if that's the most appropriate behaviour (i.e. if you really don't expect getDeparturePort() to return null, and want to blow up if you get such bad data rather than continuing and possibly propagating the problem).
You must compare strings using equals method.
In Java, String is a reference type. It means that your String hamburg, pointing to a variable in the stack, contains a reference to a managed heap object actually containing the string. A value type, conversely, is completely allocated into the stack.
The ==, read reference equals compares the stack values. Instead, all classes implement an equals method that is read value compare. It compares the real values of the object wherever they are allocated in.
The following code works for you:
public void printoutsailings() {
for (Sailing s:sailings) {
String hamburg = ("Hamburg");
if (hamburg.equals(s.getDeparturePort())) { //First hamburg to prevent any possible NullPointerException
System.out.println(s.toStringAdjusted());
}
}
}
Just for your curiosity:
PHP only compares by value
C# redefines the == operator as a value equals operator, but only for the string class
In VB.NET, the default = operator is the value equals operator. The Is operator corresponds to the reference equals
In String, equality is checked either by equals() method or compareTo() method.
Your solution can be fixed by:
if (s.getDeparturePort().equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
To avoid receiving a null from s.getDeparturePort(), I would do the following.
if ("Hamburg".equals(s.getDeparturePort())) {
System.out.println(s.toStringAdjusted());
}
This is to avoid NullPointerException if s.getDeparturePort() is null (from your example code).
Alternatively, you can use the compareTo() method like so....
Your changed code (to using compareTo():
if (s.getDeparturePort().compareTo(hamburg) == 0) {
System.out.println(s.toStringAdjusted());
}
My alternate solution (using compareTo())
if ("Hamburg".compareTo(s.getDeparturePort()) == 0) { //Zero means that it is equal.
System.out.println(s.toStringAdjusted());
}
Btw...
String hamburg = ("Hamburg");
can be easily written as
String hamburg = "Hamburg";
if(hamburg.equals(s.getDeparturePort()))
Try
public void printoutsailings() {
for (Sailing s:sailings) {
String hamburg = "Hamburg";
if (s.getDeparturePort().equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
}
}
== is comparing the object itself, you're better off using .equals() as it will compare the actual value of the String, such as :
if ((s.equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
Also make sure that Sailings has at least 1 value, otherwise you'll never enter that for loop anyway
Instead of simply providing the code...check this out, I am almost certain it will get you to where you need to go...
try if (s.getDeparturePort().equals(hamburg))
Instead of using == for String objects (or any objects), use .compareTo(), as in this example:
http://leepoint.net/notes-java/data/strings/12stringcomparison.html