33

Is it possible to define a function within a function in Java? I am trying to do something like:

public static boolean fun1()
{
  static void fun2()
  {
     body of function.
  }
  fun();
  return returnValue;
}

but I am getting error Illegal start of expression.

8
  • 4
    what are you trying to accomplish that need nested methods? Aug 17, 2011 at 18:01
  • the code of function2 appears three times in fun1 in my code (It is an big function for matching stock-exchange orders(my school assignment))and it uses many local variables of fun1. Aug 17, 2011 at 18:13
  • so what is the problem with having two non-nested methods? Then just call function2 as many times as you want inside function1 Aug 17, 2011 at 18:14
  • 1
    @Hunter if i define fun2 outside of fun1 then it will not be able to modify variables of fun1. when i compile it will give an error that cannot find symbol <variable name> Aug 17, 2011 at 18:39
  • 1
    @Harsh, just pass the variables you need as arguments to function2 Aug 17, 2011 at 18:58

2 Answers 2

50

The reason you cannot do this is that functions must be methods attached to a class. Unlike JavaScript and similar languages, functions are not a data type. There is a movement to make them into one to support closures in Java (hopefully in Java 8), but as of Java 6 and 7, it's not supported. If you wanted to do something similar, you could do this:

interface MyFun {
    void fun2();
}

public static boolean fun1()
{
  MyFun fun2 = new MyFun() {
      public void fun2() {
          //....
      }
  };
  fun2.fun2();
  return returnValue;
}
0
45

You cannot (and in Java they are called methods).

You can, however, define an anonymous class inside of a method, and call its methods.

4
  • 6
    As I see it, there is a difference between methods and functions, while functions live by themselves, methods are related to class or object.
    – MByD
    Aug 17, 2011 at 18:01
  • 2
    The clarification is useful since all java documents use this notion. Harsh (or anyone else) will find answer to future questions about methods easier with correct naming.
    – rics
    Aug 17, 2011 at 18:07
  • 1
    He can, but not in static stackoverflow.com/questions/5388584/… Sep 7, 2016 at 13:59
  • 3
    @YoushaAleayoub - Thanks, this answer was given before Java 8, and now we got lambdas :)
    – MByD
    Sep 7, 2016 at 15:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.