How do you go back to a specific line in Java? - 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.

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.

efficient way to compare multiple int values to 0

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.

How to jump in java

I have a code like this
public class Test
{
public static void main(String[] args)
{
continue s;
System.out.println("I am not supposed to print this");
s:
System.out.println("I am suppose to print this");
}
}
I get the error
java: undefined label: s
What is wrong ?
Basically, there is no practical way to do that in Java. You appear to be trying to do the equivalent of a "goto", and that is not supported in Java. The break label and continue label statements can only branch to an enclosing labelled statement.
Now according to the Java formal grammar you could write this:
s: {
continue s;
System.out.println("I am not supposed to print this");
}
System.out.println("I am suppose to print this");
but that still won't compile for two reasons:
The continue is only allowed to branch to a label on a loop statement. (A break doesn't have that restriction ... but ...)
The continue (or a break) makes the next statement unreachable.
See also: Alternative to a goto statement in Java
But there is one rather tricky way to get your code to "work":
static final boolean flag = true; // class attribute ...
...
s: {
if (flag) break s;
System.out.println("I am not supposed to print this");
}
System.out.println("I am suppose to print this");
The "test" there will be evaluated by the compiler so that the break is effectively unconditional. But the JLS says that the first println will be treated as reachable, so that you won't get an unreachable code error.
I guess this might be useful if you are generating this source code. Apart from that, it is (IMO) just a curiosity. It is simpler to do this with a regular if / else statement ... or by deleting the first "print" entirely.
Jumping like this is not possible in Java, only way to jump is from loops, while and do.
What is the "continue" keyword and how does it work in Java?
Read #Heinzi answer
2.2.6 No More Goto Statements
Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.
The Java Language Environment, James Gosling
and Henry McGilton, 1996
There is no "goto" in java. And "continue" does a little bit other function. You can use "continue" for example in loops like:
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
In the example above, if for example searchMe.charAt(5) != 'p' then the loop will continue from the beginning of loop from i=6, and numPs++; will not be processed.
You can read more about this here:
Branching Statements
continue is a keyword in Java used to skip iterations of a loop.
If you are trying to find an equivalent to GOTO, you should reconsidering how you are trying to solve your problem, GOTO is never a valid option, ever.
As far as I know, there is no goto in Java (there is a keyword, but it has no meaning)
Theoretically, Java have Jump statements return and break.
The return statement jumps out of a method, with or without returning values to the calling statement.
The break statement jumps out of loops.
As mentioned in the earlier answers, goto is not available in Java, and is not considered to be a good programming practice in procedural or object oriented programming. It existed back in the days of sequential programming.

Java one line if statement [duplicate]

This question already has answers here:
Is it ok if I omit curly braces in Java? [closed]
(16 answers)
Closed 9 years ago.
I am using if condition without braces in java something like
if(somecondition)
//Only one line Business logic
but some told use braces always even one line statement something like this
if(somecondition){
//Only one line Business logic
}
What is the better way according to java sandard?
there's no real "standard". i prefer always using braces because if you dont you risk someone adding an innocent looking logging statement turning your code from
if(somecondition)
//Only one line Business logic
into
if(somecondition)
log.debug("condition was true");
//Only one line Business logic
and then things stop working :-)
That's a matter of taste. I would use braces or else no braces but write all code in one line to improve readability.
Also you might consider using a ternary operator
booleanExpression ? value1 : value2
In addition to #radai answer, if you are a real evil mind, when you see a if with no braces you can do something that will make you ennemies by adding a semi-colon on the same line of the if but at the 800th column of the line(or something).
like
if(condition) /*a loooot of whitespace*/ ;
//Only one line Business logic that will get executed whatever is the condition
This is why i prefer to use braces and recommend people to use them
No naked if statements. You're just asking for trouble. Always use { }
it is better to use braces when checking for errors or updating the code.
imagine.
if(answer.equals("add"))
addedValue += Scanner.readInt();
but you have a new requirement to add only the absolute value, so you change to.
if(answer.equals("add2))
valueToBeAdded = Scanner.readInt();
if(valueToBeAdded < 0) valueToBeAdded = - valueToBeAdded;
addedValue += valueToBeAdded;
this is not a really correct algorithm, is just an example of what can happens.
Using if statement with braces is better way to java standard, because it increase the readability and reduce unwanted error.
The two statements have exactly the same effect but I have suffered so often from the lack of braces that I also always comment that there should be braces even around 1 line statements. This makes the code easier to maintain and can save a lot of headache. My experience shows that one line if statements often turn into multi-line statements on later iterations so what you save by not writing two { the first time, you will give later on.
According to java standard braces are better because if they are not there compiler has to work around more and also would be performance issue.

What is the most optimized way to use if statements in a loop?

I have a list I need to process. The items are either enabled or disabled. The user can choose whether or not to show disabled items.
So you have cond2 that depends on the items, and cond1 that does not. Here's the dilemma I got into: Should I use cond1 && !cond2 or !(!cond1 || cond2)? Or should I check for the cond2 (show disabled items) before the loop? I also thought (as you will see in the code I put) if I should put the cond2 before cond1, because cond2
is a boolean variable, and with "short-circuits" (lazy evaluation?), it will be faster?
My main concern was speed. If I have many items in the loop, this might be an important change.
This is code that illustrates the options:
// First Option
for (String item : items) {
doSomethingFirst(item);
if (isDisabled(item) && !showDisabled) {
continue;
}
doSomethingElse(item);
}
// Second Option
for (String item : items) {
doSomethingFirst(item);
if (!(!isDisabled(item) || showDisabled)) {
continue;
}
doSomethingElse(item);
}
// Third Option
if (showDisabled) {
for (String item : items) {
doSomethingFirst(item);
doSomethingElse(item);
}
} else {
for (String item : items) {
doSomethingFirst(item);
if (isDisabled(item)) {
continue;
}
doSomethingElse(item);
}
}
So, does the order of isDisabled(item) and showDisabled matter? Should I be checking on things before the loop? Or does the compiler optimize that? (I doubt...)
PS I don't know how I would take measurements to see actual values, if it's relevant please do.
Thanks.
In Java the expression is evaluated from left to right. With && if the first condition is false, the second one is not executed, with || if the first condition is true, the second one is not executed.
So try to put the condition that can be resolve faster in first place, in your case showDisabled.
For the third example, it looks better because you check the boolean only once but I guess it don't really change performance, a bool comparison is not really costly. You will probably have better improvement to do in other part of your code. (and for the readable aspect it's not my favorite - quite long)
If you want to measure the performance in your case use a profiler for example.
Or add in your code :
long start=System.currentTimeMillis();
//code to analyse
long timeSpent = System.currentTimeMillis()-start
You'll have to put your code in a loop, to make it relevant. And you will probably notice that Java will increase the performance after some loops ;).
Regarding readability, another good practice is to name functions and variables in their positive state. It's hard to read double negatives. Which one would you rather read?
enabled
Or
!disabled
There are some few cases though that naming things in their negative form makes sense. An example, if you will use them for terminating condition, e.g. end of file. while(!feof(fp))
But in most cases, the norm should be is to name things in their positive form, so reading code has lesser friction.
Let's see how your code looks like in positive form:
// First Option
for (String item : items) {
doSomethingFirst(item);
// if (isDisabled(item) && !showDisabled) {
if (!isEnabled(item) && showEnabled) {
continue;
}
doSomethingElse(item);
}
The readability on that code surely improved.
And even the following become readable too, the double negatives can be avoided, reading code is really merely reading it, not figuring it out too much. I once read an article that suggest that when writing code, it should be very pleasant to read too, he said reading code should not be like reading a detective novel. Reading double negatives code is like reading and deciphering a detective novel.
// Second Option
for (String item : items) {
doSomethingFirst(item);
// if (!(!isDisabled(item) || showDisabled)) {
// You can now avoid double negatives
if (!( isEnabled(item) || !showEnabled )) {
continue;
}
doSomethingElse(item);
}
In fact, the following is not merely double negative, it's a triple one:
if (!(!isDisabled(item)
isDisabled
!isDisabled
!(!isDisabled
It will take a two-pass read, or even a three-pass before you can decipher what's the intent of that code
As always with these types of questions, you should measure this to determine if this itself is your bottleneck. If it is, then I would measure the alternatives. I suspect for the above scenario that it will make next to no difference for your alternatives, especially since you'll likely be doing something much more heavyweight with the list entries (displaying them? writing them to a db or file?)
The simplest way to measure this is to generate a sizable list, record the time (say, via System.currentTimeMillis()) before you process, process, and then record the ms (or seconds) taken.
Should I use cond1 && !cond2 or !(!cond1 || cond2)? Or should I check for the cond2 (show disabled items) before the loop?
Whatever expresses your thoughts best, i.e. whatever is more readable.
My main concern was speed.
Writing speed? Refactoring speed? Compilation speed? Development speed? Reading and understanding speed? Debugging speed? Execution speed?
You can't have all at once. In no language.
I will go for the option 1, and just reverse switch
isDisabled(item) && !showDisabled
with
!showDisabled && isDisabled(item)
If isDisabled(...) is as slow as you say it is better to test the faster case first.
Now compared to the other option this is the most explicit and readable:
We do something is done for all items
we skip for items which validate some test
we do something for all other items.
It will be difficult to do more explicit. And the 3rd option is plain ugly.

Categories