so8857
so8857

Reputation: 351

Why must some variables be initialized with a value (e.g. 0, null)?

Why do some strings (e.g. topStudent1) have to be set to null, while others (e.g. name1) do not, in order to avoid a compiler error? Why do some doubles (e.g. highScore) have to be set to 0, while others (e.g. score1) do not, in order to avoid a compiler error?

public class Exercise05_09 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number of students: ");
        int numOfStudents = input.nextInt();

        String name1;
        String name2;
        String topStudent1 = null;
        String topStudent2 = null;
        double score1;
        double score2;
        double highScore = 0;
        double nextHighScore = 0;
        int count = 2;

    while (count <= numOfStudents) {
        if (count == 2) {
        System.out.println("Enter a student name: ");
        name1 = input.next();
        System.out.println("Enter a student score: ");
        score1 = input.nextDouble();
        System.out.println("Enter a student name: ");
        name2 = input.next();
        System.out.println("Enter a student score: ");
        score2 = input.nextDouble();
                if (score1 > score2) {
                    highScore = score1;
                    topStudent1 = name1;
                    nextHighScore = score2;
                    topStudent2 = name2;
                }
                else {
                    highScore = score2;
                    topStudent1 = name2;
                    nextHighScore = score1;
                    topStudent2 = name1;
                }
        }
        else {
            System.out.println("Enter a student name: ");
            name1 = input.next();
            System.out.println("Enter a student score: ");
            score1 = input.nextDouble();
                if (score1 > highScore) {
                    nextHighScore = highScore;
                    highScore = score1;
                    topStudent2 = topStudent1;
                    topStudent1 = name1;
                }
                else if (score1 > nextHighScore) {
                    nextHighScore = score1;
                    topStudent2 = name1;
                }
        }
       count++;    
    }
    System.out.printf("Top two students:\n%s's score is %3.1f\n%s's score is %3.1f\n", topStudent1, highScore, topStudent2, nextHighScore);
     }
}

Thanks!!

Upvotes: 4

Views: 134

Answers (6)

Andreas
Andreas

Reputation: 159096

All variables must be definitely assigned (JLS §16) before they are accessed, and the compiler verifies this:

Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.

Since the while loop may not execute at all (e.g. user enters 1), the use of the 4 variables (e.g. topStudent1) in the printf statement requires that the variables are initialized outside the while loop.

Such initialization doesn't have to be on the declaration line, but doing it there is simpler.

In contrast, the other variables (e.g. name1), are not used after the while loop, but only inside the loop, and are definitely assigned right before they are used.

Upvotes: 6

Erick G. Hagstrom
Erick G. Hagstrom

Reputation: 4945

Let's look at the program the way the compiler would (in a highly simplified manner, of course). The first thing we see is variable declarations, some of which initialize their variables.

After that is a while loop. The general rule is that a while loop executes an unknown number of times, including zero. So we have to assume that it's possible it will not execute at all, meaning that any variables assigned within it may not be assigned at all.

Finally we have an output statement that uses four of your variables: topStudent1, topStudent2, highScore, and nextHighScore. These are precisely the ones that you found needed to be initialized. (Actually, they just need to be assigned somewhere before this statement.)

So what's going on? Since the compiler knows it will need a value in each of those four variables to support the printf, it needs to guarantee that those variables have been assigned somewhere. Assigning inside the while loop doesn't count, since (as far as the compiler knows) the while loop won't execute at all. If you don't initialize them when you declare them, and you don't assign them in a way that the compiler recognizes will always happen between declaring them and using them, the compiler takes the conservative view and decides that they might be uninitialized.

Upvotes: 2

Vishal Gajera
Vishal Gajera

Reputation: 4207

There is a standard Rules is ,

Local Variable/Instance ( which is declare inside method ) must be initialized before use it.

so far, before use it must need to initialize it either by 0 or some value or by null.

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35011

members of the class (both static and dynamic) are assigned default values if you do not assign a value directly in the code where you define them. Parameters and variables in a method, however, are not assigned default values and need to be set to something (default value or other) before using

Upvotes: 1

Ronan
Ronan

Reputation: 613

this is because the ones you are required to set are in if and else blocks the compiler isn't sure whether they will be initialized so to stop an error it forces you to initialize them. The ones that don't require initialization are outside the if/else so they will be declared. I hope that helps

to clarify the compiler can see if they will definitely be initialized through your logic and if there is only a chance of it happening it will make sure it won't throw a null by forcing your to declare it.

Upvotes: 1

The reason is quite simple, you need to garante that some values you use are not going to explote your app because are not initialized Exception.

HOW?

like this:

when you do this:

 System.out.printf("Top two students:\n%s's score is %3.1f\n%s's score is %3.1f\n", topStudent1, highScore, topStudent2, nextHighScore);

then you are using the variables and passing those as parameters, but they are not initialized, so the method printf, has no idea about what is goint to print at compiling time, therefore they must be initialized to something (in this case null can be accepted too).

Upvotes: 1

Related Questions