4

Is there any limit on number of Java classes(Both Public and Non Public) that can be put in a Java Package?

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • 1
    Possible duplicate of [how many classes per package? methods per class? lines per method?](https://stackoverflow.com/questions/312642/how-many-classes-per-package-methods-per-class-lines-per-method) – John Joe Jul 26 '17 at 02:40
  • @JohnJoe Not a duplicate. The other question asked for recommended limits, not absolute limits. – Ellen Spertus Jul 26 '17 at 02:51
  • 1
    This is a worrying question. – shmosel Jul 26 '17 at 02:54
  • @shmosel How come? – Ellen Spertus Jul 26 '17 at 02:56
  • @EllenSpertus Why would he need to know? – shmosel Jul 26 '17 at 02:57
  • @shmosel I don't really care why the poster would need to know, but I can imagine reasons, such as if he is creating an automated process (such as a parser generator) to create classes, or maybe he just likes to know limits. – Ellen Spertus Jul 26 '17 at 03:01
  • There is no limit in the specification, so you can put classes into the package until hitting a technical limitation. If not hitting a limit at the file system or archive format, the runtime implementation likely uses arrays or collections to hold the classes, which limits the number to something close to 2³¹. You may hit memory limitations before… – Holger Jan 03 '18 at 15:25

1 Answers1

2

tl;dr: the value is implementation-dependent since it's not defined anywhere in the JVM or Java spec.

Practically speaking, it could be somewhere between maxUint16 and maxUint64.


There many limits due to the nature of JVM, but classes and packages count is not one of them.

I find this sentence from a Java spec worthwhile in this context (source 7.2):

For example, a system that uses a database to store packages may not enforce a maximum of one public class or interface per compilation unit.

It does encourage JVM implementation to avoid such a limit even if it uses something other than a file system for storing compilation artifacts like packages and classes.

As noted in one of the comments to your question, there can be technical limits, but they're probably high enough for most use cases. It can also vary a lot depending on the implementation you're using. That being said, you probably can have millions of packages and classes without any issues.


For completeness and reachability, I'll inline a @Holger comment here:

There is no limit in the specification, so you can put classes into the package until hitting a technical limitation. If not hitting a limit at the file system or archive format, the runtime implementation likely uses arrays or collections to hold the classes, which limits the number to something close to 2³¹. You may hit memory limitations before…