-1

I'm new to Java and have been practising programming within the Eclipse IDE. I have the following code:

public static void main(String[] args) {
    
    public double absoluteValue(double n) {
        if (n < 0) {
            return -n;
        } else {
            return n;
        }
    }
    
    System.out.println(absoluteValue(-5));
}

I tried to create a method absoluteValue() which returns absolute values. However, Eclipse threw a bunch of errors at me.

I managed to get my code to work when I defined absoluteValue() outside of the main method (had to define it as public static double absoluteValue(double n) though) and called it within the main method.

But I was just wondering why the above code doesn't work. Can you define methods within the main method (if so, should you)?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

3

Java does not allow nesting of methods of this sort. You can have lambdas inside of a method but you can't define a full method inside of a method. This is an important difference for Pythonistas to know.

ncmathsadist
  • 4,684
  • 3
  • 29
  • 45
  • 1
    *"This is an important difference for Pythonistas to know."* And schemers, and js-ers, and... :) – Federico klez Culloca Apr 27 '22 at 17:05
  • 1
    Unless... lambdas :-) – Jim Garrison Apr 27 '22 at 17:10
  • You could define a local class inside a method though, and since Java 17 (I think), local classes allow static methods... It is a dirty trick, but an option to define a full-fledged method inside a method. However, to be clear, it is better to write "normal" Java and not try to write Python in Java. – Mark Rotteveel Apr 27 '22 at 17:15