efficient way to compare multiple int values to 0 - java

I'm trying to compare three lengths to 0 and was wondering if there was a more efficient/cleaner way than repeating "!= 0".
public static boolean isTriangle(int lengthA, int lengthB, int lengthC) {
if (lengthA != 0 && lengthB != 0 && lengthC != 0) { //is there a shorter/cleaner way to write this?
//do a thing
}
return false;
}

You can use the IntStream and allMatch
if(IntStream.of(lengthA,lengthB,lengthC).allMatch(i->i!=0)) {
// do a thing
}
or by using noneMatch also
IntStream.of(lengthA,lengthB,lengthC).noneMatch(i->i==0)
The other way around you do this is by having a util method
public static boolean isNotZero(int val) {
return val!=0;
}
Now simplify the if condition
if (isNotZero(lengthA) && isNotZero(lengthB) && isNotZero(lengthC)) {

You're asking three things; you're asking for code that is
shorter
more efficient
cleaner
I have an alternative for you:
if ((lengthA & lengthB & lengthC) != 0)
It's correct - it does the same as your old code (it uses bitwise-and)
it is shorter.
it's potentially more efficient but only a good microbenchmark can confirm. Even if it is, that shouldn't guide you. Because of point 3, you should only consider it if it shows up as a bottleneck in your app using a performance analyzer tool, which is very, very unlikely.
however it's not cleaner. And with that I mean that it will make your code harder to read and understand, and anyone maintaining your code will now have to think about bit manipulation.
Most likely the same will go for any proposed alternative.
What you were doing in your original code is good enough; it's what people understand, and it's most likely the cleanest code you can write for the purpose.

Best answer (IMHO): "Don't even try to second-guess the optimizing compiler." Just specify the source-code in the way that most accurately specifies (to your fellow humans, nothing more ...) what you want the computer to do. Don't presume that the actual sequence of machine instructions that is actually given to the hardware actually corresponds to this. "It's magic. Really."

For Java language, your code is good. There's no better way to do this in Java.

Related

Does bitwise inclusive OR with assignment operator have advantages over typical assignment in java?

When looking at some code on one or another git, sometimes I can see that devs use bitwise inclusive OR compound assignment operator (|=) where simple assignment would be enough. Unfortunately, I don't have any code with this solution at hand, so I'll try to describe it as best I can.
Let's say, we have the following code in java:
boolean found = false;
for (String s : stringSet) {
if (s == null || s.equals("")) {
found |= true; // <== this line
}
}
if (!found) {
System.out.println("No interesting string found");
}
I ask only about the pointed line. Why people do it this way? I understand that we can have a really great amount of data, billions or trillions to iterate over. But does the pointed line changes the efficiency so dramatically? Would it be noticeably slower for a lot of data, if I change it to simple assignment: found = true;?
I don't exclude the possibility that not a speed is the main argument, but it seemed most meaningful to me.
And yes, I know this code can be converted to method or streams, but it's only a simplification of a code where it would be far more complicated etc. We can assume that before the pointed line (or even before if), there are tons of code that do something meaningful. Please, don't suggest something like "use streams instead", because I know how to java advanced already. I'd like to understand the phenomenon of this somehow enigmatic solution using bitwise inclusive OR.

How do you go back to a specific line in Java?

I am trying to make a Math Calculator Application. However I am wondering if there is a statement that allows you to go back to a certain line?
Let me clarify:
I am not referring to a loop. Here's a possibly scenerio: Let's say that the user has run the program and reached let's say line 54. If I have an if-else statement there, if there a way that I could make it so that "if (input = 0){go back to line 23}
Is there anything that may allow me to do this, not including a loop?
Java does not have a goto (goto is a reserved word but not used). Consider how your approach and language choice fit together. There is likely a better way to do this. Consider extracting a method or using a flag inside of a loop. Without more information, guidance will be limited.
Nope.
The goto statement exists in C and C++, which Java is vaguely similar to, but it's generally considered very bad practice to use. It makes code difficult to read and debug. Here are some correct ways to solve this problem with more structured programming:
do {
...
} while (input == 0);
private void doTheThing() { // please use a better name!
...
if (input == 0) doTheThing(); // recursion not recommended; see alternate
// method below
}
// alternate method:
do {
doTheThing();
} while (input == 0);
Why can't you use a loop?
Put your code in a function, then put in a loop that runs while input = 0.

What is faster and best for with if and return or while?

I have a question about the for and while loops, as we have to travel a value until a condition is met. I wonder which is more efficient at low level, and why?
That is, these two codes give the same result:
FOR:
for (int i = 0; i<10 ; i++)
{
if (i==4)
{
return;
}
}
WHILE:
int i=0;
while (i<10 and i!=4)
{
i++;
}
This is a small example of a possible loop, and we could be looking at a record of thousands.
What code is more effective? I've always said that I have to use a while in this case, but I wonder if a low level is still better while or better yet is for.
Thank you very much.
The answer is: it doesn't matter.
You will not see any difference in performance in either, unless you really try hard to make code to see the difference, and what really matters is the readability of your code (and this is where you'll save time and and money in the future), so use whichever one is more understandable.
In your case, i'll suggest the While approach ...
I'll also suggest reading this article by Eric Lippert: How Bad Is Good Enough?, just in case you're not sold on the readability vs. silly optimizations :)
They should compile very similarly. At a low level you are looking at executing the commands within the loop, and then you will have two calls to compare a value and jump to the next block of code if the condition calls for exiting the loop.
As mentioned above, while should lead to better readability and thus is the better choice.
Both for and while are the same.
The only difference is where you place the condition.
internally the while loop uses the 'for' syntax in low level.
In your scenario. While is the best option ** if you don't know the upper limit **
you can use
While(i!=4)
{
i++
}
Use for loop if you know the upper limit, else while is the best friend.

Is a program model with excessive use of exception handling efficient in terms of speed?

Though the question is generic, I would mention the scenario which sparked the query.
Scenario:
I am interested in analyzing a large number of strings (numeric ones in particular). Therefore, my first job is to filter out those ones which contain even a single character other than numbers.
A simple way to do this is (in Java):
for (String val : stringArray){
try{
int num = Integer.parseInt(val);
doSomething(num);
}
catch(NumberFormatException nfe){}
}
Another point which I must mention is that there are only about 5% of the strings in the array which are purely numeric. Thus there would be, in short, a lot of catching involved.
What I was wondering about was that whether this was an efficient way in terms of design or should I be thinking of other ways to do the same?
Conclusion based on answers: Exceptions are indeed expensive and it is not a very good design practice to use them as a form of control statement.
Therefore, one should try and look for alternatives wherever possible and if still exceptions seem to be clearer/easier, one should document it well.
What you do here is inherently correct as there is no other standard way in java to check if a string is numeric.
If a profiling proves you that this operation is too long, you could try to do it yourself as in the parseInt method but the JVM won't be able to do the same optimizations so I don't recommend it. You'll see that the JVM is heavily optimized to handle exceptions and that it does this job very well.
As a curiosity, here are a few ways to do it in java :
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java
with links to other languages, but your solution is the standard and idiomatic one and I doubt you'll find a big difference by rewriting it as in the example :
private static final boolean isNumeric(final String s) {
if (s == null || s.isEmpty()) return false;
for (int x = 0; x < s.length(); x++) {
final char c = s.charAt(x);
if (x == 0 && (c == '-')) continue; // negative
if ((c >= '0') && (c <= '9')) continue; // 0 - 9
return false; // invalid
}
return true; // valid
}
Using this, in my opinion, would be a typical case of premature optimization leading to a less maintainable code.
It is not efficient.
You can look up lots of resources on the web as to why throwing an exception is considered expensive, for example: http://www.yoda.arachsys.com/csharp/exceptions.html.
Unfortunately Java does not come with such a utility method OOTB (like C#'s tryParse). You can enumerate the characters of the string and use the Character.isDigit method (you can even intertwine the verification and the transformation into an int).
Exceptions should be used for abnormal termination of some flow.
Performing an operation that might raise an exception, you should always consider whether you can perform a check that will save you the cost and especially the code for handling an exception. For example- check whether a string is a number instead of trying to parse it and relying on the exception mechanism to tell you if its not.
It's not likely to matter much in the larger context of your application. Micro-optimizations like this are hard to guess at.
A better approach is to write your code as cleanly as possible and then measuring to see what its performance is and where bottlenecks, if any, reside. If you find that your performance is not acceptable, find the biggest bottleneck and address it if you can; rinse and repeat until performance is acceptable.
The problem is that none of us are smart enough to "know" where the problems will be. You're better off optimizing with data instead of guessing.
In your case, that's an unchecked exception. You could ignore it, but that would mean that a single bad string would blow you out of the loop. Putting the catch inside the loop allows you to tolerate that small percentage of input strings that fail the numeric parsing and continue on.
A non-exception based way to check for numeric-only strings would be to user a regular expression. For example:
public static void main(String[] args) throws Exception {
String[] array = {
"abc",
"123",
"12A",
};
Pattern p = Pattern.compile("\\d*");
for (String s: array) {
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(s);
}
}
}
Exception based handling can be expensive.
Regular expressions are not the fastest either.
Try both and see which is faster for you.

Is it good practice to use the xor operator for boolean checks? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write
if (boolean1 ^ boolean2)
{
//do it
}
than
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.
I'm curious as to the best practices regarding the usage of the ^ operator.
You can simply use != instead.
I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.
I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.
My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.
As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.
I think it'd be okay if you commented it, e.g. // ^ == XOR.
You could always just wrap it in a function to give it a verbose name:
public static boolean XOR(boolean A, boolean B) {
return A ^ B;
}
But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.
You can also use XOR to swap the values in two variables without using a third temporary variable.
// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;
Here's a Stackoverflow question related to XOR swapping.
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
IMHO this code could be simplified:
if(boolean1 != boolean2)
{
//do it
}
With code clarity in mind, my opinion is that using XOR in boolean checks is not typical usage for the XOR bitwise operator. From my experience, bitwise XOR in Java is typically used to implement a mask flag toggle behavior:
flags = flags ^ MASK;
This article by Vipan Singla explains the usage case more in detail.
If you need to use bitwise XOR as in your example, comment why you use it, since it's likely to require even a bitwise literate audience to stop in their tracks to understand why you are using it.
I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.
If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".
For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:
if (isDifferent(boolean1, boolean2))
{
//do it
}
Your "isDifferent(boolean1, boolean2)" function would look like:
private boolean isDifferent(boolean1, boolean2)
{
return boolean1 ^ boolean2;
}
Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!
If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?
The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.
public static boolean xor(boolean a, boolean b) {
return (a && !b) || (b && !a);
}
As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.
My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write "to the rivers of belief" here :) ).
!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.
str.contains("!=") ^ str.startsWith("not(")
looks better for me than
str.contains("!=") != str.startsWith("not(")

Categories