Re: public static final - compilation error



Kamil Roman wrote:
Hi,
Hi!

is it possible to initialize a public static final member of a class in the class' constructor? I try to do this and I receive error message:

variable PLUS is declared final; cannot be assigned.

The code is:

public class Stale { public static final String[] OPERATORS = new String[] {
new String("+"),
new String("-"),
new String("*"),
new String("/"),
};
public static int PLUS; //final
public static int MULTI; //final
public static int MINUS; //final
public static int DIVIDE;//final
public Stale()
{
for (int i = 0; i < OPERATORY.length; i ++)
{
if(OPERATORY[i].equals("+")) PLUS = i;
if(OPERATORY[i].equals("-")) MINUS = i;
if(OPERATORY[i].equals("*")) MULTI = i; if(OPERATORY[i].equals("/")) DIVIDE = i;
}
}
}


--
Thanks for help
KR

No, you can't initialize 'static final' things in a constructor or any non-static method. But you can (and probably want to) initialize them in the class initializer:


  static
  {
    for (int i = 0; i < OPERATORY.length; i ++)
    {
        if(OPERATORY[i].equals("+")) PLUS = i;
        if(OPERATORY[i].equals("-")) MINUS = i;
        if(OPERATORY[i].equals("*")) MULTI = i;
        if(OPERATORY[i].equals("/")) DIVIDE = i;
    }
  }

Hence, there is no need for your constructor anymore.

--
"Thomas:Fritsch$ops:de".replace(':','.').replace('$','@')

.



Relevant Pages

  • Re: Using XML Tag in C# to create Intellisense in my DLL
    ... public static int file_master_list(ref SqlConnection ... panConnection, int source_id, string frequency_cd, string ... The xml file that gets created has none of the xml I typed in my source ...
    (microsoft.public.dotnet.languages.csharp)
  • Using XML Tag in C# to create Intellisense in my DLL
    ... public static int file_master_list(ref SqlConnection ... panConnection, int source_id, string frequency_cd, string ... The xml file that gets created has none of the xml I typed in my source ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: End of String
    ... There are times, though, when your "string" won't be a String, but rather an array of char in a buffer that you read from some low-level source. ... public static int strlen ... private static void init ...
    (comp.lang.java.programmer)
  • Re: Splitting a String
    ... public static int[] SplitBarCode(string barcode) ... // Split the string. ... Ludwig Stuyck ...
    (microsoft.public.dotnet.languages.csharp)
  • public static final - compilation error
    ... I try to do this and I receive error message: ... public static int PLUS; //final ... public static int MULTI; //final ...
    (comp.lang.java.help)