[JAVA rookie] ask questions about variables that didn't get the wrong result at the beginning.

the code is as follows:

package com.helloworld;


public class HelloWorld {
    
    public static void main(String[] args) {
        
        int index;                //index
        
        for (int i = 0 ; i < 10 ; iPP) {
            
            if (i == 5 ) {
                index = i;     //i5index
            }
        System.out.println("index" + index);    
            //
            //index
        }
        
    }
    
}
The

error will disappear only if the initial variable declaration is changed from int index to index index = 0.
but I don"t understand this. I clearly assigned a value in it, why is it wrong?

Jul.12,2022

is a compilation error if "it is possible" is not assigned. That's enough control flow analysis for the compiler


(1) in java, the member variables of the class can be used directly without initialization, and JVM will initialize automatically. The original variables, such as int char short long byte initialization, float double initialization, 0.0prima Boolean initialization, false initialization, object initialization, null.

(2) the variable in the method is a local variable, JVM will not assign a default value to it, the local variable must be assigned an initial value, otherwise it will be prompted for a compilation error.

class A{
    int i;  //JVM0
    public static void main(String[] args) {
        int j = 0; // 
    }
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c5a9-2bb53.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c5a9-2bb53.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?