Java - Check Not Null/Empty else assign default value

Java - Check Not Null/Empty else assign default value

To check if a Java variable is not null or not empty (in the case of strings or collections) and assign a default value if it is null or empty, you can use conditional statements. Here are some examples for different scenarios:

  • Check and assign a default value for a nullable object:
YourObject someObject = ...; // Assign your object here YourObject defaultValue = new YourObject(); // Default value if (someObject != null) { // Use the non-null value of someObject } else { // Use the default value someObject = defaultValue; } 
  • Check and assign a default value for a nullable string:
String someString = ...; // Assign your string here String defaultValue = "Default Value"; // Default value if (someString != null && !someString.isEmpty()) { // Use the non-null and non-empty value of someString } else { // Use the default value someString = defaultValue; } 
  • Check and assign a default value for a collection (e.g., ArrayList):
List<YourType> someList = ...; // Assign your list here List<YourType> defaultValue = new ArrayList<>(); // Default value (empty list) if (someList != null && !someList.isEmpty()) { // Use the non-null and non-empty list } else { // Use the default value (empty list) someList = defaultValue; } 

In these examples, we first check if the variable is not null (for objects) and not empty (for strings or collections). If it passes the check, we use the non-null or non-empty value; otherwise, we assign the default value.

Make sure to replace YourObject and YourType with the actual data types you are working with.


More Tags

bluetooth-printing transfer aapt multipart bigdecimal default-value git-merge embedded-resource watson-assistant latex

More Java Questions

More Weather Calculators

More Trees & Forestry Calculators

More Other animals Calculators

More Chemical thermodynamics Calculators