Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, January 24, 2012

make converter and calculating decimal to binary, sign magnitude, one's complement two's complement and float

Now, I will share for you all, how to make converter  and calculating decimal to binary, sign magnitude, one's complement two's complement and float.
First, we must now about decimal , binary , sign magnitude , one's complement two's complement and float.
You can learn about that here. I make that in Indonesian language, if you confuse about that, you can translate here.
Ok, First step for make this program :
1. open your Netbeans (I recomended to use that)


Sunday, November 20, 2011

Progress di StatusBar NetBeans






Progress di StatusBar NetBeans 
















Software yang diperlukan :


  1. Java Development Kit 1.6
  2. NetBeans Platform 6.9
Tahu progress bar yang ada di pojok kanan status bar NetBeans kan? Ya, misal saat kita merunning Project atau pada proses startup, biasanya progress akan ditampilkan di bagian tersebut di NetBeans, bagusnya NetBeans mendukung multiple progress, jadi gak hanya satu progress yang bisa tampil, tapi beberapa progress pun bisa tampil  Jadi bagaimanakah cara menggunakan Progress di Statusbar NetBeans Platform?

Mini Application Java I (Zodiac)


If you want make mini application with java , ide Netbeans. Yo can try code below

Copy and paste this code to main.java
and change name of name of package with your name project



package aplikasi_zodiak;
import javax.swing.*;
public class Main {

    public static void main(String[] args) {

        int A,B ;
        String DAY,MONTH ;
        do
        {
        DAY= JOptionPane.showInputDialog("INPUT TANGGAL KELAHIRAN ANDA!!!");
        A= Integer.parseInt(DAY);
        MONTH= JOptionPane.showInputDialog("INPUT BULAN KELAHIRAN ANDA!!!");
        B= Integer.parseInt(MONTH);

        if ((A>=23 && A<=31 && B==10)||(A>=1 && A<=22 && B==11)){
        JOptionPane.showMessageDialog(null, "SCORPIO\nKeuangan : Cukup bagus,cobalah untuk lebi berhemat\nKarir : Mulai membaik,jangan sia-siakan sebuah peluang\nKesehatan : Sedikit terganggu,kurangi kegiatan yang tidak perlu\nAsmara : Cobalah untuk mengerti si dya");}
        else if ((A>=20 && A<=29 && B==2)||(A>=1 && A<=20 && B==3)){
        JOptionPane.showMessageDialog(null, "PISCES\nKeuangan : Buruk,berhati-hatila dalam penggunaan uang\nKarir : Tidak baik,ada orang yang ingin menghancurkan karir anda\nKesehatan : Baik,meski banyak masalah kesehatan anda masih terlihat baik\nAsmara : Jangan mencampuri urusan percintaan anda dengan masalah pribadi anda");}
        else if ((A>=21 && A<=30 && B==4)||(A>=1 && A<=20 && B==5)){
        JOptionPane.showMessageDialog(null, "TAURUS\nKeuangan : Fantastis,pemasukan anda sangat banyak\nKarir : Baik,semua kegiatan selesai tepat waktu\nAsmara : Si dya merindukan kamu");}
        else if ((A>=21 && A<=31 && B==3)||(A>=1 && A<=20 && B==4)){
        JOptionPane.showMessageDialog(null,"ARIES\nKeuangan : Baik,cobalah untuk menabung untuk masa depan\nKarir : Sedikit bermasalah,namun semua masi dapat anda atasi\nKesehatan : Kurangi tidur malam,jagalah terus kesehatan anda\nAsmara : Jangan malu - malu,ungkapkan cinta anda");}
        else if ((A>=21 && A<=31 && B==5)||(A>=1 && A<=20 && B==6)){
        JOptionPane.showMessageDialog(null,"GEMINI\nKeuangan : Lumayan,cukup untuk kehidupan anda sehari-hari :p\nKarir : Sukses,YOU ARE TE BEST\nKesehatan : Mantap,tetap fit meski banyak aktifitas\nAsmara : Beri dya waktu");}
        else if ((A>=21 && A<=30 && B==6)||(A>=1 && A<=22 && B==7)){
        JOptionPane.showMessageDialog(null,"CANCER\nKeuangan : Bagus,terus pertahankan cara anda mengatur keuangan anda\nKarir : Tidak terlalu buruk\nKesehatan : Mulai membaik dari keadaan sebelumnya\nAsmara : Meski dya ngak nerima kamu,bukan berarti dya ngak sayang");}
        else if ((A>=23 && A<=31 && B==12)||(A>=1 && A<=20 && B==1)){
        JOptionPane.showMessageDialog(null,"CAPRICORN\nKeuangan : Macet,tapi nggak terlalu buruk\nKarir : wiiiiiiiiiiiih,,,excelent\nKesehatan : konsumsi makanan yang bisa nambah stamina anda\nAsmara : terseok-seok");}
        else if ((A>=21 && A<=31 && B==1)||(A>=1 && A<=19 && B==2)) {
        JOptionPane.showMessageDialog(null,"AQUARIUS\nKeuangan : Payah,ngggak mendukung\nKarir : Nggak terlalu buruk sih\nKesehatan : Badan udah mulai nggak tahan dengan kondisi saat ini\nAsmara : CINTA DALAM HATI");}
        else if ((A>=23 && A<=31 && B==8)||(A>=1 && A<=22 && B==9)){
        JOptionPane.showMessageDialog(null,"VIRGO\nKeuangan : Lancar banget,gunakan baik - baik uang kamu\nKarir : Seperti biasa,gak ada masalah besar\nKesehatan : SEMPURNA,Siap buat lembur\nAsmara : Jangan hanya diam,harus tunjukkan sikap");}
        else if ((A>=23 && A<=30 && B==9)||(A>=1 && A<=22 && B==10)){
        JOptionPane.showMessageDialog(null,"LIBRA\nKeuangan : Berhemat aja\nKarir : Sedikit tersendat-sendat\nKesehatan : Gak terlalu bagus,banyak-banyak minum multivitamin\nAsmara : Akhirnya nyampai juga cinta anda");}
        else if ((A>=23 && A<=30 && B==11)||(A>=1 && A<=22 && B==12)){
        JOptionPane.showMessageDialog(null,"SAGITARIUS\nKeuangan : Pasang surut\nKarir : Hati - hati dalam bertindak\nKesehatan : Banyakin istirahat y,sayangi badan kamu\nAsmara : Menggebu - gebu");}
        else if ((A>=23 && A<=31 && B==7)||(A>=1 && A<=22 && B==8)){
        JOptionPane.showMessageDialog(null, "LEO\nKeuangan : Kamu orang yang beruntung\nKarir : Hanya masalah kecil,bisa diatasi\nKesehatan : Tidak terlalu baik,jangan makan sembarangan\nAsmara : Jauh dimata dekat dihati");}
        else {
        JOptionPane.showMessageDialog(null, "TERNYATA MASIH ADA ORANG STRES DIDUNIA INI\n ----- MANA ADA TANGGAL SEGITU -----"); }
        }
        while (JOptionPane.showConfirmDialog(null,"MULAI LAGI?")==JOptionPane.YES_OPTION);
    }
}

Friday, November 18, 2011

Java (Case Studies)


Case Studies

Control statements are fundamental in programming. The ability to write control statements is essential in learning Java programming. If you can write programs using loops, you know how to program! For this reason, this section presents three additional examples of how to solve problems using loops.

Example: Finding the Greatest Common Divisor

This section presents a program that prompts the user to enter two positive integers and finds their greatest common divisor.
The greatest common divisor of two integers 4 and 2 is 2. The greatest common divisor of two integers 16 and 24 is 8. How do you find the greatest common divisor? Let the two input integers be n1 and n2. You know that number 1 is a common divisor, but it may not be the greatest common divisor. So you can check whether k (for k = 2, 3, 4 and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. Store the common divisor in a variable named gcd. Initially, gcd is 1. Whenever a new common divisor is found, it becomes the new gcd. When you have checked all the possible common divisors from 2 up to n1 or n2, the value in variable gcd is the greatest common divisor. The idea can be translated into the following loop:
int gcd = 1;
int k = 1;

while (k <= n1 && k <= n2) {
  if (n1 % k == 0 && n2 % k == 0)
    gcd = k;
  k++;
}

// After the loop, gcd is the greatest common divisor for n1 and n2

The complete program is given in Listing 4.6, and a sample run of the program is shown in Figure 4.8.



Figure 4.8. The program finds the greatest common divisor for two integers.


Listing 4.6. GreatestCommonDivisor.java


 1 import javax.swing.JOptionPane;
 2
 3 public class GreatestCommonDivisor {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     // Prompt the user to enter two integers
 7     String s1 = JOptionPane.showInputDialog("Enter first integer");
 8     int n1 = Integer.parseInt(s1);
 9
10     String s2 = JOptionPane.showInputDialog("Enter second integer");
11     int n2 = Integer.parseInt(s2);
12
13     int gcd = 1;

[Page 109]
14 int k = 1; 15 while (k <= n1 && k <= n2) { 16 if (n1 % k == 0 && n2 % k == 0) 17 gcd = k; 18 k++; 19 } 20 21 String output = "The greatest common divisor for " + n1 + " and " 22 + n2 + " is " + gcd; 23 JOptionPane.showMessageDialog(null, output); 24 } 25 }
How did you write this program? Did you immediately begin to write the code? No. It is important to think before you type. Thinking enables you to generate a logical solution for the problem without concern about how to write the code. Once you have a logical solution, type the code to translate the solution into a Java program. The translation is not unique. For example, you could use a for loop to rewrite the code as follows:
for (int k = 1; k <= n1 && k <= n2; k++) {
  if (n1 % k == 0 && n2 % k == 0)
    gcd = k;
}

A problem often has multiple solutions. The GCD problem can be solved in many ways. Exercise 4.15 suggests another solution. A more efficient solution is to use the classic Euclidean algorithm. See http://www.cut-the-knot.org/blue/Euclid.shtml for more information.
You might think that a divisor for a number n1 cannot be greater than n1 / 2. So you would attempt to improve the program using the following loop:
for (int k = 1; k <= n1 / 2 && k <= ; n2 / 2 k++) {
  if (n1 % k == 0 && n2 % k == 0)
    gcd = k;
}

This revision is wrong. Can you find the reason? See Review Question 4.9 for the answer.

4.8.2. Example: Finding the Sales Amount

You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate.


Sales Amount Commission Rate
$0.01–$5,000 8 percent
$5,000.01–$10,000 10 percent
$10,000.01 and above 12 percent

Your goal is to earn $30,000 a year. This section writes a program that finds the minimum amount of sales you have to generate in order to make $30,000.
Since your base salary is $5,000, you have to make $25,000 in commissions to earn $30,000 a year. What is the sales amount for a $25,000 commission? If you know the sales amount, the commission can be computed as follows:
if (salesAmount >= 10000.01)
  commission =
    5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;
else if (salesAmount >= 5000.01)
  commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;
else
  commission = salesAmount * 0.08;

This suggests that you can try to find the salesAmount to match a given commission through incremental approximation. For a salesAmount of $0.01 (1 cent), find commission. If commission is less than $25,000, increment salesAmount by 0.01 and find commission again. If commission is still less than $25,000, repeat the process until it is greater than or equal to $25,000. This is a tedious job for humans, but it is exactly what a computer is good for. You can write a loop and let a computer execute it painlessly. The idea can be translated into the following loop:
Set COMMISSION_SOUGHT as a constant;
Set an initial salesAmount;

do {
  Increase salesAmount by 1 cent;
  Compute the commission from the current salesAmount;
} while (commission < COMMISSION_SOUGHT);

The complete program is given in Listing 4.7, and a sample run of the program is shown in Figure 4.9.


Figure 4.9. The program finds the sales amount for the given commission.



Listing 4.7. FindSalesAmount.java


 1 import javax.swing.JOptionPane;
 2
 3 public class FindSalesAmount {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     // The commission sought
 7     final double COMMISSION_SOUGHT = 25000;
 8     final double INITIAL_SALES_AMOUNT = 0.01;

[Page 111]
9 double commission = 0; 10 double salesAmount = INITIAL_SALES_AMOUNT; 11 12 do { 13 // Increase salesAmount by 1 cent 14 salesAmount += 0.01; 15 16 // Compute the commission from the current salesAmount; 17 if (salesAmount >= 10000.01) 18 commission = 19 5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12; 20 else if (salesAmount >= 5000.01) 21 commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10; 22 else 23 commission = salesAmount * 0.08; 24 } while (commission < COMMISSION_SOUGHT); 25 26 // Display the sales amount 27 String output = 28 "The sales amount $" + (int)(salesAmount * 100) / 100.0 + 29 "\nis needed to make a commission of $" + COMMISSION_SOUGHT; 30 JOptionPane.showMessageDialog(null, output); 31 } 32 }
The do-while loop (lines 12–24) is used to repeatedly compute commission for an incremental salesAmount. The loop terminates when commission is greater than or equal to a constant COMMISSION_SOUGHT.
In Exercise 4.17, you will rewrite this program to let the user enter COMMISSION_SOUGHT dynamically from an input dialog.
You can improve the performance of this program by estimating a higher INITIAL_SALES_AMOUNT (e.g., 25000).
What is wrong if saleAmount is incremented after the commission is computed, as follows?
do {
  // Compute the commission from the current salesAmount;
  if (salesAmount >= 10000.01)
    commission =
      5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;
  else if (salesAmount >= 5000.01)
    commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;
  else
    commission = salesAmount * 0.08;

  // Increase salesAmount by 1 cent
  salesAmount += 0.01;
} while (commission < COMMISSION_SOUGHT);

The change is erroneous because saleAmount is 1 cent more than is needed for the commission when the loop ends. This is a common error in loops, known as the off-by-one error.

Tip


This example uses constants COMMISSION_SOUGHT and INITIAL_SALES_AMOUNT. Using constants makes programs easy to read and maintain.


4.8.3. Example: Displaying a Pyramid of Numbers

This section presents a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid. If the input integer is 12, for example, the output is shown in Figure 4.10.


Figure 4.10. The program uses nested loops to print numbers in a triangular pattern.


Your program receives the input for an integer (numberOfLines) that represents the total number of lines. It displays all the lines one by one. Each line has three parts. The first part comprises the spaces before the numbers; the second part, the leading numbers, such as 3 2 1 in line 3; and the last part, the ending numbers, such as 2 3 in line 3.
Each number occupies three spaces. Display an empty space before a double-digit number, and display two empty spaces before a single-digit number.
You can use an outer loop to control the lines. At the nth row, there are (numberOfLines – n)*3 leading spaces, the leading numbers are n, n-1, … 1, and the ending numbers are 2, ..., n. You can use three separate inner loops to print each part.
Here is the algorithm for the problem:
Input numberOfLines;

for (int row = 1; row <= numberOfLines; row++) {
  Print (numberOfLines - row) * 3 leading spaces;
  Print leading numbers row, row - 1, ..., 1;
  Print ending numbers 2, 3, ..., row - 1, row;
  Start a new line;
}

The complete program is given in Listing 4.8.

Listing 4.8. PrintPyramid.java


 1 import javax.swing.JOptionPane;
 2
 3 public class PrintPyramid {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     // Prompt the user to enter the number of lines
 7     String input = JOptionPane.showInputDialog(
 8       "Enter the number of lines:");
 9     int numberOfLines = Integer.parseInt(input);
10
11     if (numberOfLines < 1 || numberOfLines > 15) {
12       System.out.println("You must enter a number from 1 to 15");
13       System.exit(0);
14     }
15
16     // Print lines
17     for (int row = 1; row <= numberOfLines; row++) {
18       // Print NUMBER OF LINES – row) leading spaces
19       for (int column = 1; column <= numberOfLines - row; column++)
20         System.out.print(" ");
21

[Page 113]
22 // Print leading numbers row, row - 1, ..., 1 23 for (int num = row; num >= 1; num-) 24 System.out.print((num >= 10) ? " " + num : " " + num); 25 26 // Print ending numbers 2, 3, ..., row - 1, row 27 for (int num = 2; num <= row; num++) 28 System.out.print((num >= 10) ? " " + num : " " + num); 29 30 // Start a new line 31 System.out.println(); 32 } 33 } 34 }
The program uses the print method (lines 20, 24, and 28) to display a string to the console. The conditional expression (num >= 10) ? " " + num : " " + num in lines 24 and 28 returns a string with a single empty space before the number if the number is greater than or equal to 10, and otherwise returns a string with two empty spaces before the number.
Printing patterns like this one and the ones in Exercises 4.18 and 4.19 is a good exercise for practicing loop control statements. The key is to understand the pattern and to describe it using loop control variables.
The last line in the outer loop (line 31), System.out.println(), does not have any argument in the method. This call moves the cursor to the next line.

Java (Minimizing Numerical Errors)


Minimizing Numerical Errors

Numeric errors involving floating-point numbers are inevitable. This section discusses how to minimize such errors through an example.
Listing 4.5 presents an example that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on. The output of the program appears in Figure 4.7.

Figure 4.7. The program uses a for loop to sum a series from 0.01 to 1.0 in increments of 0.01.


Listing 4.5. TestSum.java


 1 import javax.swing.JOptionPane;
 2
 3 public class TestSum {
 4   public static void main(String[] args) {

[Page 107]
5 // Initialize sum 6 float sum = 0; 7 8 // Add 0.01, 0.02, ..., 0.99, 1 to sum 9 for (float i = 0.01f; i <= 1.0f; i = i + 0.01f) 10 sum += i; 11 12 // Display result 13 JOptionPane.showMessageDialog(null, "The sum is " + sum); 14 } 15 }
The for loop (lines 9–10) repeatedly adds the control variable i to the sum. This variable, which begins with 0.01, is incremented by 0.01 after each iteration. The loop terminates when i exceeds 1.0.
The for loop initial action can be any statement, but it is often used to initialize a control variable. From this example, you can see that a control variable can be a float type. In fact, it can be any data type.
The exact sum should be 50.50, but the answer is 50.499985. The result is not precise because computers use a fixed number of bits to represent floating-point numbers, and thus cannot represent some floating-point numbers exactly. If you change float in the program to double as follows, you should see a slight improvement in precision because a double variable takes sixty-four bits, whereas a float variable takes thirty-two bits.
// Initialize sum
double sum = 0;

// Add 0.01, 0.02, ..., 0.99, 1 to sum
for (double i = 0.01; i <= 1.0; i = i + 0.01)
  sum += i;

However, you will be stunned to see that the result is actually 49.50000000000003. What went wrong? If you print out i for each iteration in the loop, you will see that the last i is slightly larger than 1 (not exactly 1). This causes the last i not to be added into sum. The fundamental problem is that the floating-point numbers are represented by approximation. Errors commonly occur. There are two ways to fix the problem:
  • Minimizing errors by processing large numbers first.
  • Using an integer count to ensure that all the numbers are processed.
  • To minimize errors, add numbers from 1.0, 0.99, down to 0.1, as follows:
// Add 1, 0.99, ..., 0.01 to sum
for (double i = 1.0; i >= 0.01; i = i - 0.01)
  sum += i;

To ensure that all the items are added to sum, use an integer variable to count the items. Here is the new loop:
double currentValue = 0.01;

for {int count = 0; count < 100; count++) {
  sum += currentValue;
  currentValue += 0.01;
}

After this loop, sum is 50.50000000000003.

Edisi Indonesia (Compile Java Lewat CMD)

Compile Java Lewat CMD

Saat pertama bermain java (bagi yang menggunakan notepad dan sejenisnya (tanpa IDE)) akan bingung saat akan menjalankan java lewat CMD. Mengapa?
Ya, karna CMD belum mengenali perintah yang anda masukkan. Maka dari itu kita harus seting dahulu Java dalam komputer kita. Hohohhoh :D

cara seting java gampang, antara lain :
1. Download JDK di website resmi java, yaitu ==> di sini
2. Setelah itu Install JDK di komputer
3. Apabila java telah terinstall dengan benar di komputer, saatnya melakukan setting Pathnya agar CMD mengenal java
4. Buka My Computer ==> Properties

==> Advance system setting ==> Advanced

 ==> Environment Variabels


5. Bila sudah ketemu cari Pah di system variables, klik 2 kli

6. Buka folder tempat anda menginstall java ==> copy adress java
7. Kemudian di akhir  Path tadi beri tanda ";" tanpa tanda kutip, sebagai pemisah
8. Lalu pastekan adress java yang telah di copy, contoh C:\Program Files\Java\jdk1.6.0_06\bin
9. Pilih oke dan restart komputer anda

Hal seperti ini diperlukan juga dalam menginstall ANDROID, seperi contoh di atas yang tertera adalah -1.6_r1\android-sdk-windows-1.6_r1\tools ==> yang sebenarnya alamat dari ANDROID di komputer saya ==> C:\android\dari miftah\android-sdk-windows-1.6_r1\android-sdk-windows-1.6_r1\tools.


Java (Nested Loops)


Nested Loops

Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew.
Listing 4.4 presents a program that uses nested for loops to print a multiplication table, as shown in Figure 4.6.


Figure 4.6. The program uses nested for loops to print a multiplication table.



Listing 4.4. MultiplicationTable.java

 1 import javax.swing.JOptionPane;
 2
 3 public class MultiplicationTable {
 4    /** Main method */
 5    public static void main(String[] args) {
 6      // Display the table heading
 7      String output = "                Multiplication Table\n";
 8      output += "------------------------------------------------\n";
 9
10      // Display the number title
11      output += " | ";
12      for (int j = 1; j <= 9; j++)
13        output += " " + j;
14
15      output += "\n";
16
17      // Print table body
18      for (int i = 1; i <= 9; i++) {
19        output += i + " | ";
20        for (int j = 1 j < = 9; j++) {
21          // Display the product and align properly
22          if (i * j < 10)
23            output += " " + i * j;
24          else
25            output += " " + i * j;
26        }
27        output += "\n";
28      }
29
30      // Display result
31      JOptionPane.showMessageDialog(null, output);
32    }
33  }
The program displays a title (line 7) on the first line and dashes (-) (line 8) on the second line. The first for loop (lines 12–13) displays the numbers 1 through 9 on the third line.
The next loop (lines 18–28) is a nested for loop with the control variable i in the outer loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner loop, with j being 1, 2, 3, …, 9. The if statement in the inner loop (lines 22–25) is used so that the product will be aligned properly. If the product is a single digit, it is displayed with an extra space before it.

Java (The for Loop)


The for Loop

Often you write a loop in the following common form:
i = initialValue; // Initialize loop control variable
while (i < endValue) {
  // Loop body
  ...
  i++; // Adjust loop control variable
}

A for loop can be used to simplify the preceding loop:
for (i = initialValue; i < endValue; i++) {
  // Loop body
  ...
}

In general, the syntax of a for loop is as shown below:
for (initial-action; loop-continuation-condition;
     action-after-each-iteration) {
  // Loop body;
  Statement(s);
}

The flow chart of the for loop is shown in Figure 4.5(a).


Figure 4.5. A for loop performs an initial action once, then repeatedly executes the statements in the loop body, and performs an action after an iteration when the loop-continuation-condition evaluates to true.


The for loop statement starts with the keyword for, followed by a pair of parentheses enclosing initial-action, loop-continuation-condition, and action-after-each-iteration, and followed by the loop body enclosed inside braces. initial-action, loop-continuation-condition, and action-after-each-iteration are separated by semicolons.
A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates. This variable is referred to as a control variable. The initial-action often initializes a control variable, the action-after-each-iteration usually increments or decrements the control variable, and the loop-continuation-condition tests whether the control variable has reached a termination value. For example, the following for loop prints "Welcome to Java!" a hundred times:
int i;
for (i = 0; i < 100; i++) {
  System.out.println("Welcome to Java!");
}

The flow chart of the statement is shown in Figure 4.5(b). The for loop initializes i to 0, then repeatedly executes the println statement and evaluates i++ while i is less than 100.
The initial-action, i=0, initializes the control variable, i. The loop-continuation-condition, i< 100 is a Boolean expression. The expression is evaluated at the beginning of each iteration. If this condition is true, execute the loop body. If it is false, the loop terminates and the program control turns to the line following the loop.
The action-after-each-iteration, i++, is a statement that adjusts the control variable. This statement is executed after each iteration. It increments the control variable. Eventually, the value of the control variable should force the loop-continuation-condition to become false. Otherwise the loop is infinite.
for (int i = 0; i < 100; i++) {
  System.out.println("Welcome to Java!");
}

If there is only one statement in the loop body, as in this example, the braces can be omitted.

Tip


The control variable must always be declared inside the control structure of the loop or before the loop. If the loop control variable is used only in the loop, and not elsewhere, it is good programming practice to declare it in the initial-action of the for loop. If the variable is declared inside the loop control structure, it cannot be referenced outside the loop. For example, you cannot reference i outside the for loop in the preceding code, because it is declared inside the for loop.


Note


The initial-action in a for loop can be a list of zero or more comma-separated variable declaration statements or assignment expressions. For example,
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
  // Do something
}

The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements. For example,
for (int i = 1; i < 100; System.out.println(i), i++);

This example is correct, but it is not a good example, because it makes the code difficult to read. Normally, you declare and initialize a control variable as initial action, and increment or decrement the control variable as an action after each iteration.

Note


If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion: