-1
// Simple program to understand pass by reference 
import java.util.*;
public class HelloDate {
    public static void main(String args[])
    {
         class Number                     // Contains only an integer
         {
             int i;
         }
         static void f(Number k)           // <<--- Illegal start of expression ???
         {
             k.i = 22;
         } 
         Number n1 = new Number();        // New object of Number
         n1.i = 9;
         f(n1);                           //Passing an object
         System.out.println(n1.i);        // Print
      }
    }  

The code is showing an error on static void f(Number k). Should I put the method void f() in a class? If yes, why is that necessary?

glglgl
  • 89,107
  • 13
  • 149
  • 217

4 Answers4

5

Methods have to be members of classes, they can only be placed in the body of a class.

AdamSpurgin
  • 951
  • 2
  • 8
  • 28
0

It is not valid to nest methods within other methods but you can define a inner class withing a method and gain a similar effect. This previous thread has some great examples.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

Problem is, you have a method f() directly inside another method main().

rocketboy
  • 9,573
  • 2
  • 34
  • 36
0

When you put a class in a method, it is called a local class, whose scope is only in the method.

     class Number // local class
     {
         int i;
     }

However, you cannot put a method directly in another method. You can only put a method in a class. Take your code as an example, you can put f either in HelloDate or Number.

If you put f in HelloDate, you need to put Number in HelloDate, too. Otherwise, the argument of f, Number k, will refer to java.lang.Number instead of the Number defined in main.

johnchen902
  • 9,531
  • 1
  • 27
  • 69