Assignment, Increment and Decrement Operators

In reality almost nobody writes for loops like we did in the previous sections. They would almost certainly use the increment or decrement operators instead. There are two of these, ++ and -- and they work like this.

//Count to ten class CountToTen { public static void main (String args[]) { int i; for (i=1; i <=10; i++) { System.out.println(i); } System.out.println("All done!); } }

//Count to ten?? class BuggyCountToTen { public static void main (String args[]) { int i; for (i=1; i <=10; i--) { System.out.println(i); } System.out.println("All done!); } } When we write i++ we're using shorthand for i = i + 1 . When we say i-- we're using shorthand for i = i - 1 . Adding and subtracting one from a number are such common operations that these special increment and decrement operators have been added to the language. They also allow the compiler to be smarter about certain optimizations on some CPU architectures, but mainly they make code easier to write and read.

However what do you do when you want to increment not by one but by two? or three? or fifteen? We could of course write i = i + 15 but this happens frequently enough that there's another short hand for the general add and assign operation, += . We would normally write this as i += 15 . Thus if we wanted to count from 0 to 20 by two's we'd write:

class CountToTwentyByTwos { public static void main (String args[]) { int i; for (i=0; i <=20; i += 2) { System.out.println(i); } System.out.println("All done!); } //main ends here } As you might guess there is a corresponding -= operator. If we wanted to count down from twenty to zero by twos we could write:

class CountToZeroByTwos { public static void main (String args[]) { int i; for (i=20; i = 0; i -= 2) { System.out.println(i); } System.out.println("All done!); } }

 

Bhopal news
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

freelance web designer india ecommerce web developer | Ecommerce web design, software developer india | Web hosting India Windows hosting | India web hosting Windows hosting India | India software developer | web designer india