Quoted from one of the question from JQPlus: public class SubstringTest { public static void main(String args[]) { String String = "string isa string"; System.out.println(String.substring(3, 6)); } } Using String as a variable name is OK while String is also a class name. I am confused!
You aren't allowed to use any of the reserved words as identifiers. You can use most any other word. After compilation, the bytecode doesn't remember what you originally named your identifiers - the compiler makes up its own names (so to speak). By using common class names as identifiers, you're more likely to confuse yourself than the compiler.
The above code works fine . The variable "String" is good as any other varibale. I slightly modified the above code to below. public class SubStringTest { public static void main(String args[]) { String String = "string isa string"; String s1 = String; System.out.println(String.equals(s1)); //true System.out.println(String.substring(3, 6)); //ing System.out.println(s1); //string isa string } }
Here, its allowing us to do anything , as we do with any other String variable... no obnormal behavior. But, I tried the same with int. /////////////////// int int x=100; System.out.println(int); The above code gives me all kinds of compilation errors. So, this opppeses your explanation. We are not supposed to use the keywords/reserved words as identifiers. I guess, there must be some other reason for the success of the line. //String String = "string isa string"; Can you please look into it?? [ June 15, 2002: Message edited by: Murthy Ram ]
oops!! sorry for the typo.. What I meant was, we are not allowed to use String, int, float as identifiers. But, how the above the code works with String , not with int, or float,or char.. thanks
Murthy, Reason : int is a keyword, String not. Therefore you can use String,Float,Byte as a variable name, but using char,float,byte as a variable name will give an error. Jamal Hasanov www.j-think.com
Hi Murphy, I don't know why Sun allows such a mess. If we define a class and one of its method is public String subString(int a, int b) and we use String as a variable name of its object,when we call String.subString(4,10). Then we can predict what could happen.
Alan, It would be very difficult for the compiler if every class name can't be a identifier. Take a look at the API Specs and you'll see why. In your scenario, I think Java will generate a compiler error because it cannot determine which String class to use. You should use the fully qualified name for the class you wanna use (ex. java.lang.String). [ June 16, 2002: Message edited by: Paul Villangca ]