2

Is there a limit to how many fields can be declared in a Java class? This question addresses the number of arguments of a method, but I am curious knowing if a Java class has any limit, and what is this limit.

This is just out of curiosity - I wouldn't actually declare a class with thousands of fields.

Community
  • 1
  • 1
Yassine Badache
  • 1,587
  • 1
  • 11
  • 30
  • This almost certainly doesn't answer your question, but a hard limit would be the maxing out available heap space with one instance xD – Neil Locketz Sep 27 '16 at 14:40
  • 1
    Why you are so interested on how many fields it is possible to declare in a class? If you need to have thousands of fields probably you don't need different names for them but you will use a collection or array to store their values accessing them by index. – Davide Lorenzo MARINO Sep 27 '16 at 14:42
  • Added some precisions in my edit. It is just a curiosity. – Yassine Badache Sep 27 '16 at 14:43

2 Answers2

8

Exactly 65535, not counting the inherited fields.

From Limitations of the Java Virtual Machine:

The number of fields that may be declared by a class or interface is limited to 65535 by the size of the fields_count item of the ClassFile structure (§4.1).

Note that the value of the fields_count item of the ClassFile structure does not include fields that are inherited from superclasses or superinterfaces.

Tunaki
  • 116,530
  • 39
  • 281
  • 370
4

Yes, 65535. It is explained here https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.11

The relevant part is:

The number of fields that may be declared by a class or interface is limited to 65535 by the size of the fields_count item of the ClassFile structure (§4.1).

Note that the value of the fields_count item of the ClassFile structure does not include fields that are inherited from superclasses or superinterfaces.

uoyilmaz
  • 2,855
  • 11
  • 25
  • 1
    Please add exact quote: "The number of fields that may be declared by a class or interface is limited to 65535 by the size of the fields_count item of the ClassFile structure" – talex Sep 27 '16 at 14:44
  • Isn't giving the link to the source material serving the same purpose? – uoyilmaz Sep 27 '16 at 14:46
  • 1
    Not exactly. External resource may be damaged or inaccessible so it is better to have real answer inside your answer. Just imagine that oracle will be sold as IBM was and URL get replaced. – talex Sep 27 '16 at 14:49