I created a "Color Chooser" with three textboxes where the user defines rgb values.
To check if values entered are correct (only numbers between 0-255) I'm using the following:
public Color getColor() {
if (tfRed.getText().equals("") || tfGreen.getText().equals("") || tfBlue.getText().equals("")) {
return new Color(0, 0, 0, 0);
} else {
if (tfRed.getText().matches("\\d+") && tfGreen.getText().matches("\\d+") && tfBlue.getText().matches("\\d+")) {
// ...
} else {
return new Color(0, 0, 0, 0);
}
}
}
What I'm asking: is it better to use String.isEmpty()? I never found a satisfying answer and I've always wondered if there is any difference.
I think isEmpty() is a bit more efficient. However a smart compiler may optimize the equals("") call anyway. From the OpenJDK source:
671 public boolean isEmpty() {
672 return count == 0;
673 }
1013 public boolean equals(Object anObject) {
1014 if (this == anObject) {
1015 return true;
1016 }
1017 if (anObject instanceof String) {
1018 String anotherString = (String)anObject;
1019 int n = count;
1020 if (n == anotherString.count) {
1021 char v1[] = value;
1022 char v2[] = anotherString.value;
1023 int i = offset;
1024 int j = anotherString.offset;
1025 while (n-- != 0) {
1026 if (v1[i++] != v2[j++])
1027 return false;
1028 }
1029 return true;
1030 }
1031 }
1032 return false;
1033 }
Also the answer here on whether to use str.isEmpty() or "".equals(str) is spot on:
The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string
Yes, use String.isEmpty(). It is cleaner (semantically) (performance is also slightly better, but that would be unnoticable) If the instance can be null, use commons-lang StringUtils.isEmpty(string)
Since isEmpty() checks if the length of the String is 0 and "" is the only String with length 0, each String for which isEmpty() returns true would also return true to .equals(""). So technically, they do the same thing.
There might be a minimal difference in performance, but I wouldn't bother about that at all (I'd be very surprised if it were noticeable in production code).
Another difference is if you wrote "".equals(someString), then it would be "null-safe". In other words: if someString was null, this construct would simply evaluate to false and not throw a NullPointerException. If, however, you have someString.equals("") then this would not apply.
The most important difference is how it's read: isEmpty() makes the intention very clear: you want to treat empty strings differently. .equals("") is ever so slightly less clear ("if that string equals that other string, that happens to be empty").
Typically, I like to use equals but in reverse, ie:
"".equals(someString);
Null-safe :)
But yeah, isEmpty() is a simpler operation but not so much that I see it making any significant performance contribution (unless you are writing embedded real-time stuff).
With myString.equals(""), first the compiler creates an String object (it is equivalent to myString.equals(new String("")).
So, isEmpty() should be a better option (although equals("") is very popular).
In theory, it is. For isEmpty(), only the internal metadata of the string has to be looked at (e.g., it's length). For the comparison, you would expect slightly more case differentiations happening.
In practice, it does not matter. You would not observe the speed difference.
Rule of thump: Use the method that is best understood / most readable by the programmer. If it is a test for empty string, I think isEmpty() fits that purpose best.
isEmpty() is faster because it only compares the length integer field in String class to 0 while comparing to an empty string will at best compare references (similar speed) and at worst - run a loop with 0 iterations.
But the biggest difference is readability - isEmpty() is shorter and easier to grasp. BTW I wish there was an isBlank() shorthand for .trim().isEmpty()...
One more reason using myString.equals("") or myString.length() == 0 is that String#isEmpty() method was introduced in Java 1.6.
So arguments to do not use String#isEmpty() can be compatibility reasons with previous versions of Java.
It's partly a matter of history and legacy uses. isEmpty() was only added in JDK 6:
/**
* Returns <tt>true</tt> if, and only if, {#link #length()} is <tt>0</tt>.
*
* #return <tt>true</tt> if {#link #length()} is <tt>0</tt>, otherwise
* <tt>false</tt>
*
* #since 1.6
*/
public boolean isEmpty() {
Before that, everyone compared with "" to see if an String was empty or not. Old habits die hard, so loads of people keep using the "" comparison.
Of course, as mentioned by someone else already, if you use "".equals(someString) then it's automatically null safe. Many people combine the idea of isEmpty with null safeness, by making a static isEmpty method.
isEmpty was only introduced in 1.6. Check Since tag in javadoc.
Therefore, if you are compiling for 1.5 and lower equals("") is your only choice.
However, if version compatibility is not of your concern, I would use isEmpty. As Bozho pointed out it is semantically cleaner ( and a bit faster ).
I had always used .isEmpty()... until today, when I discovered that it does not exist in Java 5.
So :
In Java 6 and newer, we have the choice, and I recommend using .isEmpty(), it is easier to write and clearer to read.
In Java 5 and older we have to use .equals("").
String.equals("") is bit slower than just an isEmpty() call. Strings store a count variable initialized in the constructor, since Strings are immutable.
isEmpty() compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.
So to answer your question, isEmpty() will actually do a lot less! and that's a good thing.
Related
Which is better in terms of best practice / efficiency?
if (x == 1
&& y == 1
&& z == 1)
{ do things }
or
if (x != 1 ||
y != 1 ||
z != 1)
{ don't do things and go to a different bit of logic.}
Is there any difference in efficiency when short circuiting ANDs and ORs? Is it (generally) better to check positively or negatively when multiple logical assertions need to be made?
For pure optimization of the code it depends case-by-case. The scenario that will on average do the least amount of comparisons.
For code design it is also case-by-case. The if-cases should match what you are actually looking for. A function that tests if a string is inputted correctly for example. (the tests are made up)
public boolean isValidString (string s) {
if (s.isEmpty())
return false;
if (s.length() < 12)
return false;
if (s...)
return false
return true;
}
In this case the most logical approach is the ||. It could be written.
public boolean isValidString (string s) {
if (s.isEmpty() || s.length() < 12 || s...)
return false;
return true;
}
With http://en.wikipedia.org/wiki/De_Morgan%27s_laws this could be rewritten to not and. However it is not what we want to test, even though they yield the same result.
So stick to the logical approach in general cases.
If you think about efficiency then think about how often each case will occur. The most likely one should be put in front so the whole expression is shortcircuited immediately.
Better you use "==" instead of going for "!=".
This is also recommended with PMD.
The following is good and improves redability.
If(true){
//
}else{
//
}
than
If(!true){
//
}else{
//
}
Well, in some JVM implementations boolean values are stored as integers in the JVM. int value 1 meaning true and int value 0 meaning false. Also, comparison logic at processor level is architecture dependent. Some machines might subtract 2 operands, then add and then compare, others might compare byte by byte etc.. So, unless you are looking at a specific hardware architecture (which you shouldn't.. atleast for java programming language), I don't think this matters much..
I have a string that I would like to convert into an integer before storing it as a property of an object. Although I can use regular if statements, I wanted to use a ternary operation to build my understanding of it. Here is the code I've tried
field_num = (((boolean bool_is_int = is_integer(string)) == true) ? (Integer int = Integer.parseInt(string)) : null);
What I'm trying to do (very basically) is set "field_num" (which is of type int) to the value of "string" if it is equal to an integer (by first converting it). is_integer is a function I have to check if a string is equal to an integer. It returns a boolean value.
Thanks for any help.
I would do something like this:
Integer theint = is_integer(thestr) ? Integer.parseInt(thstr) : null;
You cannot assign NULL to an intrinsic int but you can to an Integer object. Typically, of course, you'd simply rely on the parseInt() call throwing an exception rather than explicitly testing for integerness of the string beforehand.
field_num = is_integer(string) ? Integer.parseInt(string): -1;
In plain english this says if 'string' is an integer then parse string for the int and set it to field_num otherwise, set it to -1. -1 is arbitrary. you should instead use a number that is invalid for field_num.
You do not need is_integer(string) == true because that evaluates to the same thing as is_integer(string). You also don't need to set the boolean bool_is_int because unless you actually want that value later in the program.
You should just use an if/else statement. The Ternary operator is useful when you you want to set a variable to one of two values based on a condition. In your example, you don't want to set the value if the string is not an integer so ternary doesn't fit the situation well.
Keep it simple :)
int field_num = isInt(string) ? Integer.parseInt(string) : Integer.MAX_VALUE;
if (field_num == Integer.MAX_VALUE) {
// error; string is not a valid representation of int
}
To determine Whether a String represents an int value :
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
[Corrected]
Learn one thing at a time.
First, the ?: operator (more often referred to as the conditional operator, or the if/else operator; "ternary" just means it takes three arguments, and it's the only C operator that does so, hence the confusion)...
field_num = is_integer(string) ? Integer.parseInt(string) : null;
Ahhh. So field_num is an Integer. Would have help if you'd said that.
Second: Assignment-in-passing. If you don't know that you need to do this, and you can't make it perfectly obvious what you're doing and why, DON'T. It's hard to read, and it's rarely appropriate.
Also, "int" is not a legal variable name.
But if you insist:
Integer myint;
boolean bool_is_int;
field_num = (bool_is_int = is_integer(string)) ? (myint = Integer.parseInt(string)) : null;
What's myint's value in the false/else case? It's left as whatever it had been set to previously. This might be what you intended, but it's very hard for someone reading your code to understand.
In most cases, unless the ?: is a very simple one that can be read at a glance -- (foo!=null) ? foo.doSomething() : defaultValue -- you're better off using a real if/then/else statement. It's likely to be just as efficient after the compiler and JIT are done with it, and it'll be a lot easier to maintain.
I'm wondering if there's a way to convert a boolean to an int without using if statements (as not to break the pipeline). For example, I could write
int boolToInt( boolean b ){
if ( b )
return 1
return 0
But I'm wondering if there's a way to do it without the if statement, like Python's
bool = True
num = 1 * ( bool )
I also figure you could do
boolean bool = True;
int myint = Boolean.valueOf( bool ).compareTo( false );
This creates an extra object, though, so it's really wasteful and I found it to be even slower than the if-statement way (which isn't necessarily inefficient, just has the one weakness).
You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.
If you check the compiled code of that method (by the way, using return b ? 1 : 0; compiles to the exact same instructions), you will see that it does not use a jump:
0x0000000002672580: sub $0x18,%rsp
0x0000000002672587: mov %rbp,0x10(%rsp) ;*synchronization entry
0x000000000267258c: mov %edx,%eax
0x000000000267258e: add $0x10,%rsp
0x0000000002672592: pop %rbp
0x0000000002672593: test %eax,-0x2542599(%rip) # 0x0000000000130000
; {poll_return}
0x00000000025b2599: retq
Note: this is on hotspot server 7 - you might get different results on a different VM.
Use the ?: operator: ( b ? 1 : 0 )
You can use the ternary operator:
return b ? 1 : 0;
If this is considered an "if", and given this is a "puzzle", you could use a map like this:
return new HashMap<Boolean, Integer>() {{
put(true, 1);
put(false, 0);
}}.get(b);
Although theoretically the implementation of HashMap doesn't need to use an if, it actually does. Nevertheless, the "if" is not in your code.
Of course to improve performance, you would:
private static Map<Boolean, Integer> map = new HashMap<Boolean, Integer>() {{
put(true, 1);
put(false, 0);
}};
Then in the method:
return map.get(b);
Otherwise, you could use the Apache Commons BooleanUtils.toInteger method which works like a charm...
// Converts a boolean to an int specifying the conversion values.
static int toInteger(boolean bool, int trueValue, int falseValue)
// Converts a Boolean to an int specifying the conversion values.
static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue)
I found a solution by framework. Use compare for Boolean.
// b = Your boolean result
// v will be 1 if b equals true, otherwise 0
int v = Boolean.compare(b, false);
This is not directly possible, not in Java anyway. You could consider directly using an int or byte instead of a boolean if you really need to avoid the branch.
It's also possible that the VM is smart enough to eliminate the branch (the if or ?:) itself in this case, as the boolean's internal representation is quite likely to be the literal 1 or 0 anyway. Here is an article on how to examine the generated native machine code for the Oracle JDK, and if you need speed, make sure you're using the "server" JVM as it performs more aggressive optimization than the "client" one.
I can't say I recommend this. It's both slower than the ternary operator by itself, and it's too clever to be called good programming, but there's this:
-Boolean.FALSE.compareTo(value)
It uses the ternary under the covers (a couple of method calls later), but it's not in your code. To be fair, I would be willing to bet that there's a branch somewhere in the Python execution as well (though I probably only bet a nickel ;) ).
Since you want no if / else solution your expression is perfect, though I would slightly change it
int myint = Boolean.valueOf( bool ).compareTo( Boolean.FALSE );
There is no object creation involved, Boolean.valueOf(boolean b) returns either Boolean.TRUE or Boolean.FALSE, see API
A reasonable alternative to ising to the ternary to avoid an "if":
private static Boolean[] array = {false, true};
int boolToInt( boolean b ){
return Arrays.binarySearch(array, b);
}
Note that I consider this s "puzzle" question, so if coding it myself i would use the ternary..
You can try using ternary operator like this
int value = flag ? 1 : 0;
Nowadays, jdk has delivered a useful Utils method: BooleanUtils.toInteger()
In the source code, the method that jdk realize it must be efficient:
public static int toInteger(boolean bool) {
return bool ? 1 : 0;
}
So, I think the most votes answer is very great, return bool ? 1 : 0 is the best practice.
Example Code to use BooleanUtils as followed:
BooleanUtils.toInteger(false);
int ansInt = givenBoolean ? 1 : 0;
I am wondering complexity of following if statement
if (isTrue()) //case 1
VS
if(isTrue()==true) //case 2
And isTrue defined as
boolean isTrue(){
//lots of calculation and return true false based on that.
return output;
}
I was thinking, complexity of if (isTrue()) is lower then if(isTrue()==true) because on case 2 require additional comparison for equals.
What about space complexity?
Any different thought?
Both of them are same in speed/space. But second way is weird for C/C++ programmers.
The different is, second way is just less readable.
They are equivalent. And when doing global optimizations condition is removed altogether.
The second case (checking for ==true) can get problematic if you or someone else redefines the value of true.
Let's say that we have the following C code:
#define true 2
bool isEqual(int a, int b)
{
return (a == b);
}
if (isEqual(5, 5)) {
printf("isEqual #1\n");
}
if (isEqual(5, 5) == true) {
printf("isEqual #2\n");
}
The output from this code will be
isEqual #1
So the shorter form where you leave out ==true is preferable not only because it leads to less verbose code but also because you avoid potential problems like these.
This is a homework question that I am having a bit of trouble with.
Write a recursive method that determines if a String is a hex number.
Write javadocs for your method.
A String is a hex number if each and every character is either
0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9
or a or A or b or B or c or C or d or D or e or E or f or f.
At the moment all I can see to test this is if the character at 0 of the string is one of these values he gave me then that part of it is a hex.
Any hints or suggestions to help me out?
This is what I have so far: `
public boolean isHex(String string){
if (string.charAt(0)==//what goes here?){
//call isHex again on s.substring(1)
}else return false;
}
`
If you're looking for a good hex digit method:
boolean isHexDigit(char c) {
return Character.isDigit(c) || (Character.toUpperCase(c) >= 'A' && Character.toUpperCase(c) <= 'F');
}
Hints or suggestions, as requested:
All recursive methods call themselves with a different input (well, hopefully a different input!)
All recursive methods have a stop condition.
Your method signature should look something like this
boolean isHexString(String s) {
// base case here - an if condition
// logic and recursion - a return value
}
Also, don't forget that hex strings can start with "0x". This might be (more) difficult to do, so I would get the regular function working first. If you tackle it later, try to keep in mind that 0xABCD0x123 shouldn't pass. :-)
About substring: Straight from the String class source:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
offset is a member variable of type int
value is a member variable of type char[]
and the constructor it calls is
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
It's clearly an O(1) method, calling an O(1) constructor. It can do this because String is immutable. You can't change the value of a String, only create a new one. (Let's leave out things like reflection and sun.misc.unsafe since they are extraneous solutions!) Since it can't be changed, you also don't have to worry about some other Thread messing with it, so it's perfectly fine to pass around like the village bicycle.
Since this is homework, I only give some hints instead of code:
Write a method that always tests the first character of a String if it fulfills the requirements. If not, return false, if yes, call the method again with the same String, but the first character missing. If it is only 1 character left and it is also a hex character then return true.
Pseudocode:
public boolean isHex(String testString) {
If String has 0 characters -> return true;
Else
If first character is a hex character -> call isHex with the remaining characters
Else if the first character is not a hex character -> return false;
}
When solving problems recursively, you generally want to solve a small part (the 'base case'), and then recurse on the rest.
You've figured out the base case - checking if a single character is hex or not.
Now you need to 'recurse on the rest'.
Here's some pseudocode (Python-ish) for reversing a string - hopefully you will see how similar methods can be applied to your problem (indeed, all recursive problems)
def ReverseString(str):
# base case (simple)
if len(str) <= 1:
return str
# recurse on the rest...
return last_char(str) + ReverseString(all_but_last_char(str))
Sounds like you should recursively iterate the characters in string and return the boolean AND of whether or not the current character is in [0-9A-Fa-f] with the recursive call...
You have already received lots of useful answers. In case you want to train your recursive skills (and Java skills in general) a bit more I can recommend you to visit Coding Bat. You will find a lot of exercises together with automated tests.