Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java expressions [duplicate]

I am trying to understand this code in Java 7 environment,

int T = getIntVal();
while (T--> 0) {
 // do stuff here
}

T is not modified within the while loop. Can someone explain this code?

like image 689
Vel Avatar asked Aug 25 '16 17:08

Vel


People also ask

What does duplicate mean in Java?

Duplicate code as the name suggests is a repetition of a line or a block of code in the same file or sometimes in the same local environment.

How do you find duplicate parentheses in an expression?

A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis. Examples: Below expressions have duplicate parenthesis - ((a+b)+((c+d))) The subexpression "c+d" is surrounded by two pairs of brackets. (((a+(b)))+(c+d)) The subexpression "a+(b)" is surrounded by two pairs of brackets.


2 Answers

what confuses you is that there is no whitespace between the T-- and the >, so you might think there's a --> operator.
looking like this:

while (T-- > 0) {

}

It makes more sense, in every loop you decrease T by one

like image 60
Nir Levy Avatar answered Oct 16 '22 08:10

Nir Levy


The -- (decrement) operator will subtract from T each time the loop is run (after the loop condition is run since it as after T).

The simplest way is to just try it out:

public class Tester {

   public static void main(String[] args) {
      System.out.println("-------STARTING TESTER-------");
      int T = 5;
      while (T-- > 0) {
         System.out.println(T);
      }
      System.out.println("-------ENDING TESTER-------");
   }

}

Output:

-------STARTING TESTER-------
4
3
2
1
0
-------ENDING TESTER-------

If the -- operator was before T, the output would look like this (since it subtracts before the loop condition is run):

-------STARTING TESTER-------
4
3
2
1
-------ENDING TESTER-------
like image 2
Adam Avatar answered Oct 16 '22 09:10

Adam