Does Java have Identical Comparison Operator example === - java

Java is a Strong Static Casting so does that mean there is no use for "==="
I have looked at tons of documentation and have not seen Identical Comparison Operator.

=== is useful in weak typed languages, such as Javascript, because it verifies that the objects being compared are of the same type and avoids implicit conversions.
=== has absolutely no use in a strongly typed language such as Java because you can't compare variables of different types without writing a specific method for doing this.
For example, if you want to compare an int to a String in Java, you will have to write some special method as such:
boolean compareIntString(int i, String s) {
return (i == parseInt(s));
}
But this is pretty much overkill. (And as you'll notice, as written, this method only accepts an int and a String. It doesn't accept just any two variables. You know before you call it that the datatypes are different.)
The main point is, that while you can do i == s in Javascript, you can't do i == s in Java, so you don't need ===.
I guess, the short answer is that Java's == is Javascript's ===. If you want to emulate Javascript's == and compare two items, ignoring data type, you'll have to write a custom method which accepts generic data types as arguments... and figure out the logic on comparing, at a minimum, all the possible combinations of Java's primitive data types...

No java does not have === operator. Reason is pretty well explained by nhgrif. Here is the list of operators in java and their precedence:
Source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Related

Java There's any use on a simple "isNull"/"isNotNull" function?

I'm feeling quite silly for asking this question, but I've already seen this code on two separate corporate codebases and I'm starting to think there's some chunk of ancient java knowledge I'm not aware of.
So, we got this kind of code:
/* Lot of corporate stuff */
if (ClassicUtilsClass.isNotNull(variable)) {
/* Variable handling shenanigans. */
}
Going to our ClassicUtilsClass revealed the implementation of the function:
/* Lot of useful static functions*/
public static isNotNull(Object o) {
return o!=null;
}
public static isNull(Object o) {
return o==null;
}
I read it, scratched my head, looked around the internet, asked colleagues and friends, then laugh at the uselessness of the function. Then I switched jobs and a colleague showed me more or less the same code.
In the same codebase we have the classic "isNullOrEmpty" which does the standard "return object==null || object.size() == 0;", so I can understand having a function to wrap the null comparison... plus something else, but I don't see the point of creating a whole new function for null checking.
I'm losing something here?
There are similar functions in the Objects utility class, called nonNull and isNull. The reason they are provided is to be used as predicates, e.g.
...stream().filter(Objects::nonNull)...
I can't see any reason to use
if (SomeClass.isNotNull(x))
rather than the shorter, clearer
if (x!=null)
There are only a few reasons to implement operators as methods that I can think of.
The first reason is to "profile" how many times the operation is used in an application. Profiling tools count the time spent in methods and the number of times methods are called but they don't track operator usage.
The second reason to implement operators as functions is to use them in functional programming constructs. Operators cannot be passed around using reflection, but methods can, so it is possible to create functional operations (map, reduce, etc) that use reflection and in those cases operators would need to be implemented as methods to be utilized.
A third possible reason to implement the not null operator as a method is to simplify the automated translation of some other programming languages into java. In java primitive types cannot be null so checking if they are null directly using the == operator would cause a compiler error. Java will autobox primitives into objects so they can be used as arguments to methods which accept Object as their argument type. In this case a code translator could translate null checks to method calls without needing to track the variable type.
Maybe the reason could be that in some tests it can be useful to mock ClassicUtilsClass.isNotNull and ClassicUtilsClass.isNull methods to return true or false.
Anyway as you I can't see the point. Different would be a StringUtils.isEmpty by Apache Commons, which returns true if the string is null or equal to ""

What is operator overloading and is it different from Polymorphism?

I program in Java and have been trying to understand exactly what operator overloading is. I'm still a bit puzzled.
An operator can take on different meanings depending on which class uses it? I've read that it is "Name Polymorphism".
Java apparently does not support it and there seems to be a lot of controversy around this. Should I worry about this?
As a last question, in an assignment the teacher has stated that the assignment uses operator overloading, he is a C++ programmer mainly but we are allowed to write the assignment in Java. since Java does not support overloading, is there something I should be wary of?
Operator overloading basically means to use the same operator for different data types. And get different but similar behaviour because of this.
Java indeed doesn't support this but any situation where something like this could be useful, you can easily work around it in Java.
The only overloaded operator in Java is the arithmetic + operator. When used with numbers (int, long, double etc.), it adds them, just as you would expect. When used with String objects, it concatenates them. For example:
String a = "This is ";
String b = " a String";
String c = a + b;
System.out.print (c);
This would print the following on the screen: This is a String.
This is the only situation in Java in which you can talk about operator overloading.
Regarding your assignment: if the requirement is to do something that involves operator overloading, you can't do this in Java. Ask your teacher exactly what language you are allowed to use for this particular assignment. You will most likely need to do it in C++.
PS: In case of Integer, Long, Double etc. objects, it would also work because of unboxing.
Java doesn't allow overloading operators. It uses a very limited kind of operator overloading though, since + does addition or concatenation depending on the context.
If your assignment asks you to implement something by overloading operators, you won't be able to do it in Java. Maybe you should ask the teacher why he allows Java for such an assignment.
If your assignment only asks you to use an overloaded operator, then having your program use + for concatenation and addition would fit the bill. But I would ask the teacher, because I doubt that it's what he expects.
Java apparently does not support it and there seems to be a lot of
controversy around this.
There is no controversy about this. Some people might disagree with the decision, but James Gosling and others decided from day one to leave operator overloading by class developers out of the language. It's not likely to change.
As pointed out by others here, they reserved the right for the JVM to overload operators on a limited basis. The point is that you can't do it when you're developing your own classes.
They did it because there were examples of C++ developers abusing the capability (e.g. overloading the dot operator.)
Should I worry about this?
No. Java won't explode. You just won't be able to do it for your classes. If you feel like you need to, you'll just have to write C++ or some other language.
As to your query about the difference between operator overloading and polymorphism. Polymorphism is a standard OOP concept where an instance of a class may exhibit different characteristics depending on the underlying type. For example in C++:
class Shape {
...
virtual void draw()=0;
}
class Circle :public Shape {
virtual void draw() {...draw a circle...}
}
class Square:public Shape {
virtual void draw() {...draw a square...}
}
..
Shape *s = new Circle();
s->draw(); // calls Circle::draw();
s=new Square(); // calls Square::draw();
Hence s is exhibiting polymorphism.
This is different from operator overloading but you already have been explained what that is in the other answers.
Can either use natural a != b (a is not equal to b) or a.Equals(b)
b.set(1, 0);
a = b;
b.set(2, 0);
assert( !a.Equals(b) );
But java has a limited set of operator overloading than other languages http://en.wikipedia.org/wiki/Operator_overloading

I don't understand this ("string" == "string") example

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.

Scala, Java and equality

val filesHere = (new java.io.File(".")).listFiles
val filesHere2 = (new java.io.File(".")).listFiles
scala> filesHere == filesHere2
res0: Boolean = false
That is quite counter intuitive. I would rather expect that filesHere and filesHere2 are equal.
This is certainly due to a semantics mismatch between Java and Scala, e.g., about arrays or (files) equality. Clearly, I am missing something here!
If I ruled the world, I would deprecate Scala's eq method on the grounds that the name is extremely confusible with equals and ==. Instead English does have a word which expresses identity as opposed to equality: I would simply call it is .
Similarly I would replace Scala's ne (which is a terrible name, since it's both an abbreviation and incomprehensible) with isnt .
Seems to me these could actually be added to AnyRef and the old methods deprecated, even at this late stage.
The equals() method of Java arrays uses reference equality rather than anything more sophisticated, and Scala's == is simply Java's equals().
The comparison doesn't work as expected, because this Java API returns an Array.
Scala's arrays and Java arrays are the same behind the scenes and although Scala's array looks like a class it is just a java.io.File[] (in this example).
This is the reason why the check for equality can't be overridden. Scala has to use Java semantics for it.
Consider this example:
val filesHere = (new java.io.File(".")).listFiles.toList
val filesHere2 = (new java.io.File(".")).listFiles.toList
This would work as expected.
You may want to read through here:
http://ofps.oreilly.com/titles/9780596155957/AdvancedObjectOrientedProgramming.html#EqualityOfObjects
but it appears that if you did:
filesHere.sameElements(filesHere2) that it should be true.
The javadoc for this is here:
http://www.scala-lang.org/api/2.6.0/scala/IterableProxy.html#sameElements%28Iterable%5BB%5D%29
UPDATE:
A couple of snippets from the first link that may be helpful:
In Java, C++, and C# the == operator tests for reference, not value equality. In contrast, Ruby’s == operator tests for value equality. Whatever language you’re used to, make sure to remember that in Scala, == is testing for value equality.
In reference to == not working as expected on Lists:
While this may seem like an inconsistency, encouraging an explicit test of the equality of two mutable data structures is a conservative approach on the part of the language designers. In the long run, it should save you from unexpected results in your conditionals.
UPDATE 2:
Based on comments from Raphael I looked at the specification, and it was dated two days ago for the most recent update, and I see these at http://www.scala-lang.org/files/archive/nightly/pdfs/ScalaReference.pdf:
Method equals: (Any)Boolean is structural equality, where two instances
are equal if they both belong to the case class in question and they have equal
(with respect to equals) constructor arguments.
class AnyRef extends Any {
def equals(that: Any): Boolean = this eq that
final def eq(that: AnyRef): Boolean = . . . // reference equality
So, it appears that the definition hasn't changed in Scala 2.10.2, as the specification seems to be consistent. If the behavior is different, then if you write a unit test it should be sent as a bug for Scala.

Efficient way to convert unknown objects to appropriate Method.invoke arguments?

I'm writing a reflection-based RPC service that gets arguments passed in via a variety of mechanisms. Sometimes the arguments correctly match the parameter type, sometimes they're always strings, and sometimes they're wrapped up in dynamically typed "scripty" objects that need the appropriate value extracted out.
Before I can call method.invoke, I need to build the argument list, something like this:
Object a[] = new Object[method.parameterClasses.length];
for (int i = 0; i < a.length; ++i)
{
a[i] = prepare(method.parameterClasses[i], rpc.arguments[i]);
}
The "prepare" method looks something like:
Object prepare(Class clazz, Object o)
{
if (o == null) return null;
if (clazz == o.getClass()) return o;
if (clazz == String.class) return o.toString();
// skip a bunch of stuff for converting strings to dates and whatnot
// skip a bunch of stuff for converting dynamic types
// final attempts:
try
{
return clazz.cast(o);
}
catch (Exception e)
{
return o; // I give up. Try the invoke and hope for the best!
}
}
During unit testing, I was recently rather surprised to discover that a method passed a boxed Integer that expected a primitive long was actually failing the cast and falling through the bottom, and then being properly converted by something during the invoke(). I'd assumed the call to "cast" would do the trick. Is there any way to explicitly perform and check the argument conversion done normally by invoke?
Lacking that, I thought about putting in explicit checks for numeric types, but the number of permutations seemed out of hand. When I add support for extracting numbers from the script dynamic types and converting strings, it gets even worse. I envision a bunch of conditional typechecks for each possible numeric target class, with Integer.decode, Long.decode etc for the String arguments, Short.decode, and Number.intValue, Number.longValue, etc. for Numbers.
Is there any better way to do this whole thing? It seemed like a good approach at first, but it's getting pretty yucky.
It is indeed surprising, but that is the current behavior. See bug 6456930.
In terms of a better way to approach the problem, at its core, no you will have to define all of those rules. There are better (more maintainable) patterns that a series of if's, though. For starters, I'd have some strategy objects that can be invoked for one side of those objects (probably the class side) so that you look up the appropriate object (say from a Map) based on the class, and then you can limit your conversions to one side (each object would be concerned about how to get things into that particular class). That way when there is a new kind of class conversion that you need to support, you can write an object for it, test it separately and just plug it into the map without changing further code.
There's really not a better way. There are an infinite number of potential conversions, but only a tiny number that really make sense. Rather than trying to give clients complete freedom, I recommend specifying a contract for type coercion.
As a starting point, check out the type conversion rules used by the JSP Expression Language. They are quite powerful, and allow many types of conversions to take place, but they are also well-defined, easy to remember—and possible to implement.
There are at least a few shortcuts you can take to simplify your code:
If the parameter is an instance of java.lang.Number and the argument type is either byte, short, int, long, float or double (either as primitive, or as wrapper class), you can use the methods in Number like byteValue(), shortValue(), etc to convert the parameter.
If the parameter is an instance of java.lang.String and the argument type is one of the above mentioned, you can use the static valueOf(String) method in the respective class for conversion.
Converting further, and perhaps even proprietary types would of course need more work. If it's really necessary and your prepare method is getting to large, you should perhaps consider abstracting the conversion behind an interface and allowing pluggable conversion providers to be dynamically added to the application?

Categories

Resources