Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array with decrement operator

 
Devaraj Rajakumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone please help me with the following issue?

I tried to process some data in an array using �for� loop and came across following problem with the condition statement.

int [] intArray = {1,5,4,6};
for(int x = intArray.length-1; x = =0; x--){
System.out.println(intArray[x]);
}

Since the condition statement should be of Boolean type I used �x= =0 � and also I tried �x<=0� but both compiles OK, not running and no run time errors.

When I changed to �x>=0� it works perfectly. I�m bit confused why this is happening.

Regards,
Devaraj
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The body of the for loop is executed as long as the conditional statement is true. So you should use x >= 0, then it will loop unitl x gets to zero, what is what you want.
 
Devaraj Rajakumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks bart zagers, I guess the condition statement should be always applied so that it does not refer to "0" initially.
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to explain it properly

for statement
 
Campbell Ritchie
Sheriff
Pie
Posts: 48952
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW: Did you really write x = =0? You can't have a space between the two = in an equality operator.
 
Devaraj Rajakumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, I didnt have any space in between the two equal signs. (==)

thanks
 
Campbell Ritchie
Sheriff
Pie
Posts: 48952
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The space might have been a misprint wherever you found your example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic