Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace from null value empty string in java? [closed]

Tags:

java

I'm getting the null values from DB, but I need to display the empty string "" instead.


For example, I have to append four values to display in the single cell of a Excel sheet like below:

sheet.addCell(new Label(4, currentRow, a.getPar()+" "+a.getO()+" "+a.getPar()));


How to achieve the expected result (the replacement) in Java?

like image 410
user2408111 Avatar asked May 28 '13 13:05

user2408111


People also ask

How do you replace a null in a string in Java?

String str=null; String str2= str. replace('l','o'); System. out. println(str2);

How do you handle empty and null string in Java?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.

How do you replace a character in a string with an empty string in Java?

If you just exchange single for double quotes, this will work because an empty string is a legal value, as opposed to an "empty character", and there's an overload replace(CharSequence, CharSequence) . Keep in mind that CharSequence is the supertype of String .

How do I replace a null in a string?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.


2 Answers

If I understand correctly, you can use the ternary opperator:

System.out.println("My string is: " + ((string == null) ? "" : string));

In case you are not familiar with it, it reads "Is string null? If it is, then 'return' en empty string, else 'return' string". I say 'return' because you can consider ((string == null) ? "" : string) as a function that returns a String.

You can replace the empty string with any other String of course.

like image 74
Djon Avatar answered Sep 28 '22 19:09

Djon


If I understand correctly, you need this

public static String replaceNull(String input) {
  return input == null ? "" : input;
}

and the use it where ever you need it like

sheet.addCell(new Label(4,currentRow, replaceNull(a.getParan())+" "+replaceNull(a.getO())+" "+replaceNull(a.getParan())));

Hope this helps

like image 38
rahul maindargi Avatar answered Sep 28 '22 19:09

rahul maindargi