1

In Java 8, there are situations where I would like for the program to point to a specific part of a method rather than at the start of the method, but is there a way to do this?

I know that, for example, I could create a loop with a copy of the section of code I want to repeat, and I could also break the method up into sections such as:

public static void main(String[] args) 
 { //do stuff
  methodA();
 }
public static void methodA()
{
  //do more stuff
 methodB();
}
public static void methodB()
{  
//do some other stuff
if (answer == 1) methodA(); //return to methodA
else System.exit(0);
}

This is a very simplistic example (with obvious code missing, but is just shown to reference) of how I have been going about it, but I would love to be able to insert some kind of label within main and reference to it like a method without having to break up the main method into chunks.

The question is: Is it possible? Or is there some other approach I could be taking?

Also: If this is not available in Java, but is available in some other language, a reference to such a language would be helpful for me to look into.

EDIT: To clarify, I am not specifically looking for a goto() command so please don't assume such in your answers. I also would prefer avoiding a goto() command even if available because anything that points to a line rather than a method will break if I ever add code above it. What I was imagining was more along the lines of this:

public static void main(String[] args) 
 { //do stuff
  label bookmarkA();
   //do more stuff
   bookmarkA();
 }

As you can see, this is declaring where I would be jumping to later and then calling it like I would be calling a method. Based on the answers below, I doubt something like this specifically exists (although I would love it if it did), but it seems that there are some commands to move up or down within a method within some limits.

A good answer might tell me what is possible and at least point me in a direction to properly use it. A good answer might also tell me if something closer to what I want is also available in another language.

Lastly, this is not a duplicate of questions asking for goto() commands because that's not really what I want.

EDIT 2: In case anything about this question is unclear, I am not asking about any SPECIFIC approach to doing what I want, nor am I specifying that I want to begin execution of a method anywhere other than at the beginning of the method I am starting in. I am asking, specifically, what is possible. Please assume that there is only ONE method in use or that everything I would like to happen is in the same method.

As I explained VERY CLEARLY, I already know how to approach the problem with multiple methods, but I wanted to solve the issue within the same method if possible.

Elliander
  • 503
  • 1
  • 9
  • 19
  • Perhaps you should tell us why you want to do this / what you want to achieve – Marged Jun 26 '15 at 05:44
  • 1
    Doesn't using the `return` statement helps you to achieve what you want in this case? – Tagir Valeev Jun 26 '15 at 05:47
  • Having some "methodB" that might conditionally terminate the entire program two levels deep is probably not something most people would characterize as "good design". However, if you *really* want to write in a coding style like 1980's BASIC, you can abuse Java "continue" and "break" like this: [Is thtere a goto statement in Java?](http://stackoverflow.com/questions/2545103/is-there-a-goto-statement-in-java) – paulsm4 Jun 26 '15 at 05:48
  • @Marged It's primarily a complexity issue. On a few occasions I decided later in a project that I needed to bring the user back to just after an initial series of questions were asked, but doing so with methods required that I go back and rewrite a substantial portion of code to use methods and I ended up with a series of bugs to deal with as I took care of passing the variables. In another project I instead nested the entire chunk of code I was working in within a while loop, but I had problems catching improper user input. In either case being able to point to the line would be helpful. – Elliander Jun 26 '15 at 06:16
  • @paulsm4 The program termination is not something I would do, I just wanted to show that I had an understanding of an approach. I have seen too many good questions closed simply because a snippet of code was missing. goto is a good reference. I see many people saying how bad it is, but from my perspective I think it would be better to have 2 lines rather than fragmenting the code or using too many indents. Can you post that as an answer, maybe with a specific explanation or reference? In the link you gave it says it's not used. – Elliander Jun 26 '15 at 06:22
  • 2
    Q: Is there a way (in Java) to go to a specific part of method, rather than start of method? A: [Asaph's response](http://stackoverflow.com/a/31065731/421195): basically, "No". 1) Java doesn't have "Goto". 2) using labels + continue/break is possible - but not recommended. 3) Java [switch/case](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html) might be appropropriate. 4) But breaking your code into separate, discrete modules is almost always "The right thing". Here's why: http://www.drdobbs.com/cpp/what-dijkstra-said-was-harmful-about-got/228700940 – paulsm4 Jun 26 '15 at 19:03

4 Answers4

6

No. Java does not support this. You cannot begin execution of a method at an arbitrary point within the method. Consider breaking your methods down into smaller methods to accomplish your goal.

Update:

What you are essentially asking for is a goto that references a label rather than a line number, such as in the C programming language:

The syntax for a goto statement in C is as follows:

goto label;
..
.
label: statement;

-- http://www.tutorialspoint.com/cprogramming/c_goto_statement.htm

But, even in C where it's supported, using goto is widely considered to be a bad practice. From the same link:

NOTE: Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

-- http://www.tutorialspoint.com/cprogramming/c_goto_statement.htm

Or, more famously see the legendary Go to considered harmful paper by Edsger Dijkstra.

Java does not support goto (although it is a reserved word). The only branching statements supported in java are break, continue and return which are neatly summarized in the canonical java language tutorial.

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • 2
    Indeed, the "other approach" is to refactor the code so that there is no need for a "jump in the middle of the code" need. It's completely a design issue. – Kayaman Jun 26 '15 at 05:58
  • Breaking methods into smaller methods is exactly what I am doing, as I specified. My issue is that this approach introduces far more complexity than is needed. Personally, I don't really care if it's some sort of "taboo". The simplest solutions to the most complicated problems are preferred. As long as I am properly commenting my code for my own future reference it would seem like a good thing. – Elliander Jun 26 '15 at 06:26
  • 1
    @Elliander there is no goto in Java - the only "jumps" you can get are: method calls, return/break/break label/continue/continue label. – assylias Jun 26 '15 at 07:18
  • @assylias Remember, I did not specifically ask for a "goto" command. It may seem like it, but I just wanted a way to move the program focus to a specific point up in the same function. It looks like, based on assorted comments, the answer is that there is a way to do this through specific and limited rules and that, if ever implemented, a goto() command would provide similar functionality that I require. In other words, this answer we are commenting on is incorrect and someone should make a complete answer so that it can be selected as best answer. – Elliander Jun 26 '15 at 09:22
  • 1
    @Elliander This answer is correct. In Java, method execution always begins at the top of the method. **Always**. Period. There is no way to circumvent this using return, break, break label, continue, continue label or any other "specific or limited rules". – Asaph Jun 26 '15 at 14:13
  • @Asaph OK, what part of the question don't you understand? I even edited the question in the hopes of making it more clear. Did I ask to begin execution of a method in the middle? NO! I asked to be able to move UP in the method WITHOUT having to create a new one! If it's possible to do that your answer is incorrect. – Elliander Jun 26 '15 at 17:05
  • @Elliander The title of your question is "Is there a way to go to a specific part of method, rather than start of method?" and the first paragraph is "In Java 8, there are situations where I would like for the program to point to a specific part of a method rather than at the start of the method, but is there a way to do this?". The answer to that is no. You later added edits that contradict the above, such as "nor am I specifying that I want to begin execution of a method anywhere other than at the beginning" Contradicting yourself makes your question *harder* to understand, not *easier*. – Asaph Jun 26 '15 at 17:36
  • @Asaph A title can only provide so much information, which is why I added more details. No, I did not contradict myself because I was VERY FREAKING SPECIFIC about what the situation was. For example, if I have ONLY a main() method I can type in main(); anywhere within main(); to go to the top. However, I wanted to go to another specific part without having to start the entire method over. From what others have said this *IS* possible so arguing with me over my intentions doesn't help anyone. I have not contradicted ANYTHING I said, you just don't seem to care to actually read the question. – Elliander Jun 26 '15 at 23:12
  • @Asaph Seriously, I outlined the background problem, specified the solution I was using, gave an example for the type of functionality I was looking for, and even left it open for some broad answers for alternative approaches. As for "nor am I specifying that I want to begin execution of a method anywhere other than at the beginning" that is NOT a contradiction because a method that is used must be called at least once from the beginning. Your answer suggests that I am never using code before what I am pointing which is not true. I even clarified that the method has run from beginning. – Elliander Jun 26 '15 at 23:17
  • @Asaph even your suggestion "Consider breaking your methods down into smaller methods to accomplish your goal." implies a lack of understanding of what I am asking. If, for example, I specify in the question that I am breaking my methods down into smaller methods, but would like an alternative to use within the same method, it's pretty silly to suggest that. – Elliander Jun 26 '15 at 23:18
  • @Elliander I've updated my answer. I think the gap here is that you claim you're not looking for a `goto`, but in fact that is *exactly* what you're asking for, without realizing it. You want to be able to jump to an arbitrary point in your code using a label (not a line number). This is what `goto` does (as implemented in C). And, as already stated, it's not supported in Java. Additionally, using `goto` is widely considered to be a bad practice. – Asaph Jun 27 '15 at 14:35
  • @Asaph The real issue here is that I am not limiting my potential answers to a specific feature. It's left open ended. Even if goto() is the approach that works best for what I want this answer is still not really accurate. If it is possible to use C code in Java to make use of a feature within a Java project and/or if there are ways of using strictly Java code it becomes largely irrelevant as to if it's actually possible. As for it being considered "bad practice", I don't care. It's just a tool. Yes, people abused that tool, but every tool has both a use and an abuse. – Elliander Jun 29 '15 at 16:58
  • @Asaph In general, I understand why people have created the taboo, but it's wrong. People are focused on the wrong thing. Instead of putting emphasis on code readability they just targeted a specific tool set. They would rather see hundreds of new lines of code instead of just two lines with proper commenting. To me, using too many methods/functions/loops where a single line would be worse than using too many goto() commands because, ultimately, you are using the same line to call to the same thing, except now you have to add additional lines to direct to more and more useless methods. – Elliander Jun 29 '15 at 17:04
0

Assembler is a language that supports such things. In assembler you can either call "functions" or jump to addresses directly.

Here is a made-up example of a function / method:

00000000: mov eax, [ebx]    
00000004: mov [var], ebxvar
00000008: mov eax, [esi-4]
0000000A: mov [esi+eax], cl
0000000C: mov edx, [esi+4*ebx]    
...

On each line you can see the address the code is located at (the stuff before the ':')

You can either do jmp 0 or jmp 000000A, which will lead you to totally different "lines of code". But doing things like that is fragile because you easily mess up your stack for example.

Marged
  • 10,577
  • 10
  • 57
  • 99
  • Not sure if that was supposed to be ironical :-) – assylias Jun 26 '15 at 05:59
  • I was just answering what he asked for. It is up to him to decide if this makes his problem bigger or smaller ;-) Perhaps he should have asked for "high-level language" :] – Marged Jun 26 '15 at 06:03
  • lol. Thanks. I have actually used that in ASM before, I just haven't seen something like that in higher level languages. – Elliander Jun 26 '15 at 06:27
  • @Elliander that sounds interesting. Which assembler by the way ? – Marged Jun 26 '15 at 06:47
  • @Marged To be honest? I don't remember. It was a good 15 to 20 years ago, but the last time I did anything with ASM was when I was studying the .NET languages briefly. I thought it was a very nice feature to be able to use ASM and other languages in the same project so that I can purposefully use features I need which may not be implemented. In any case, to clarify the question, I wasn't specifically asking for a goto() or a jump command. On the contrary, I was imagining something a bit more orderly where the user would have to declare the point that will be jumped to just like a method. – Elliander Jun 26 '15 at 09:29
  • @Marged Wait, I think it was MASM. Ya, I just looked it up and I am fairly certain that MASM is what I used. Or rather some version of it. Since we are on the topic, does Java support any way to make use of ASM? Although personally, the idea of going to or jumping to a specific line seems horrific to me. It would mean that if I ever insert some code above what I am working with I would have to change every use of it. It would make far more sense to have something like: " Label referenceA(); " and then calling referenceA(); as if I was calling a function. That sounds much safer. – Elliander Jun 26 '15 at 09:37
  • @Elliander the good old times of MASM and TASM ... You could perhaps (and I don't say you should ;-)) use a bytecode manipulation framework to achieve what you describe above. There exist some frameworks, one of them is even called ASM ;-) But unless the rest of us didn't understand the "depth" of your approach: don't do such things, simply refactor your methods that their functionality can be called in a fine-grained way. – Marged Jun 26 '15 at 09:41
  • @Marged As for what I am trying to do? In Java, nothing specific. Yet. Although I studied other languages to varying degrees, I never had a formal education in programming so I added computer science as a second major to my genetics major. This class happens to focus on Java which I have never worked in before, but I am required to use specific outputs without deviation so my only chance of learning new things is within the code. Doing the same thing in different ways. I am trying to find cleaner alternatives to what I have been doing because it's much messier than what I am used to doing. – Elliander Jun 26 '15 at 09:58
0

The best approach is to break your methods into smaller methods. Then you can call the part you need without any convolutions.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
-1

Based on the comments received so far, this is possible with limitations.

1.) The goto() approach does not function in Java 8. Of course, that wouldn't be a solution to the problem anyway because pointing to a specic line can cause problems if anything is ever added above such a reference later. The alternative idea also does not appear to exist.

On the other hand, limited functionality of goto() in java was implemented by this approach.

2.) As another has pointed out, the method has to run from the beginning at least once. Of course, since the question is focused on trying to solve the problem without creating additional methods this should go without saying. The method is already running and I only want to move up within the same method.

3.) The available functionality seems to be limited to break, break , continue, continue . Although I have not received more details, it seems to be a good direction to go from for trying to approach my problem with.

4.) It also appears to be possible to make some use of assembly within Java. You can apparently call C code via JNI and use the C code to call assembly which would allow for the goto() functionality if absolutely needed. Since the assembly instructions would be kept separate, likely in it's own class, it shouldn't lead to spaghetti code and would avoid some of the issues of using goto() normally.

I prompted for others to create such a listed answer, but no one has so I felt it necessary to answer it myself to avoid misinformation to be passed to others. If, however, someone has a more complete answer within the next few days I will select their answer as the best.

Elliander
  • 503
  • 1
  • 9
  • 19