I'm trying to check if a form field is empty in java. I search a lot, But I only found it in javascript.
The problem is I want to check it in my Controller.
How can I do this?
Regards.
Thank you.
You can check parameter by HttpServletRequest :
String p = req.getParameter("p");
if(p==null){
System.out.println("parameter p is empty");
}
If you are testing it in your controller:
if(request.getParameter().trim().compareTo("") == 0){ // Do what you want
If you are testing it in your page, simply try this:
if(field.text.toString().trim().compareTo("") == 0){ //Do what you want
With Java 6 you can test an empty String :
if(null == myString || myString.trim().isEmpty() { .. ;}
EDIT to add trim() for blank removing
Checking empty filed you have to check null and empty string.
if(str == null && str.equals(""){}
Related
This question already has answers here:
How can I check if a single character appears in a string?
(16 answers)
Closed 4 years ago.
Basically, I have a form where people can enter stuff in, and there is one part where they input an email address. Sometimes, people just put in their name and don't put an actual email address. Sometimes they do not fill it out at all.
Is there any easy way to check to see if the string has an # symbol in it and check to see if its Null?
Any help is appreciated
Use an AND boolean operator. str != null && str.contains("#")
We first check the string is not null, then check that it contains '#'. Note: The reason that the null check is first is so that we do not attempt to access the string if it is null.
String s = "email#email.it";
if(s!= null && !s.isEmpty() && s.contains("#") ) {
System.out.println("ok");
}
else System.out.println("ko");
}
The String class contains a contains method to check the # symbol, and you can simply check for null with a != null call:
public static void main(String[] args) {
String a = "should be false";
String b = "should be #true";
String c = null;
System.out.println(checkString(a));
System.out.println(checkString(b));
System.out.println(checkString(c));
}
static boolean checkString(String str) {
return str != null && str.contains("#");
}
Output:
false
true
false
Here is some really simple code to achieve this:
String ourString = "example#emailIsCool.com";
if(/* Check if our string is null: */ ourString != null &&
/* Check if our string is empty: */ !ourString.isEmpty() &&
/* Check if our string contains "#": */ ourString.contains("#")) {
System.out.println("String Fits the Requirements");
} else {
System.out.println("String Does Not Fit the Requirements");
}
For future reference, this is extremely broad for Stack Overflow, and you should try checking the javadoc before you make a post asking for the answer. For example, here is the javadoc for the String class: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Javadocs provided by Oracle detail every method and attribute for all of the classes included in the standard java library. Here is a link to the javadoc homepage for Java 7.
https://docs.oracle.com/javase/7/docs/api/overview-summary.html
I think use Optional is the best way to do this.
Codes like this:
String nullEmail = null;
System.out.println(Optional.ofNullable(nullEmail).filter(s -> s.contains("#")).isPresent());
String rightEmail = "478309639#11.com";
System.out.println(Optional.ofNullable(rightEmail).filter(s -> s.contains("#")).isPresent());
String wrongEmail = "chentong";
System.out.println(Optional.ofNullable(wrongEmail).filter(s -> s.contains("#")).isPresent());
The output is:
false
true
false
i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of best available approach which is good for memory and performance both.
1) Below does not account for all spaces like in case of empty XML tag
return inputString==null || inputString.length()==0;
2) Below one takes care but trim can eat some performance + memory
return inputString==null || inputString.trim().length()==0;
3) Combining one and two can save some performance + memory (As Chris suggested in comments)
return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;
4) Converted to pattern matcher (invoked only when string is non zero length)
private static final Pattern p = Pattern.compile("\\s+");
return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();
5) Using libraries like -
Apache Commons (StringUtils.isBlank/isEmpty)
or Spring (StringUtils.isEmpty)
or Guava (Strings.isNullOrEmpty)
or any other option?
Useful method from Apache Commons:
org.apache.commons.lang.StringUtils.isBlank(String str)
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)
To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:
if(myString==null || myString.isEmpty()){
//do something
}
or if blank spaces need to be detected as well:
if(myString==null || myString.trim().isEmpty()){
//do something
}
you could easily wrap these into utility methods to be more concise since these are very common checks to make:
public final class StringUtils{
private StringUtils() { }
public static bool isNullOrEmpty(string s){
if(s==null || s.isEmpty()){
return true;
}
return false;
}
public static bool isNullOrWhiteSpace(string s){
if(s==null || s.trim().isEmpty()){
return true;
}
return false;
}
}
and then call these methods via:
if(StringUtils.isNullOrEmpty(myString)){...}
and
if(StringUtils.isNullOrWhiteSpace(myString)){...}
Just to show java 8's stance to remove null values.
String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
...
}
Makes sense if you can use Optional<String>.
This one from Google Guava could check out "null and empty String" in the same time.
Strings.isNullOrEmpty("Your string.");
Add a dependency with Maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
with Gradle
dependencies {
compile 'com.google.guava:guava:20.0'
}
Haven't seen any fully-native solutions, so here's one:
return str == null || str.chars().allMatch(Character::isWhitespace);
Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):
return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
Or, to be really optimal (but hecka ugly):
int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;
One thing I like to do:
Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}
...
notBlank(myStr).orElse("some default")
Apache Commons Lang has StringUtils.isEmpty(String str) method which returns true if argument is empty or null
springframework library Check whether the given String is empty.
f(StringUtils.isEmpty(str)) {
//.... String is blank or null
}
Optional.ofNullable(label)
.map(String::trim)
.map(string -> !label.isEmpty)
.orElse(false)
OR
TextUtils.isNotBlank(label);
the last solution will check if not null and trimm the str at the same time
In most of the cases, StringUtils.isBlank(str) from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.
Take an example where I have an input object which was converted into string using String.valueOf(obj) API. In case obj reference is null, String.valueOf returns "null" instead of null.
When you attempt to use, StringUtils.isBlank("null"), API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.
Simply and clearly:
if (str == null || str.trim().length() == 0) {
// str is empty
}
With the openJDK 11 you can use the internal validation to check if the String is null or just white spaces
import jdk.internal.joptsimple.internal.Strings;
...
String targetString;
if (Strings.isNullOrEmpty(tragetString)) {}
You can make use of Optional and Apache commons Stringutils library
Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);
here it will check if the string1 is not null and not empty else it will return string2
If you have to test more than one string in the same validation, you can do something like this:
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class StringHelper {
public static Boolean hasBlank(String ... strings) {
Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();
return Optional
.ofNullable(strings)
.map(Stream::of)
.map(stream -> stream.anyMatch(isBlank))
.orElse(false);
}
}
So, you can use this like StringHelper.hasBlank("Hello", null, "", " ") or StringHelper.hasBlank("Hello") in a generic form.
We can make use of below
Optional.ofNullable(result).filter(res -> StringUtils.isNotEmpty(res))
.ifPresent( s-> val.set(s));
I know the isEmpty() method used to check if an arraylist is empty, but I am trying to check if an arraylist is not empty. I tried to look online but I didn't find any useful information on how to do this. My code is like "while ArrayList is not empty then run code).
Invert the result of isEmpty().
public boolean notEmpty(ArrayList a) {
return !a.isEmpty();
}
That will tell you when a list is not empty.
Alternatively, you can also check whether the array is null by the length/size of the arraylist.
while(arrayListName.size() > 0 ){
//execute code
}
If you initialize arrays as null you can just check if they are not null:
List<String> myArray = null;
myArray = myFunction.getArrayValues;
if (myArray != null) {
processArray (myArray);
}
This is easier to read for me
while (arrayList.isEmpty() == false) {
//do something cool
}
Can be useful
if (!arrayList.isEmpty() ){
//execute code
System.out.println(arrayList.get(arrayList.size()-1));
}
I have a doubt regarding checking null condition.For eg :
if(some conditon)
value1= value; //value1 is string type
else
value1= "";
Similarly some 4 other string value has similar condition.
What i need is i want to check whether all those 5 string value is null or not,Inorder to do some other specific part.
i did it like this
if(value1 == null)
{
}
but the pgm control didnot entered the loop eventhough value1="".
then i tried
if(value1 ==""){
}
this also didnt worked.
Cant we check null and "" value as same??
can anyone help me??
If you want to check is a String is null, you use
if (s == null)
If you want to check if a string is the empty string, you use
if (s.equals(""))
or
if (s.length() == 0)
or
if (s.isEmpty())
An empty string is an empty string. It's not null. And == must never be used to compare string contents. == tests if two variables refere to the same object instance. Not if they contain the same characters.
To check both "is not null" and "is not empty" on a String, use the static
TextUtils.isEmpty(stringVariableToTest)
It looks like you want to check wether a String is empty or not.
if (string.isEmpty())
You can't check that by doing if (string == "") because you are comparing the String objects. They are never the same, because you have two different objects. To compare strings, use string.equals().
When you are working on String always use .equals.
equals() function is a method of Object class which should be overridden by programmer.
If you want to check the string is null then if (string.isEmpty()) else you can also try if (string.equals(null))
You can use:
we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)
if(("").equals(s))
prefer below.
String str;
if(str.length() > 0)
{
Log.d("log","str is not empty");
}
else
{
Log.d("log","str is empty");
}
if(string.equals(""))
{
}
How to check if the string is not null?
if(!string.equals(""))
{
}
Checking for null is done via if (string != null)
If you want to check if its null or empty - you'd need if (string != null && !string.isEmpty())
I prefer to use commons-lang StringUtils.isNotEmpty(..)
You can do it with the following code:
if (string != null) {
}
Checking for null is done by:
string != null
Your example is actually checking for the empty string
You can combine the two like this:
if (string != null && !string.equals("")) { ...
But null and empty are two different things
Nothing really new to add to the answers above, just wrapping it into a simple class. Commons-lang is quite all right but if all you need are these or maybe a few more helper functions, rolling your own simple class is the easiest approach, also keeping executable size down.
public class StringUtils {
public static boolean isEmpty(String s) {
return (s == null || s.isEmpty());
}
public static boolean isNotEmpty(String s) {
return !isEmpty(s);
}
}
Use TextUtils Method.
TextUtils.isEmpty(str) : Returns true if the string is null or 0-length. Parameters: str the string to be examined Returns: true if str is null or zero length
if(TextUtils.isEmpty(str)){
// str is null or lenght is 0
}
Source of TextUtils class
isEmpty Method :
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluating the the second if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
Beware, it's only available since Java SE 1.6.
You have to check str.length() == 0 or str.equals("")
on previous versions.
As everyone is saying, you'd have to check (string!=null), in objects you're testing the memory pointer.
because every object is identified by a memory pointer, you have to check your object for a null pointer before testing anything else, so:
(string!=null && !string.equals("")) is good
(!string.equals("") && string !=null) can give you a nullpointerexception.
if you don't care for trailing spaces you can always use trim() before equals()
so " " and "" gives you the same result
The best way to check a String is :
import org.apache.commons.lang3.StringUtils;
if(StringUtils.isNotBlank(string)){
....
}
From the doc :
isBlank(CharSequence cs) :
Checks if a CharSequence is empty (""), null
or whitespace only.
You can use Predicate and its new method (since java 11) Predicate::not
You can write code to check if string is not null and not empty:
Predicate<String> notNull = Predicate.not(Objects::isNull);
Predicate<String> notEmptyString = Predicate.not(String::isEmpty);
Predicate<String> isNotEmpty = notNull.and(notEmptyString);
Then you can test it:
System.out.println(isNotEmpty.test("")); // false
System.out.println(isNotEmpty.test(null)); // false
System.out.println(isNotEmpty.test("null")); // true
A common way for testing null string in Java is with Optionals:
Optional.ofNullable(myString).orElse("value was null")
Optional.ofNullable(myString).ifPresent(s -> System.out.println(s));
Optional.ofNullable(myString).orElseThrow(() -> new RuntimeException("value was null"));
And to test if it is null or empty you can use Apache org.apache.commons.lang3 library that gives you the following methods:
StringUtils.isEmpty(String) / StringUtils.isNotEmpty(String): It tests if the String is null or empty (" " is not empty)
StringUtils.isBlank(String) / StringUtils.isNotBlank(String): Same as isEmpty bt if the String is only whitespace it is considered blank
And applied to Optional you get:
Optional.ofNullable(myString).filter(StringUtils::isNotEmpty).orElse("value was null or empty");
Try using Strings.isNullOrEmpty("") from com.google.common.base.Strings this method returns boolean value and checks for both null and empty string.
if(string != null)
or
if(string.length() == 0)
or
if(("").equals(string))
u can try this
if(string != null)