Posts

Showing posts from January, 2016

StackOverflow Q&A you should read if you program in Java

Overview There are common questions which come up repeatedly in Java.  Even if you know the answer it is worth getting a more thorough understanding of what is happening in these cases. How do I compare Strings? The more general questions is how do I compare the contents of an Object.  What is surprising when you use Java for the first time is that if you have a variable like String str this is a reference to an object, not the object itself.  This means when you use == you are only comparing references. Java has no syntactic sugar to hide this fact so == only compares references, not the contents of references. If you are in any doubt, Java only has primitives and references for data types up to Java 9 (in Java 10 it might value value types) The only other type is void which is only used as a return type. Is Java Pass by Reference or Pass by Value? How do I compare Strings? Why does 128 == 128 return false but 127 == 127 return true? How do I avoid lots of !