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>");
		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");
		Simplegui simple = new Simplegui();
		simple.setSize(secondArg, firstArg);


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 :)

6 Years
Discussion Span
Last Post by Bladtman242

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.

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

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 :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.