How to remove the null after concatenation of two strings.
Ex:
String a = null;
String b = Hello;
a+=b;
System.out.println(a);// output is nullhello
here, i need output as only hello,
Thanks in advance.
You can use this
String a = null;
String b = "Hello";
a = ((a==null) ? "": a) + b;
System.out.println(a);
The Java designers thought it a good idea to treat the compound assignment by sum operator += when applied to a null lvalue java.lang.String reference as a special case by injecting a (rather arbitrary) textual stringification of nullness.
(I see it as a manifest act of utter madness: an alternative would include throwing a NullPointerException as would happen if += is applied to a numeric boxed type such as java.lang.Integer.)
If you don't want this behaviour then you need to program specifically to obviate it.
You can use custom method for this, this is one line of code:
public static String concat(String a, String b) {
return a == null ? b : b == null ? a : a + b;
}
It might be a bit of overhead, but you can use Objects.toString method:
String a = null;
String b = Hello;
System.out.println(Objects.toString(a,"").concat(Objects.toString(b,"")));
public static String toString(Object o,
String nullDefault)
Returns the result of calling toString on the first argument if the
first argument is not null and returns the second argument otherwise.
This will handle all the possible cases {(a == null, b!= null),(a != null, b == null),(a == null, b == null),(a != null, b!= null)}
other alternative will be using Optional
System.out.println(
Optional.ofNullable(a).orElse("")
.concat(Optional.ofNullable(b).orElse(""))
);
public T orElse(T other)
Return the value if present, otherwise return other.
This will be identical to the first solution. Both of this solutions has one common disadvantage: code needs to be duplicated for every additional variable. For example if now we need to concatenate 3 variables a,b and c. We will have to just copy and paste same code for c.
In this case we can use Streams
System.out.println(
Stream.of(a,b)
.filter(Objects::nonNull)
.collect(Collectors.joining())
);
It will create a stream consisting of strings a and b; will filter out all strings which are null and finally collect all remaining strings using empty delimiter. In case if there are more then 2 variables we will just add them to initial stream.
I hope you will find this helpful.
You may use Google's Guava library to get rid of null before concatenation.
String a = Strings.nullToEmpty(null);
String b = Strings.nullToEmpty("Hello");
a+=b;
System.out.println(a);// output is hello
It makes the code more explicit about the fact that you don't want null, IMO it's more readable as than a ternary expression.
Related
This is an extremely basic question but why is the following code returning a null pointer exception?
String a = null;
String b = null;
System.out.println(a.equals(b));
According to the docs here:
http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)
the .equals() function is first checking for null before comparing values. Shouldn't it return true since they are both null?
The method you linked to takes in two objects and is a static method. You need to call it like Objects.equals(a, b). Instead you are calling .equals() on a null object which throws NPE
Shouldn't it return true since they are both null?
nop. since a is a null-referenced object, invoking ANY instance method on that object will throw a NPE
so what you can do:
if you are still on java 6 do
System.out.println(a == null ? b == null : a.equals(b));
and since java 7
System.out.println(Objects.equals(a, b));
I usually write following method,
private boolean equalsWithNull(String first, String second){
return ((first!=null&&second!=null && first.equals(second)) || (first==null && second==null));
}
Objects::equals is the best option, but you can use
Optional.ofNullable(a).equals(Optional.ofNullable(b))
as well. However I don't really see any cases when you will choose Optional approach instead of Objects
you can check both values instead of reference,
String a = null;
String b = null;
System.out.println(a == b ? "true":"false");
it returns true.
Converting the value to String in java; There are multiple ways of doing it.
Just wanted to know what's the difference between each other in the following ways.
strValue.toString()
strValue+""
""+strValue
It depends on java version. Java 7 would act a bit smarter using StringBuilder + append().
Generally, you do not want unnecessary allocations. Use first one.
strValue.toString()
will return itself, because the toString() implementation of String (I'm guessing strValue is indeed of type String) returns this.
strValue+""
""+strValue
Will result in the same value (strValue) but won't invoke the toString() method
All Strings contain the same value, try it out:
String strValue = "Hello world"; // not null
String a = strValue.toString();
String b = strValue+"";
String c = ""+strValue;
Measuring its length give all the result 11, because adding an empty String to another one equals the original String itself:
System.out.println(a.length());
...
Try the equality between these Strings:
System.out.println(a.equals(b));
System.out.println(b.equals(c));
System.out.println(c.equals(a));
They are all true, because these Strings have the same value to be compared. All it in the case the strValue is not null.
One major difference is how null is handled.
If strValue is null, strValue.toString() will throw a NullPointerException, while the other two options will return the String "null".
Other differences may be observed if strValue is of a boxed numeric type, and you try to concatenate other numeric variables to it.
For example :
If
Integer a = 5;
Integer strValue = 6;
Then
a+strValue+""
would return
"11"
while
a+""+strValue
or
""+a+strValue
would return
"56"
Map<String,Integer> m;
m = new TreeMap<String,Integer>();
Is it good practice to add the following cast just to avoid the null pointer exception when m.get() is null.
System.out.println( ((Integer) 8).equals( m.get("null") ) ); // returns false
Alternatively with a prior null check it starts to look a bit ugly.
System.out.println( m.contains("null") != null && m.get("null").equals( 8 ) );
Is there a better way to write this? Thanks.
The == operator doesn't compare values, but references.
You should use the .equals() method, instead, applied to the Integer variable (for which you are sure that is not null and NPE won't be thrown):
Integer eight = 8; //autoboxed
System.out.println(eight.equals(m.get("null")));
This will print false even the m.get("null") returns null.
No, because it will not work. You can't compare two Integer with ==, as that compares references and not the integer values. See more info in this question
You'll need a helper method, such as:
boolean safeIntegerCompare(Integer a, int b)
{
if (a != null)
return a.intValue() == b;
return false;
}
I try to avoid casts whenever possible, so I'd rather use the following, which also looks nicer in my opinion:
Integer.valueOf(8).equals(m.get("null"))
If only one of the arguments may be null (as is the case when you're comparing an unknown value to a constant), use equals() like this:
Integer foo = Integer.valueOf(8); // you could write Integer foo = 8; here too but I prefer to avoid autoboxing
if (foo.equals(m.get("x"))) { //will never throw an NPE because foo is never null
...
}
Note that your example isn't going to work in general because comparing non-primitive values with == only returns true if they refer to the same object instance. (Which in this case might even be true for very specific reasons but most of the time it isn't.)
To expand the accepted answer: i find myself having to check the equality of 2 Integer variables which might or might not be null.
So my solution would be:
boolean equals =
Optional.ofNullable(objectA.getNullableInteger()).equals(Optional.ofNullable(objectB.getNullableInteger());
You can use Objects.equals
int foo = 1;
Integer bar = null;
Objects.equals(foo, bar);
I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate.
I tried all this but that didn't work.
String COMPLETEDATE;
COMPLETEDATE = country[23];
if(country[23] == null && country[23].length() == 0)
{
// ...
}
if (COMPLETEDATE.equals("null"))
{
// ...
}
if(COMPLETEDATE== null)
{
// ...
}
if(COMPLETEDATE == null || COMPLETEDATE.equals("null"))
{
// ...
}
For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:
if("constantString".equals(COMPLETEDDATE)) {
// logic
}
But in general, your approach isn't correct.
The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.
The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.
Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.
Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".
To check null string you can use Optional in Java 8 as below:
import Optional
import java.util.Optional;
import it as above
String str= null;
Optional<String> str2 = Optional.ofNullable(str);
then use isPresent() , it will return false if str2 contains NULL otherwise true
if(str2.isPresent())
{
//If No NULL
}
else
{
//If NULL
}
reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
It is not entirely clear what you are asking, but to check if a String variable is null, use the following statement.
if(myString==null)
This checks whether the object reference is null.
The following statement, which you have written is incorrect for two reasons.
if (COMPLETEDATE.equals("null"))
{
// ...
}
1. null is a keyword in Java, "null" is just a string of text.
2. .equals() checks to see if two objects are equal according to the given method's definition of equality. Null checks should always be made using the == comparison operator, as it checks reference equality.
If a variable is null, you cannot dereference it.
That means you can not invoke methods on it.
So... The following if statement will throw a NullPointerException every time the first clause is true:
if (a == null && a.length() == 0)
In other words: if a is null, you CANNOT invoke the length method on a.
I have the following situation. I have a HashMap in Java with keys as strings.
Then in some stage , in runtime I create strings equal to those keys in order to retrieve the data from that map.The strings are created as follows within "for" loop:
String keyToRetrive = "lights[" + Integer.toString(i) + "]" + ".Intensity";
The strange thing about it that when I iterate through the map to find the key that equals that string ,even when the match is found the search steps over.So in this search loop :
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
if (name == entry.getKey()) { ///name- "lights[0].Intesity"
uniformOut = (ICleanable) entry.getValue();
break;
}
}
The key with the name "lights[0].Intesity" never returns true even that the map contains one.How I solved it .I used hashCode() for both compared string values.So this version does work:
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
if (name.hashCode() == entry.getKey().hashCode()) {
uniformOut = (ICleanable) entry.getValue();
break;
}
}
UPDATE: After being pointed to the fact that "==" doesn't work good and "equals()" should be used I would like to narrow the question:Why "==" does work for strings which were not created from several concatenated blocks? I mean, if I defines key string to compare agains as a simple single string:
String foo="foo";
Such a string is compared using "==" against HashMap key all right.
I am not an expert Java programmer so can anybody explain why it works this way?
You are comparing Strings using == operator. Use equals() instead:
name.equals(entry.getKey())
This is a common pitfall in Java, see How do I compare strings in Java? and Difference between Equals/equals and == operator?.
BTW (unrelated to your problem) when concatenating strings you don't need to call toString() explicitly so this:
"lights[" + Integer.toString(i) + "]" + ".Intensity"
can be replaced with:
"lights[" + i + "]" + ".Intensity"
It'll work for i of any type, not only int.
When you compare objects using ==, you're performing a "referential equality" comparison, meaning that you're checking whether the two references point at the same String object in memory. If you're familiar with C, it would be like:
char* a = some_string();
char* b = some_other_string();
if (a == b) { ... }
On the other hand, when you compare objects using .equals(), you're performing a "structural equality" comparison, meaning that you're checking whether the two objects contain equivalent data. Again, the C analog of this would be:
char* a = some_string();
char* b = some_other_string();
if (strcmp(a, b) == 0) { ... }
Now, the thing you really, really don't want to do is to compare the two objects' hash codes. Why not? Because two objects with the same hash code are not necessarily equal! They might be, but you can't correctly rely on it.
Update: You also asked about why == works for string literals. The answer is because the Java compiler doesn't allocate constant strings on the heap; instead it stores them in the constant pool of the class in which they're used. So, if you write:
String foo1 = "foo";
String foo2 = "foo";
Then the compiler will have both references point at the same location in the class's constant pool. If, however, you write:
String foobar1 = "foobar";
String foobar2 = "foo" + bar();
String bar() { return "bar"; }
The compiler isn't quite smart enough to figure out that foobar2 is logically equivalent to foobar1. However, even if you know that the two variables are compile-time constants, you still should keep it simple and use .equals().
The others have stated why your code won't work, however:
1) If you're using a HashMap, you should use map.get(key) to retreive the value, not an interator of entries; that's the whole point of the Hash Map.
2) Use generics, avoid explicitly casting as much as you can!