Writing a function inside the main method - Java

Viewed 78768

Can you write a method inside the main method? For example I found this code:

public class TestMax {
    public static void main(String[] args) {
    int i = 5;
    int j = 2;
    int k = max(i, j);
    System.out.println("The maximum between is " + k);
}

 public static int max(int num1, int num2) {
    int result;
    if (num1 > num2)
       result = num1;
    else
       result = num2;

    return result; 
  }
}

Can the method max be coded inside the main method?

7 Answers

No. One cannot directly define method in methods in java. Except special conditions, like pre declared methods in inbuilt classes. The preferable method is define method in same class and ofcourse call it.

Related