aditya aditya - 1 year ago 71
Java Question

How to reuse a variable without initializing a new one in for loop in java?

I was writing a function in java which counts the number of characters after white spaces in a string. This problem might sound trivial to some of you.

public int countAfterSpaces(final String a){
int position = 0; // escapes leading whitespaces
while(position<a.length() && a.charAt(position)==' ') position++;

Now I want to reuse this variable (position) in a for loop without creating a new one (i) in the initialization statement. Currently I am doing this.

int count = 0;
for (int i=position; i<a.length; i++) count++;
return count;

Answer Source

You don't need to declare a new variable:

for (; position<a.length; position++) count++;

You can leave any field of the for loop blank.

Or better yet, why not:

count = a.length - position;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download