Home arrow Java & J2EE arrow Page 2 - Java Statements

While Loop - Java

In our last article, we finished our discussion of Java operators, and started to take a look at statements. In this article, we'll continue explaining Java statements. Statements aren't exactly complicated once you grasp the concept. Indeed, many statements have counterparts -- of a sort -- in real life.

TABLE OF CONTENTS:
  1. Java Statements
  2. While Loop
  3. Do-While
  4. For Loop
  5. To Be Continued...
By: James Payne
Rating: starstarstarstarstar / 13
October 24, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

The first iteration we will look at is called the While Loop. It is your standard loop that can best be described as: while this is true, keep doing this.


class CountDown {

public static void main(String args[]) {

int timer = 10; // Sets initial value of timer to 10


while(timer > 0) { // Says do this while timer > 0

System.out.println(“T minus “ + timer);

timer--; // Decrements timer by -1 each loop

}

}

}

The above code is a timer, exactly like the one used by NASA. If you ran the program, the following would print to your screen:

  T minus 10

  T minus 9

  T minus 8

  T minus 7

  T minus 6

  T minus 5

  T minus 4

  T minus 3

  T minus 2

  T minus 1

The code gives the variable timer an initial value of ten and then as it passes through each loop, it decrements the timer's value by one, prints the string “T minus" and appends the current value of timer to it. It does this until the value of timer is no longer greater than 0.

Just as a side note, if the value of timer was not greater than 0 to begin with, the program would have skipped the loop altogether.



 
 
>>> More Java & J2EE Articles          >>> More By James Payne
 

blog comments powered by Disqus
   

JAVA & J2EE ARTICLES

- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins
- Java EE 7 Looks to the Cloud
- Oracle Seeks Billions from Google Over Patent
- Oracle Java 6 Update Fixes Security Vulnerab...
- RIM Releases New BlackBerry Java SDK
- Oracle Now Offering JRockit for Free
- Google App Engine Includes Java Backend


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap

Dev Shed Tutorial Topics: