problem with ObjectInputStream.java

Alex Nicolaou anicolao at mud.cgl.uwaterloo.ca
Thu Feb 4 13:18:19 PST 1999


Archie Cobbs wrote:
> 
> In ObjectInputStream.java, note the double declaration of "Integer key":
> 
> >     case ObjectStreamConstants.TC_CLASSDESC:
> >           ObjectStreamClass cls = new ObjectStreamClass();
> >           currObject = (Object)cls;
> >           Integer key = new Integer(++nextKey);
> >           objectsDone.put(key, currObject);
> >           invokeObjectReader(currObject, ObjectStreamClass.class);
> >           cls.clazz = resolveClass(cls);
> >           cls.buildFieldsAndOffset();
> >           break;
> >
> >     case ObjectStreamConstants.TC_STRING:
> >           currObject = readUTF();
> >           Integer key = new Integer(++nextKey);
> >           objectsDone.put(key, currObject);
> >           break;
> 
> Clearly this makes sense, once you realize that there's no way
> during execution that "key" will be declared twice.

No, this doesn't make sense because braces are the only mechanism in the
language to define variable scope. The fact that you've used a goto
(disguised as a break statement) to jump out of the block doesn't change
the fact that the variable is already declared. Consider the following
(legal!) program:

public class foo {
    public void sw(int x) {
    switch(x) {
    case 0:
        int y = 3;
        break;
    default:
        // uncommenting this line gives an error
        // System.out.println("y = " + y);
        y = 5;
        int z = x;
        break;
    }
    }

    public void main(String[] argv) {
        sw(0);
        sw(1);
    }
}

The above program compiles and is legal unless you try to access y
before it is initialized.

To fix your problem, uses braces in each branch of the switch:

switch(x) {
case 0: 
	{
	int y = 3;
	}
	break;
default:
	{
	int y = 5;
	}
	break;
}

Now the variables in each branch of the switch are in their own blocks
and are unrelated.

alex


More information about the kaffe mailing list