String selectedVal = "";
for (SelectItem item : filterItems) {
selectedVal = item.getValue().toString();
break;
}
I am getting selectedVal=" " how to check this empty space in java.
I tried with if(!selectedVal.equals("") and if(!selectedVal.isEmpty()) but condition getting true.How to check more than one empty space ?
You can trim() your string before checking with isEmpty()
boolean isEmpty = myString.trim().isEmpty();
Beware of isEmpty(), it's only available since Java SE 6
Resources :
javadoc - String.trim()
javadoc - String.isEmpty()
I use this all the time:
public static boolean isBlank(String s)
{
return (s == null) || (s.trim().length() == 0);
}
Returns true on null, empty string, or whitespace only.
For such a simple test, using an external library is not a good idea, but if you need String manipulation (left and right padding, etc.), you can go for Apache commons lang and the
StringUtils.isEmpty() method.
More recently, you can use the Google Guava library and the class Strings. This library has a lot of usefull util methods (null handling, etc.). Once again, use this library only if you have others needs than checking empty strings.
boolean isEmpty = myString.toString().trim().isEmpty()
I use a routine similar to what Grodriguez posted. It ends up in a util/BagOTricks.java file in every project. My routine does a similar check and returns a null as a space, or the trimmed input string.
I am not a java programmer, but with regex, \s means white space.
This link might also be useful:
/**
* Helper function for making null strings safe for comparisons, etc.
*
* #return (s == null) ? "" : s;
*/
public static String makeSafe(String s) {
return (s == null) ? "" : s;
}
/**
* Helper function for null, empty, and whitespace string testing.
*
* #return true if s == null or s.equals("") or s contains only whitespace
* characters.
*/
public static boolean isEmptyOrWhitespace(String s) {
s = makeSafe(s);
for (int i = 0, n = s.length(); i < n; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
You can use this method:
public boolean isNullOrEmpty(String s) {
return s == null || s.trim().isEmpty();
}
Method returns true when passed string is null or empty / only contains blank spaces.
Using the Apache Commons Lang library, you can use StringUtils.isEmpty() to check if a String is empty ("") or null, and StringUtils.isBlank() to check if a String is whitespace, empty ("") or null.
Note the differences:
isEmpty()
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
isBlank()
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
Related
I'm trying to write a method that checks if a given string only contains these {([])} characters.
// Test strings
String S = "{U}" // should give FALSE
String S = "[U]" // should give FALSE
String S = "U" // should give FALSE
String S = "([)()]" // should give TRUE
I've tried:
if(S.matches("[{(\\[\\])}]")) {
return 1;
}
But this returns never true.
String.matches() matches the entire string against the pattern. The pattern you are trying is failing because it only matches a single character - for example, "{".matches("[{(\\[\\])}]") would return true. You need to add a repeat to your regex - either * if you want to match empty strings, or + if the string must contain at least one character, like so:
if(S.matches("[{(\\[\\])}]+")) {
return 1;
}
if(S.matches("^[{(\\[\\])}]+$")) {
return 1;
}
^ - beginning of the line
[]+ - characters contained in character class [] ONE OR MORE times
$ - end of the line
If you want to create a method (as you've mentioned in question), you might want to consider creating such method returning boolean (note that returning boolean (true or false) is not equal to returning 1 or 0 in Java):
public boolean checkIfContainsOnlyParenthesis(String input) {
return input.matches("^[{(\\[\\])}]+$");
}
If your intention was to return 1 when condition is fulfilled and - for example - 0, when it's not, you need to change return value of that method toint:
public int checkIfContainsOnlyParenthesis(String input) {
if(input.matches("^[{(\\[\\])}]+$")) {
return 1;
} else {
return 0;
}
}
That way you can pass your S string as argument of that method like this:
checkIfContainsOnlyParenthesis(S);
if(namefield.getText().compareTo("")==0)
Is this code above correct to check that no input is there in the textfield so that a error message can be generated?
provided have to use compareTo func only
to be more accurate
String data = nameField.getText()
if(data==null || data.length()==0)
{
//show error message here
}
It depends on how the namefield.getText() method is implemented in your platform. Since you didn't method which platform you are using. I suggest you can check the documentation.
Generally, when the namefield is not set, namefield.getText() will return a empty String which is "". So we don't need to check if it's null.
So we can check using following code:
if(namefield.getText().isEmpty()){}
which is same as following:
if(namefield.getText().length()==0){}
Because String.isEmpty() method is implemented as following:
public boolean isEmpty() {
return value.length == 0;
}
On the other hand, when the namefield.getText() can return null. You need to check null to avoid NPE.
String name = namefield.getText();
if(name==null || name.isEmpty()){}
Finally, if you want to check if the input string is whitespace, you can simply use String.trim() to remove the whitespace.
if(namefield.getText().trim().isEmpty()){}
or
String name = namefield.getText();
if(name==null || name.trim().isEmpty()){}
Even though we can use name.equals(""), I don't think it's the best way. Since in String.equals method, it firstly check if the objects are the same and then use the length to check if they're equal. However, when we get a text from a Textfield, the object will not be the same with the constant string "".
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
The method compareTo() is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.
Instead use equals()
if(namefield.getText().equals(null) || namefield.getText().equals(""))
{
//do this
}
I would use
if((namefield.getText()== null) || (namefield.getText().length() == 0)){
show error message
}
Do I lose anything by replacing the following:
public final boolean testEquals(String left, String right) {
if ((left == null && right != null) || (left != null && right == null)) {
return false;
} else if (left == null && right == null) {
return true;
} else {
return left.equalsIgnoreCase(right);
}
}
With this from the JDK 7 Objects class:
public final boolean testEquals(String left, String right) {
return Objects.equals(left,right);
}
If I lose the case insensitivity, is replacing it with
Objects.equals(left.toLowerCase(),right.toLowerCase());
enough? Does it make sense to?
If you are not only limited to JDK you can use
StringUtils.equalsIgnoreCase(CharSequence str1, CharSequence str2)
from apache-commons lang which is null-safe and will return
StringUtils.equalsIgnoreCase(null, null) = true
StringUtils.equalsIgnoreCase(null, "abc") = false
StringUtils.equalsIgnoreCase("abc", null) = false
StringUtils.equalsIgnoreCase("abc", "abc") = true
StringUtils.equalsIgnoreCase("abc", "ABC") = true
The method String.equalsIgnoreCase(String) is "unfortunately" a little more complex. You can look into the code, but it is well explained in the javadoc itself:
Compares this String to another String, ignoring case considerations.
Two strings are considered equal ignoring case if they are of the same
length and corresponding characters in the two strings are equal
ignoring case.
Two characters c1 and c2 are considered the same ignoring case if at
least one of the following is true:
The two characters are the same (as compared by the == operator)
Applying the method Character.toUpperCase(char) to each character produces the same result
Applying the method Character.toLowerCase(char) to each character produces the same result
In this answer I recommended using
s.replaceFirst("\\.0*$|(\\.\\d*?)0+$", "$1");
but two people complained that the result contained the string "null", e.g., 23.null. This could be explained by $1 (i.e., group(1)) being null, which could be transformed via String.valueOf to the string "null". However, I always get the empty string. My testcase covers it and
assertEquals("23", removeTrailingZeros("23.00"));
passes. Is the exact behavior undefined?
The documentation of Matcher class from the reference implementation doesn't specify the behavior of appendReplacement method when a capturing group which doesn't capture anything (null) is specified in the replacement string. While the behavior of group method is clear, nothing is mentioned in appendReplacement method.
Below are 3 exhibits of difference in implementation for the case above:
The reference implementation does not append anything (or we can say append an empty string) for the case above.
GNU Classpath and Android's implementation appends null for the case above.
Some code has been omitted for the sake of brevity, and is indicated by ....
1) Sun/Oracle JDK, OpenJDK (Reference implementation)
For the reference implementation (Sun/Oracle JDK and OpenJDK), the code for appendReplacement doesn't seem to have changed from Java 6, and it will not append anything when a capturing group doesn't capture anything:
} else if (nextChar == '$') {
// Skip past $
cursor++;
// The first number is always a group
int refNum = (int)replacement.charAt(cursor) - '0';
if ((refNum < 0)||(refNum > 9))
throw new IllegalArgumentException(
"Illegal group reference");
cursor++;
// Capture the largest legal group string
...
// Append group
if (start(refNum) != -1 && end(refNum) != -1)
result.append(text, start(refNum), end(refNum));
} else {
Reference
jdk6/98e143b44620
jdk8/687fd7c7986d
2) GNU Classpath
GNU Classpath, which is a complete reimplementation of Java Class Library has a different implementation for appendReplacement in the case above. In Classpath, the classes in java.util.regex package in Classpath is just a wrapper for classes in gnu.java.util.regex.
Matcher.appendReplacement calls RE.getReplacement to process replacement for the matched portion:
public Matcher appendReplacement (StringBuffer sb, String replacement)
throws IllegalStateException
{
assertMatchOp();
sb.append(input.subSequence(appendPosition,
match.getStartIndex()).toString());
sb.append(RE.getReplacement(replacement, match,
RE.REG_REPLACE_USE_BACKSLASHESCAPE));
appendPosition = match.getEndIndex();
return this;
}
RE.getReplacement calls REMatch.substituteInto to get the content of the capturing group and appends its result directly:
case '$':
int i1 = i + 1;
while (i1 < replace.length () &&
Character.isDigit (replace.charAt (i1)))
i1++;
sb.append (m.substituteInto (replace.substring (i, i1)));
i = i1 - 1;
break;
REMatch.substituteInto appends the result of REMatch.toString(int) directly without checking whether the capturing group has captured anything:
if ((input.charAt (pos) == '$')
&& (Character.isDigit (input.charAt (pos + 1))))
{
// Omitted code parses the group number into val
...
if (val < start.length)
{
output.append (toString (val));
}
}
And REMatch.toString(int) returns null when the capturing group doesn't capture (irrelevant code has been omitted).
public String toString (int sub)
{
if ((sub >= start.length) || sub < 0)
throw new IndexOutOfBoundsException ("No group " + sub);
if (start[sub] == -1)
return null;
...
}
So in GNU Classpath's case, null will be appended to the string when a capturing group which fails to capture anything is specified in the replacement string.
3) Android Open Source Project - Java Core Libraries
In Android, Matcher.appendReplacement calls private method appendEvaluated, which in turn directly appends the result of group(int) to the replacement string.
public Matcher appendReplacement(StringBuffer buffer, String replacement) {
buffer.append(input.substring(appendPos, start()));
appendEvaluated(buffer, replacement);
appendPos = end();
return this;
}
private void appendEvaluated(StringBuffer buffer, String s) {
boolean escape = false;
boolean dollar = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\' && !escape) {
escape = true;
} else if (c == '$' && !escape) {
dollar = true;
} else if (c >= '0' && c <= '9' && dollar) {
buffer.append(group(c - '0'));
dollar = false;
} else {
buffer.append(c);
dollar = false;
escape = false;
}
}
// This seemingly stupid piece of code reproduces a JDK bug.
if (escape) {
throw new ArrayIndexOutOfBoundsException(s.length());
}
}
Since Matcher.group(int) returns null for capturing group which fails to capture, Matcher.appendReplacement appends null when the capturing group is referred to in the replacement string.
It is most likely that the 2 people complaining to you are running their code on Android.
Having had a careful look at the Javadoc, I conclude that:
$1 is equivalent to calling group(1), which is specified to return null when the group didn't get captured.
The handling of nulls in the replacement expression is unspecified.
The wording of the relevant parts of the Javadoc is on the whole surprisingly vague (emphasis mine):
Dollar signs may be treated as references to captured subsequences as described above...
You have two alternatives | or-ed together, but only the second is between ( ) hence if the first alternative is matched, group 1 is null.
In general place the parentheses around all alternatives
In your case you want to replace
"xxx.00000" by "xxx" or else
"xxx.yyy00" by "xxx.yyy"
Better do that in two steps, as that is more readable:
"xxx.y*00" by "xxx.y*" then
"xxx." by "xxx"
This does a bit extra, changing an initial "1." to "1".
So:
.replaceFirst("(\\.\\d*?)0+$", "$1").replaceFirst("\\.$", "");
I want to reverse a sentence recursively and below is my following code. I wanted to know what other bases cases shud i take care of. And for the base case if string is null, how should that be handled?
public String reverse(String s) {
int n = s.indexOf(' ');
if(n == -1)
return s;
return reverse(s.substring(n+1))+" "+s.substring(0,n);
}
The reverse of null is null, so that's easy:
if(s == null) return null;
Because your method has the potential to return null, then, I would also do some null checking before referencing the value in your return statement and trying to append to it. so, something like...
String reversed = reverse(s.substring(n+1));
if(reversed != null) return reverse + " " + s.substring(0,n);
else return s;
Everything else looks fine. You shouldn't need any other base cases. Of course, this will reverse the sentence exactly as-is, including punctuation and case information. If you want to do this kind of thing, more strenuous processing will be required.
To ensure appropriate upper- and lower-case structure, I'd probably do something like this in your normal base case:
if(n == -1) {
s = s.toLowerCase();
String firstLetter = new String(s.charAt(0));
s = s.replaceFirst(firstLetter, firstLetter.toUpperCase());
return s;
}
Punctuation gets a little more complicated, especially if you have more than just an ending period, exclamation point, or question mark.
in your case, if the string is null, you can return an empty string (""). Returning a null will require you to handle the null in the calling functions and if you miss a case, you might encounter a NullPointerException