[675] in java-interest

home help back first fref pref prev next nref lref last post

Java compiler is trying too hard for me (fwd)

daemon@ATHENA.MIT.EDU (Gary Joseph Bowdridge)
Wed Jul 12 21:10:05 1995

From: grover@ra.isisnet.com (Gary Joseph Bowdridge)
To: java-interest@java.sun.com
Date: Wed, 12 Jul 1995 20:46:55 -0300 (ADT)


> Hi,
> 
> The Java compiler "javac" won't let me do the following type of code:
> 
>    class smartjavac {
>       public void init() {
>          int x;
>          for (int i=0; i<3; i++) {
>             if (i == 0)  x = i;
>             else if (i == 1)  x = i;
>             else x = i;
>          }
>          System.out.println("ValueOfX is " + x );
>       }
>    }
> 
> The compiler print out the following message and won't generate 
> any class code.
> 
>    smartjavac.java:9: Variable x may not have been initialized.
>            System.out.println("ValueOfX is " + x );
>                                             ^
>    1 error
> 
> I've tried several compiler options including "-nowarn", but got the
> same result.
> 
> Any fix for this problem?

  The compiler does not know that x is SURE to have a value assigned to
in at the point where it's value is used (the println line)

  Instead of just declareing x, declare and initilize it with:

int x=0;

  I don't know why variables don't initilize to "0" or null when
declared, but they don't, so you have to make certain that you
have all variables initilized before using them... doing this in
an "if" block is not good enough.. Even though you have if/else
and x WILL be defined in one of them, i assume the compiler can't
be bothered to check into such detail.

___
_gary_
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post