Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch off "java: variable might not have been initialized"

Tags:

java

I have the following code:

public static void main( String[  ] args ){
    int begin, end;
    try{
        begin = Integer.valueOf( args[ 1 ] );
        end = Integer.valueOf( args[ 2 ] );
    }catch( NumberFormatException conversion_error ){
        System.out.println( "Not A Number." );
        System.exit( 1 );
    }
    if( begin >= end ){
        System.out.println( "Wrong arguments. (" + begin + " >= " + end + ")" );
        System.exit(1);
    }
    System.out.print( "OK." );
    System.exit(0);
}

When I try to compile it, I get this error.

Error:(13, 13) java: variable begin might not have been initialized Error:(13, 22) java: variable end might not have been initialized

I understand why compiler is warning me, but the very purpose of my code is handling such situations: when variables are not initialized I shut down my program. In such case I never use them.

I think that answer is fairly simple: initialize "begin" and "end" outside "try" block, for example by immediately assigning zeros to them.

int begin = 0, end = 0;

But can I force compiler to just ignore the issue? Is there any way to switch off such inquisitive checks of my code? It's not like there is any technical problem with my program, outside of possibly wrong values of my variables.

like image 735
Daedan Avatar asked Jul 24 '15 02:07

Daedan


1 Answers

No. You can't switch it off. The compiler insists that you don't use uninitialized variables. It is a rule of Java.

You need to fix your code. Specifically, code that depends on the success of code in a prior try block should be inside that try block.

like image 186
user207421 Avatar answered Oct 21 '22 15:10

user207421