This question already has answers here:
Interview : Java Equals
(7 answers)
Closed 8 years ago.
Is there a performance impact, assuming str is a java.lang.String, of using "String".equals(str) vs str.equals("String")? My gut says, "No, the JVM / compiler will optimize the literal string in either case", but I see the first style crop up enough in various codebases and it just looks so unnatural (at least to me), so I figured there must be a reason besides style.
The only reason for using "String".equals(str) (which I find ugly) is laziness, as it saves you the need to check that str != null prior to calling str.equals("String").
Performance-wise there shouldn't be any difference. You are comparing two String instances either way.
"String".equals(str)
Does not yield the same result as
str.equals("String")
if str == null.
In the first case, it returns false, in the second, it throws a NullPointerException.
"String".equals(str)
Is in fact equivalent to
str != null && str.equals("String")
Related
This question already has answers here:
How to write a ternary operator (aka if) expression without repeating yourself
(17 answers)
Is using Optional.ofNullable as a replacement for the ternary operator a good practice?
(6 answers)
Avoid violation of DRY with ternary?
(2 answers)
Closed 2 years ago.
I'm fairly new to Java and I'm trying to check if a variable is null and use its value if its not. Previous developer wrote something like this:
xModel.setName(xService.getName(xID) != null ? xService.getName(xID) : "");
And I would like to refactor it so I wouldn't have to use xService twice to just get the name.
I know I can store the value beforehand but this is just an example. I just wonder if there is a way to do this in Java?
Thanks.
I disagree with all other answers. They require special functionality from specific versions by importing structures from the standard library, or obscure calls that works in this specific case, and all in all just hides the simplicity of what you're trying to do.
Keep it simple (KISS). Don't introduce more complexity and concepts when you don't need them. You're refactoring another developers code, which means this is a project where someone else will probably be reading your code later on. So keep it dead simple.
String name = xService.getName(xID);
xModel.setName(name != null ? name : "");
This is more readable than all other examples and doesn't require intimate knowledge of the standard library and its API.
Objects.toString​( Object o, String nullDefault )
In this particular case you can use java.util.Objects.toString. Second argument is a default value to use in case of a null in the first argument.
xModel.setName(Objects.toString(xService.getName(x.ID), ""));
What you have is already the best core Java can do pre Java 8. From 8 onwards, you may use optionals:
xModel.setName(Optional.ofNullable(xService.getName(xID)).orElse(""));
This question already has answers here:
String valueOf vs concatenation with empty string
(10 answers)
Closed 7 years ago.
I've had a few people tell me that things like this are super lazy:
int val = 5;
System.out.println("" + val);
String myStr = "" + val;
Why is this better than String.valueOf(val)? Isn't it doing the exact same thing under the hood?
It's not really "better", just shorter, making it easier to read and type. There is (virtually) no ther difference, even though a real purist might, probably, say, this is actually worse, because (at least, in the absence of optimization), this creates an intermediate StringBuilder object, that is then appended a character before being converted into a String, so, this may be spending more ticks, than .valueOf.
From JLS:
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I know that Strings in Java should be compared using .equals() and not using == operator.
But in the given below code there is a primaryObserverId which has a value of ""
The given below if condition runs fine on Java 6 but fails on Java 7
String primaryObserverId = request.getParameter("primary_observer_id");
if(primaryObserverId == null || primaryObserverId=="")
primaryObserverId = RoleMap.getUserIdForThisSession(session.getId());
Need to know why this code was working on Java 6 and not on Java 7.
I know how the concept of String Pool works for string literals in java , just want to know the reason this abrupt behavior.
Can using different version of GlassFish may cause any issue as I am using GlassFish-2.1 with Java 6 and GlassFish-4.1 with Java 7
All string literals in java are placed in a special area of the heap as they are required. So if you have a variable that is initialised to an empty string, this string is added to the heap. If you have another variable that is initialised to an empty string then it will contain a reference to the empty string already on the heap rather than creating a new one. So it seems your problem is that when you run your application in java 6 for some reason an empty string is on the heap at that point so you can check that the two strings are exactly the same object. However when run in java 7 there is no empty string on the heap so the two string must be completely different objects.
See this article for a more complete explanation.
== compares the address in memory while equals() compares if 2 objects are meaningfully equivalent, so in your case it makes more sense to user the equals() method as the Servlet creates the String not using the pool, so they are not == but they are meaningfully equivalent, therefore equals.
String primaryObserverId = request.getParameter("primary_observer_id");
if(primaryObserverId == null || "".equals(primaryObserverId)){
primaryObserverId = RoleMap.getUserIdForThisSession(session.getId());
}
This question already has answers here:
How does the String class override the + operator?
(7 answers)
Closed 9 years ago.
Can any one tell me the exact implementation of '+' operator of String in Java.
As I know this is concat operator to concat two string even then since String is a class then where is implementation of this operator and how it works?
The implementation is compiler-specific, although it usually just ends up creating a StringBuffer or StringBuilder behind the scenes, and appends to it. Note that it has special treatment for efficiency, so that x + y + z can be compiled as something like
new StringBuilder().append(x).append(y).append(z).toString();
... and also to perform compile-time concatenation of constant string expressions.
You can see the operator described in JLS section 15.18.1, but that doesn't mandate any particular implementation.
To see what your particular compiler does, simply compile some code you're interested in and then use javap -c to look at the bytecode it generates.
String + may be optimised away by the compiler. If it is not it is the same as
a + b
becomes on most JVMs today (older versions used StringBuffer)
new StringBuilder().append(a).append(b).toString();
So StringBuilder.append() is what you want.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If statement using == gives unexpected result
Hi I'm using this code to add elements to my ComboBox, and I do not want to add empty elements, here's the code:
public void elrendezesBetoltes(ArrayList<Elrendezes> ElrLista){
int i;
Elrendezes tmp;
model.removeAllElements();
model = new DefaultComboBoxModel(comboBoxItems);
for(i=0; i<ElrLista.size(); i++){
tmp = ElrLista.get(i);
if(tmp.getName()!="")comboBoxItems.add(tmp.getName()); //not working
addButton2(tmp.getSeatnum(),tmp.getCoord(),tmp.getFoglalt());
}
}
My problem is that the if statement is not working, it still adds empty names to my combobox. What am I doing wrong?
Always use equals method to compare Strings: -
if (tmp.getName()!="")
should be: -
if (!tmp.getName().equals(""))
or simply use this, if you want to check for empty string: -
if (!tmp.getName().isEmpty()) {
comboBoxItems.add(tmp.getName());
}
Use equals method to compare string. By using != operator, you are comparing the string instances, which is always going the be true as they(tmp.getName() and "") are not same string instances.
Change
tmp.getName()!=""
to
!"".equals(tmp.getName())
Putting "" as first string in comparison will take care of your null scenario as well i.e. it will not break if tmp.getName() is null.
Use equals():
if (!tmp.getName().equals(""))
Using == or != compares string references, not string contents. This is almost never what you want.
you have to compare Strings with "equals", then it will work
if(!tmp.getName().equals(""))comboBoxItems.add(tmp.getName())
you are comparing for identity (==, !=) but each String instance has its own identity, even when they are equal.
So you need to do !tmp.getName().equals("").
Generally it is considered best practice to start with the constant string first, because it will never be null: !"".equals(tmp.getName())
However, I would recommend to use apache commons lang StringUtils. It has a notEmpty() and notBlank() method that take care of null handling and also trimming.
PS: sometimes identity will work for Strings. but it should not be relied upon as it is caused by compiler or jvm optimization due to String immutability.
Use String#isEmpty()
if(!tmp.getName().isEmpty())
OR:
if(!tmp.getName().equals(""))
Always, check String equality with equals method. == operator only checks if two references point to the same String object.
Another alternative if not on Java 6 and isEmpty is unavailable is this:
if (tmp.getName.length()>0)
Checking for the length is supposed to be quicker than using .equals although tbh the potential gain is so small its not worth worrying too much about.