8

Possible Duplicate:
Max name length of variable or method in Java

I was reading the java docs and it says “A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits … “ in c++ the variable name length is around 255 characters depending on the compiler, so how is this handled in java does the compiler truncate the variable name after x number of characters, and if this is true what would be x ?

Community
  • 1
  • 1
Mike G
  • 4,829
  • 11
  • 47
  • 76
  • Why do you expect the compiler to truncate the string if the documentation tells you that strings can be of arbitrary length? – Kerrek SB Jan 08 '12 at 23:46
  • 2
    @KerrekSB I just dont understand how it can be unlimited what if the variable name alone was 15gb – Mike G Jan 08 '12 at 23:48
  • Maybe the Java compiler comes with an arbitrary-length string class? `BigString` or so... although even the basic string should already be able to grow to a size that's at the order of the addressable machine memory. – Kerrek SB Jan 08 '12 at 23:52
  • 1
    @MikeG: If a variable name requires 15gb to store, then I feel sorry for your keyboard (not to mention your fingers and sanity). I know it's unrelated to the question, but worrying about the limit of the length of a variable name probably means that the name is (just a bit) too long. – AusCBloke Jan 08 '12 at 23:55

3 Answers3

9

According to the class file format spec (under section 4.11):

The length of field and method names, field and method descriptors, and other constant string values is limited to 65535 characters by the 16-bit unsigned length item of the CONSTANT_Utf8_info structure (§4.4.7). Note that the limit is on the number of bytes in the encoding and not on the number of encoded characters. UTF-8 encodes some characters using two or three bytes. Thus, strings incorporating multibyte characters are further constrained.

This applies to local variables as well because of the LocalVariableTable pointing to CONSTANT_Utf8_info values for the variable names.

Michael
  • 41,989
  • 11
  • 82
  • 128
prunge
  • 22,460
  • 3
  • 73
  • 80
  • 2
    but that is not the flimit or a variable length - the compiler can deal with longer names (tested 70000 with java 11) – user85421 Mar 04 '19 at 11:35
2

No one in their right mind should ever come within miles of the limit. You reach a point where it defeats the purpose. You want to choose names that clarify your intent, but that doesn't mean a variable name should rival "Ulysses" in length. The limit has more to do with good taste and readability.

duffymo
  • 305,152
  • 44
  • 369
  • 561
-1

Given that a java.lang.String has a field

private final int count;

to specify the number of characters in it, the maximum identifier length must be no more than

Integer.MAX_VALUE

MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66