Is there a max length for class/method/variable names in Java? the JLS doesn't seem to mention that. I know very long names are problematic anyway from code readability and maintainability perspective, but just out of curiosity is there a limitation (I guess class names might be limited by the file system maximal file name limitation).
ANSI standard recognizes a length of 31 characters for a variable name. However, the length should not be normally more than any combination of eight alphabets, digits, and underscores.
It is 65535 characters to be exact. The same rule applies to the length of the class level variables as well (but not to the local variables - the one which is defined inside a method).
It doesn't matter.
It causes a negligibly small performance difference in practise, but only when declaring the variable. Afterwards, it gets a specific address in the memory, and it is referred as this address, not the variable name, so it won't affect the performance anymore.
As long as necessary. – CodesInChaos Show activity on this post. There's no set length which can be said to be the ideal length for a variable name (in Java or in any other language, pretty much). There are, however guidelines you can use when deciding:
length vs length() in Java. array.length : length is a final variable applicable for arrays. With the help of length variable, we can obtain the size of the array. string.length() : length() method is a final variable which is applicable for string objects. length() method returns the number of characters presents in the string. length vs length()
the length of a variable name can be a 32 bit integer number. Which number is the maximum the compiler will allow is open to experimentation. 65535 - A-OK! 65536 - Oh no!
Technically, the Java language spec doesn't have an upper limit for identifier length. This is a limitation of your JVM implementation. Cheers! Sun's compiler apparently doesn't conform to the spec. java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.8 says: "An identifier is an unlimited-length sequence..."
If I'm not mistaken, the limit is not in the language itself but in the classfile format, which limits names to 64k, so for all practical intents and purposes identifier length is not a problem. Specifically, this is the definition of a constant string in the pool, which seems to imply the maximal length is 16 bit:
CONSTANT_Utf8_info { u1 tag; u2 length; u1 bytes[length]; }
Class names may be more of an issue for file systems, I agree, I'm not sure what's currently supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With