-1

When using Eclipse Luna I run into this issue: When I declare a variable outside of the for loop (or another structure), then initialize it within the For loop, upon closing the for loop the value assigned to the variable within the for loop is not carried over.
Perhaps this is how it's supposed to be, but when using Eclipse Juno I don't have this problem.

int sebastian;

for(int i=0;i<8;i++)
{
    sebastian = 5*i;
    System.out.println(sebastian);
}
rirriput
  • 19
  • 1
  • Is the problem the message you used for the summary, shown in the editor and the Problems View, or a different problem you have when you run this code? – nitind Mar 09 '15 at 23:36
  • Do you have an example of some source code demonstrating the problem? The code you've provided doesn't. –  Mar 10 '15 at 19:13

3 Answers3

0

I'm not sure what's wrong there, but it SHOULD be carried over. It looks like it carries over, and when I run it, it carries over.

I ran

public static void main(String[] args) {
    int sebastian = 0;

    for (int i = 0; i < 8; i++) {
        sebastian = 5 * i;
        System.out.println(sebastian);
    }

    // this should print the last value a second time
    System.out.println(sebastian);
}

and my output was

0
5
10
15
20
25
30
35
35 // this is the carry over that shows up
Aify
  • 3,543
  • 3
  • 24
  • 43
0

Local variables do not have default values. When you write int sebastian; in a method, the variable sebastien does not the value 0, rather it is unassigned. You cannot use the variable until it is "definitely assigned". The rules for definite assignment are complicated. It seems clear that the variable will have been given a value in the loop (because the loop repeats 8 times), but that does not meet the rules for definite assignment.

int sebastian;
for(int i=0;i<8;i++)
{
    sebastian = 5*i;
    System.out.println(sebastian);  // sebastien is definitely assigned here. It was assigned the line before!
}
System.out.println(sebastian); // sebastien is not definitely assigned here.

The easiest way round this to just give the variable a "dummy" value when you declare it:

int sebastien = -1; 
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
0

See rules for 'Definite Assignment' in the Java Language Spec. You can't refer to a local variable before it has a value assigned: http://docs.oracle.com/javase/specs/jls/se7/html/jls-16.html

Kevin Hooke
  • 2,583
  • 2
  • 19
  • 33