• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

identifier

 
Jian Yi
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why does this code even compile? Isn't String a keyword? Isn't it true that a keyword can't be used as an identifier?
thanks,
Jenny
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jenny Yin:
Isn't String a keyword? Isn't it true that a keyword can't be used as an identifier?
thanks,
Jenny

String is not a keyword - it's the name of a class. Class names are still legal identifiers in Java. It is true, however, that keywords can't be used as identifiers. For example, you can't use "this" as an identifier.
Corey
[ April 24, 2002: Message edited by: Corey McGlone ]
 
Junilu Lacar
Bartender
Posts: 7606
54
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jenny,
In the code you gave, the local String variable effectively shadows the java.lang.String class. Consider the following code:

This code compiles and produces the output:
footest
5
On line 7, you need to fully qualify the reference to java.lang.String otherwise you will get a compiler error because the compiler will use the local String variable.
Notice the compiler is smart enough (well, actually the guys who wrote the compiler are the smarties) to use the context to recognize that 'String' on line 4 refers to the shadowed java.lang.String rather than the local variable String.
HTH,
Junilu
 
Jian Yi
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Corey,
Thanks for pointing that out.
Junilu,
That's a fun exercise you showed me. Thanks.
-Jenny
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic