Hi guys :)
Well I got an "variable might not have been initialized" error when I tried
to compile the following code:

import java.lang.*;

public class NewFrame {
    
	public static void main(String[] args) {

	    if (args.length != 3) {
            System.out.println("Usage: java NewFrame <frame-name> <frame-hight> <frame-width>");
            System.exit(1);
        }
        
		int firstArg, secondArg;

		try {
			firstArg = Integer.parseInt(args[1]);
			secondArg = Integer.parseInt(args[2]);
		} catch (NumberFormatException e) {
				System.err.println("Second and third aguments must be integers");
				System.exit(1);
		}
						
		
		Simplegui simple = new Simplegui();
		simple.setSize(secondArg, firstArg);
		simple.setTitle(args[0]);
        simple.setVisible(true);

    } 
}

The error occurs when trying to use the variables firstArg and secondArg in line 24.
if I initialize them when I declare them in line 12, It compiles and runs correctly.

So should I just do that? Is this one of the rare times when that is okay or is there some workaround I should know about?
Thanks a bunch in advance :)

Since the try statement might fail your variables will not be initialized, just as the compiler states. either you can place the code that uses firstArg and secondArg in the try statement or you can initialize the variables to something.

You could also set firstArg and secondArg to some default value in the catch statement. I know that you call system.exit(1) in the catch statement but the compiler probably doesn't care about that.

Java is quite good at catching errors like this, but try to always initialize variables when you create them to save yourself from headache in the future.

commented: Even though it might be basic stuff to you, it was great help to me :) +2

It somehow puzzles me that the compiler has such extensive capabilities for error handling, and yet it ignores the System.exit(1).
Well anyway, I guess the best thing to do is to use the variables in the try statement.
Thank you very much :)

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.