The local variable is not initialized, but the program still compiles

public class Test {

   public static void main(String[] args) {
       System.out.println("started");
       //func();

   }

   static void func(){
       double d;
       int i;
       System.out.println("d ="+d);
       System.out.println("i ="+i);
   }

}

What I know are local variables that must be initialized before they are used. Here dand iare local variables. You can see that I did not initialize them. Why can I still compile the program and execute it?

If I disable func (), I get a compilation error.

+4
source share
2 answers

If you use javacto compile it, it does not compile:

stephen@blackbox tmp]$ cat > Test.java
public class Test {

   public static void main(String[] args) {
       System.out.println("started");
       //func();

   }

   static void func(){
       double d;
       int i;
       System.out.println("d ="+d);
       System.out.println("i ="+i);
   }

}
[stephen@blackbox tmp]$ javac Test.java 
Test.java:12: error: variable d might not have been initialized
       System.out.println("d ="+d);
                                ^
Test.java:13: error: variable i might not have been initialized
       System.out.println("i ="+i);
                                ^
2 errors
[stephen@blackbox tmp]$ 

, IDE, - IDE, , . "" -, . , ... ... .

, . IDE .


. .

+4

. :

Test.java:12: error: variable d might not have been initialized
   System.out.println("d ="+d);
                            ^
Test.java:13: error: variable i might not have been initialized
   System.out.println("i ="+i);
                            ^
2 errors
+1

Source: https://habr.com/ru/post/1613601/


All Articles