What are the maximum number of modifiers, a java method can contain?

633 Views Asked by At

There are several modifiers used before declaring a java method such as public, static, synchronized etc.

I just want to know the maximum numbers of modifiers or all the combination of modifiers a java method can contain.

2

There are 2 best solutions below

7
GhostCat On BEST ANSWER

See the Java language spec, chapter 8.4:

MethodDeclaration:
  {MethodModifier} MethodHeader MethodBody

and:

 MethodModifier:
 (one of) 
 Annotation public protected private 
 abstract static final synchronized native strictfp

You can't mix:

  • the access modifiers (so you got one of those 3, or none for package protected)
  • abstract, static, final
  • abstract with (private, static, final, native, strictfp, synchronized)
  • and finally: native and strictfp

Taking all of that together (thanks to user Andreas for the excellent wording):

Using regex syntax, we get to:

 [ public | protected | private] static final synchronized [native | strictfp]

So, the maximum number is 5; and 6 different combinations of those 5 keywords.

3
Andreas On

According to the Java spec, §8.4.3. Method Modifiers, the total list of modifies are (not counting annotations):

public protected private
abstract static final synchronized native strictfp

public, protected, and private are mutually exclusive, though that section doesn't say that.

The spec also says:

It is a compile-time error if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, strictfp, or synchronized.

So if you include abstract that only leaves public | protected, so max of 2.

The next rule in the spec says:

It is a compile-time error if a method declaration that contains the keyword native also contains strictfp.

So, this means that without abstract, you can mix as follows:

public | protected | private
static
final
synchronized
native | strictfp

Max length of 5, and there are 3 * 2 = 6 combinations with that length.