Skip to content
Advertisement

local variable initialization were wrong java [closed]

I am new to java, why a, b,c initialization are wrong in the following code.

public static void main(String[] args) {

    if (args.length < 2) 
        throw new IllegalArgumentException ("we need 2 argumeents");
    else { 
       int a = Integer.parseInt(args[0]);
       int b = Integer.parseInt(args[1]);
       int c = a+b;
    }
        System.out.println(a + " + " + b + " = " + c);
}

Advertisement

Answer

Java works differently compared to JavaScript. Every {} block has an own variable scope. Variables defined inside a block are not visible outside.

public static void main(String[] args) {
  {
    int x=1;
    System.out.println(x); // prints 1
  }
  {
    int x=2;
    System.out.println(x); // prints 2
  }
  // System.out.println(x); // error: cannot find symbol
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement