The following code will not compile n i'm a little stuck as to why -

public class Question8{

    static final int ROW_SIZE = 10;
    static final int COL_SIZE;

    public static void main(String[] args){
        COL_SIZE = 10;
        ROW_SIZE = ROW_SIZE + 10;
    }
}

Dani AI

Generated

: the compile problem comes from how Java treats final fields and when they must be initialized. pointed in the right direction; the clarified rules below explain why the original assignments in main fail and show safe fixes.

A static final that has no initializer is a "blank final" and must be given exactly one value during class initialization (either at the declaration or inside a static initializer). Assigning a static final inside a regular method (such as main) does not meet the definite-assignment requirement and will produce errors like variable … might not have been initialized or cannot assign a value to final variable …. Likewise, once any final has been initialized, any attempt to assign it again is a compile-time error.

Two straightforward corrections:

static final int COL_SIZE;
static {
    COL_SIZE = 10;   // valid: assigned during class initialization
}

or, if the value must change at runtime, remove final:

static int rowSize = 10;  // mutable, can be updated later
rowSize += 10;

If the intention is a compile-time constant, compute it at declaration:

static final int ROW_SIZE = 10 + 10;  // constant assigned once

Diagnostics: compile with javac and read the exact error lines — they point to either an uninitialized blank final or an illegal reassignment. 's different result means the source used there likely differed; the compiler output is the authoritative indicator of the problem.

Recommended Answers

All 3 Replies

I'm not sure. I was able to compile without any errors.

static final int ROW_SIZE = 10;
static final int COL_SIZE;

You are declaring ROW_SIZE AND COL_SIZE as final ....
when a variable is declared as final ... its value cant be changed at any stage of the program. And you are changing the values of both .. so it wont compile.

yeah . . .

what nanosani said. When you declare a variable as a final, that variable cannot be changed - ever (well until the garbage collector comes to get it).

You must give a value to a final variable when you declare it. Otherwise, you cannot re-assign it later.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.