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.
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.
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:
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.
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 keywordsprivate
,static
,final
,native
,strictfp
, orsynchronized
.
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 containsstrictfp
.
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.