public static int Count( ArrayList<Student> studentList )
{
int j = 0;
for( Student s : studentList )
{
j = j++;
}
return j;
}
What am I doing wrong?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
public static int Count( ArrayList<Student> studentList )
{
int j = 0;
for( Student s : studentList )
{
j = j++;
}
return j;
}
What am I doing wrong?
Why do you think the value of j is changed from 0? Add some println statements to see what is happening.
What is in studentList? Is the code in the loop ever executed?
What is the value of j in the loop?
Please edit your post and wrap your code with
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.
If you don't understand my answer, don't ignore it, ask a question.
Four common ways to increment the value of the variable j: in memory:
j = j + 1;
j += 1;
j++;
++j;
Your statement in the loop is none of these. It is:
j = j++;
This has the following effect:
Since the ++ operator has higher precedence than the '=' operator, it evaluates the expression on the right of the '=' first, then it stores the value of the expression in memory:
So, here's the drill:
- Evaluates the expression j++. The value of the expression is the previous value of the variable j in memory
- This particular expression has a side-effect: It increments the value of j in memory (after the expression has been evaluated) and, therefore, stores the incremented value in memory. At this point you have incremented the value of j
However...
- Then, applying the '=' operator, it stores the previously obtained value of the expression in memory, thus overwriting the incremented value that you just stored, with the old value.
Bottom line: It stores the old value in memory each and every time.
You can easily verify my assertion by running something like the following:
Output::
i = 0: j = 0 i = 1: j = 0 i = 2: j = 0 i = 3: j = 0 i = 4: j = 0
Cheers!
Z
Hey nice questions and I am agree with Norm that you should edit your post and wrap it with
to get highlighting and preserve formatting.<YOUR CODE HERE>
Have a wonderful day!