Altering return value of method - java

Lets say that I have a method that returns a String. I want to check if the returned String is equal to another String and if they are the same to set the returned String to be just "". How would I go about doing this.

Assuming the "original" string is str and the "other" string is anotherStr:
return str.equals(anotherStr) ? "" : str;
Notice that anyway you have to return something if the strings are different, I'm returning str, but you'll know what's the appropriate value to return in this case.

Use String.equals() to compare two strings in Java.
return str.equals("bla") ? "" : str;

Set up your check() method like this, where you pass in the String you want to check for, and run it at the end of the method...
public String check(String comparison){
// do some normal processing here, which ends up with a String 'result' that you want to return
...
// Do the check at the end
if (result.equals(comparison)){
return "";
}
else {
return result;
}
}
Alternatively, you can add the check into the method call itself, which doesn't require you to change the signature of the method...
String result = runMethod();
if (result.equals(comparison)){
result = "";
}

Related

How to verify if a string contains a whole other string?

So I have this method which returns true if the validation is correct:
private boolean validation() {
String emailStr = etEmail.getText().toString();
if (emailStr.trim().isEmpty()) {
etEmail.setError(getResources().getString(R.string.eroareEmpty));
return false;
} else if (!emailStr.endsWith("stud.ase.ro") && emailStr.length() <= 15) {
etEmail.setError(getResources().getString(R.string.eroareEmail));
return false;
}
return true;
}
I want to verify that the text i type in EditText etEmail contains (only at the end of the string) "stud.ase.ro", the whole string not just a part of it.
In simple words, i want to verify if the email ends with "stud.ase.ro" and nothing else.
Currently my method returns true, even if i type something unsual like "hellllllllllllooo#stud", which it shouldn't do.
To match at the end of the string, use the String.endsWith method.
if (str.endWiths("hello123#stud")) {
//bla bla
}
You might want to improve your code. You're using EditText right?
EditText.getText() does not return null
You should create a local variable for repeated code access the text inside EditText: String emailStr = etEmail.getText().toString()
It will increase readability a lot.

StringBuilder appends null as "null"

How come?
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append((String)null);
sb.append(" World!");
Log.d("Test", sb.toString());
Produces
06-25 18:24:24.354: D/Test(20740): Hellonull World!
I expect that appending a null String will not append at all!!
BTW, the cast to String is necessary because StringBuilder.append() has a lot of overloaded versions.
I simplified my code to make a point here, in my code a got a method returning a string
public String getString() { ... }
...
sb.append(getString());
...
getString() sometimes returns null; now I have to test it if I want to use a StringBuilder!!!!
Furthermore, let's clarify my question here: how can I get StringBuilder.append() to accept, in an elegant way, a null string, and not convert it to the literal string "null".
By elegant I mean I don't want to get the string, test if it is null and only then append it. I am looking for an elegant oneliner.
How come?
Its clearly written in docs
The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.
So please put a null check before append.
That's just the way it is. null is appended as "null". Similarly, when you print null with System.out.println(null) you print "null".
The way to avoid that is that method that returns string getString() checks for null:
public String getString() {
...
if (result == null) {
return "";
}
}
It behaves like this, because null isn't an empty String as you think of it. Empty Stringwould be new String("");. Basically append() method appends "null" if it gets null value as a parameter.
EDIT
My previous answer was not reflecting the appropriate reason for such behaviour of StringBuilder as asked by OP. Thanks to #Stephen C for pointing out that
I expect that appending a null String will not append at all!!
But it is appending. The reason for such behaviour of StringBuilder is hidden in implementation detail of append(Object obj) method which takes us to AbstractStringBuilder#append(String str) method which is defined as follows:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; -->(1)
//.......
return this;
}
It clearly specifying that if the input String is null then it is changed to String literal "null" and then it processes further.
How can I get StringBuilder.append() to accept, in an elegant way, a null string, and not convert it to the literal string "null".
You need to check the given String for null explicitly and then proceed. For example:
String s = getString();
StringBuffer buf = new StringBuffer();
//Suppose you want "Hello "<value of s>" world"
buf.append("Hello ");
buf.append(s==null?" world" : s+" world");
AbstractStringBuilder class appends an object through String.valueOf(obj) method which in turn converts NULL into string literal "null". Therefor there is no inbuilt method to help you here. You have to either use ternary operator within append method or write a utility method to handle it, as others suggested.
This will work for you
public static String getString(StringBuilder sb, String str) {
return sb.append(str == null ? "" : str).toString();
}
What about writing an utility method like
public static void appendString(StringBuilder sb, String st) {
sb.append(st == null ? "" : st);
}
or this the ternary operator is very handy.
String nullString = null;
StringBuilder sb = new StringBuilder();
sb.append("Hello");
if (nullString != null) sb.append(nullString);
sb.append(" World!");
Log.d("Test", sb.toString());
There! I did it in one line :)
One line?
sb.append((getString()!=null)?getString():"");
done. But is pointless as have to call getString() twice
As was suggested build check into getString() method
You can also write decorator for StringBuilder, which can check whatever you want:
class NotNullStringBuilderDecorator {
private StringBuilder builder;
public NotNullStringBuilderDecorator() {
this.builder = new StringBuilder();
}
public NotNullStringBuilderDecorator append(CharSequence charSequence) {
if (charSequence != null) {
builder.append(charSequence);
}
return this;
}
public NotNullStringBuilderDecorator append(char c) {
builder.append(c);
return this;
}
//Other methods if you want
#Override
public String toString() {
return builder.toString();
}
}
Example of usage:
NotNullStringBuilderDecorator sb = new NotNullStringBuilderDecorator();
sb.append("Hello");
sb.append((String) null);
sb.append(" World!");
System.out.println(sb.toString());
With this solution you have not to change POJO classes.

replace null or empty data in string builder with some message

I have a string builder and it contains some data.I want to ensure whenever there is a null or empty("") data in it, i want to replace it with some message e.g not available. This is a huge data and i cannot go and replace each and every String.
Following is a snippet of code :
Stringbuilder sb = new Stringbuilder();
String a = "10";
String b = 13;
sb.append("entity.id=").append(a).append("entity.value=").append(b);
sb.toString;
So whenever entity.id or entity."ANYTHING" equals "null" or is empty, it should be replaced with a message like entity.id= not available
Without knowing your exact requirements, this may not be perfect, but is one option:
public void myCustomAppend(Appendable a, CharSequence cs){
if(cs == null || cs.length() == 0){
a.append("(not available)");
}else{
a.append(cs);
}
}
myCustomAppend(sb, "entity.id=");
myCustomAppend(sb, a);
myCustomAppend(sb, "entity.value=");
myCustomAppend(sb, b);
Some improvements to this could include creating it as a custom object with it's own state - preventing the need to keep passing-in the same reference to the StringBuilder, as well as allowing for successive calls to be chained (as you had them in the original question).
Create a function, for example...
public String checkString(String str) {
if(str == null || str.isEmpty())
return "N/A";
return str;
}
Call it on a String you want to append.
sb.append("entity.id=").append(checkString(a)).append("entity.value=").append(checkString(b));
Consider using Guava's Joiner class.
List<String> values = newArrayList("value1", "value2", a, b, c);
String result = Joinger.on(" ").useForNull("null").join(values);
You can also use "omitNull" instead of "useForNull"
Seeing what you are doing, you might also want to look at MoreObjects.ToStringHelper
Guava docs
check the strings if they are empty, before you append it. If the string is empty you can append a your message instead of the content of the data strings. ;)

Java - Compare two strings and assign value to third variable?

this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.

How to check if String value is Boolean type in Java?

I did a little search on this but couldn't find anything useful.
The point being that if String value is either "true" or "false" the return value should be true. In every other value it should be false.
I tried these:
String value = "false";
System.out.println("test1: " + Boolean.parseBoolean(value));
System.out.println("test2: " + Boolean.valueOf(value));
System.out.println("test3: " + Boolean.getBoolean(value));
All functions returned false :(
parseBoolean(String) returns true if the String is (case-insensitive) "true", otherwise false
valueOf(String) ditto, returns the canonical Boolean Objects
getBoolean(String) is a red herring; it fetches the System property of the given name and compares that to "true"
There exists no method to test whether a String encodes a Boolean; for all practical effects, any non-"true"-String is "false".
return "true".equals(value) || "false".equals(value);
Apache commons-lang3 has BooleanUtils with a method toBooleanObject:
BooleanUtils.toBooleanObject(String str)
// where:
BooleanUtils.toBooleanObject(null) = null
BooleanUtils.toBooleanObject("true") = Boolean.TRUE
BooleanUtils.toBooleanObject("false") = Boolean.FALSE
BooleanUtils.toBooleanObject("on") = Boolean.TRUE
BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
BooleanUtils.toBooleanObject("off") = Boolean.FALSE
BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
BooleanUtils.toBooleanObject("blue") = null
if ("true".equals(value) || "false".equals(value)) {
// do something
} else {
// do something else
}
Here's a method you can use to check if a value is a boolean:
boolean isBoolean(String value) {
return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
.anyMatch(b -> b.equalsIgnoreCase(value));
}
Examples of using it:
System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false
The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true, put "false" in string, they return false.
You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean.
Wrap that in a Method ContainsBoolString and you're go.
EDIT
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result.
int i;
if (Int32.TryParse("Hello", out i))
// Hello is an int and its value is in i
else
// Hello is not an int
Benchmarks indicate they are way faster than the following:
int i;
try
{
i = Int32.Parse("Hello");
// Hello is an int and its value is in i
}
catch
{
// Hello is not an int
}
Maybe there are similar methods in Java? It's been a while since I've used Java...
Actually, checking for a Boolean type in a String (which is a type) is impossible. Basically you're asking how to do a 'string compare'.
Like others stated. You need to define when you want to return "true" or "false" (under what conditions). Do you want it to be case(in)sensitive? What if the value is null?
I think Boolean.valueOf() is your friend, javadoc says:
Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.
Can also do it by regex:
Pattern queryLangPattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = queryLangPattern.matcher(booleanParam);
return matcher.matches();
Yes, but, didn't you parse "false"? If you parse "true", then they return true.
Maybe there's a misunderstanding: the methods don't test, if the String content represents a boolean value, they evaluate the String content to boolean.
String value = "True";
boolean result = value.equalsIgnoreCase("true") ? true : false;
Well for this, also have a look at org.apache.commons.lang.BooleanUtils#toBoolean(java.lang.String), along with many other useful functions.
return value.equals("false") || value.equals("true");
Something you should also take into consideration is character casing...
Instead of:
return value.equals("false") || value.equals("true");
Do this:
return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");
I suggest that you take a look at the Java docs for these methods. It appears that you are using them incorrectly. These methods will not tell you if the string is a valid boolean value, but instead they return a boolean, set to true or false, based on the string that you pass in, "true" or "false".
http://www.j2ee.me/javase/6/docs/api/java/lang/Boolean.html
See oracle docs
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
function isBooleanString(val) {
if (val === "true" || val === "false"){
return true
} else {
return false
}
}
isBooleanString("true") // true
isBooleanString("false") // true
isBooleanString("blabla") // false

Categories