Java Quiz – Variable and Package Names

Does the following code compile?

public class Test
{
    private String java = "a test";
    
    public static void main(String[] args) {
        java.lang.System.out.println("hello");
    }
}


The answer to this question is “it depends”. Under JDK 1.4’s compiler this works, but under JDK 1.5 it fails. It also fails under Jikes, so I guess it was a bug in 1.4. I find the interaction between local variable names and package names unfortunate, although quite understandable. I guess the problem I have that there is no syntax to override the interpretation of “java”.

As I like to do these days, I also checked out C#. Csc also reported an error although I found the message somewhat misleading

public class Test
{
    private string System = "odd name";
    
    public static void Main(string[] args) {
        System.Console.WriteLine("hello");
    }
}
Test.cs(31,9): error CS0118: 'System' denotes a 'namespace' where a 'class' was expected

Commenting out the string member variable allows this to compile, so I don’t think the fact the System denotes a namespace is really the issue. It’s really because System denotes a non static variable. Just a minor nit