Friday 17 February 2017

A Second Short Program & Two Control Statements - Java Tutorials

A Second Short Program

Perhaps no other concept is more fundamental to a programming language than that of a variable. As you probably know, a variable is a named memory location that may be assigned a value by your program. The value of a variable may be changed during the execution of the program. The next program shows how a variable is declared and how it is assigned a value. In addition, the program also illustrates some new aspects of console output. As the comments at the top of the program state, you should call this file Example2.java.

       /*
       Here is another short example.
       Call this file "Example2.java".
   */
   class Example2 {
       public static void main(String args[]) {
         int num; // this declares a variable called num

         num = 100; // this assigns num the value 100

         System.out.println("This is num: " + num);

         num = num * 2;

         System.out.print("The value of num * 2 is ");
         System.out.println(num);
      }
    }

When you run this program, you will see the following output:

    This is num: 100
    The value of num * 2 is 200

Let’s take a close look at why this output is generated. The first new line in the program is shown here:

    int num; // this declares a variable called num

This line declares an integer variable called num. Java (like most other languages) requires that variables be declared before they are used.
Following is the general form of a variable declaration:

         type var-name;

Here, type specifies the type of variable being declared, and var-name is the name of the variable. If you want to declare more than one variable of the specified type, you may use a comma-separated list of variable names. Java defines several data types, including integer, character, and floating-point. The keyword int specifies an integer type.
In the program, the line

    num = 100; // this assigns num the value 100

assigns to num the value 100. In Java, the assignment operator is a single equal sign.
The next line of code outputs the value of num preceded by the string “This is num:”. 

    System.out.println("This is num: " + num);

In this statement, the plus sign causes the value of num to be appended to the string that precedes it, and then the resulting string is output. (Actually, num is first converted from an integer into its string equivalent and then concatenated with the string that precedes it. This process is described in detail later in this book.) This approach can be generalized. Using the + operator, you can string together as many items as you want within a single println( ) statement.

The next line of code assigns num the value of num times 2. Like most other languages, Java uses the * operator to indicate multiplication. After this line executes, num will contain the value 200.
Here are the next two lines in the program:

    System.out.print("The value of num * 2 is ");
    System.out.println(num);

Several new things are occurring here. First, the built-in method print( ) is used to display the string “The value of num * 2 is ”. This string is not followed by a newline. This means that when the next output is generated, it will start on the same line. The print( ) method is just like println( ), except that it does not output a newline character after each call. Now look at the call to println( ). Notice that num is used by itself. Both print( ) and println( ) can be used to output values of any of Java’s built-in types.



Two Control Statements

Although Chapter 5 will look closely at control statements, two are briefly introduced here so that they can be used in example programs in Chapters 3 and 4. They will also help illustrate an important aspect of Java: blocks of code.

The if Statement

The Java if statement works much like the IF statement in any other language. Further, it is syntactically identical to the if statements in C, C++, and C#. Its simplest form is shown here:

          if(condition) statement;

Here, condition is a Boolean expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed. Here is an example:

    if(num < 100) println("num is less than 100");

In this case, if num contains a value that is less than 100, the conditional expression is true, and println( ) will execute. If num contains a value greater than or equal to 100, then the println( ) method is bypassed.

As you will see in Chapter 4, Java defines a full complement of relational operators which may be used in a conditional expression. Here are a few:

        Operator                                      Meaning
             <                                               Less than
             >                                               Greater than
             ==                                             Equal to

Notice that the test for equality is the double equal sign.
Here is a program that illust rates the if statement:

    /*
       Demonstrate the if.

       Call this file "IfSample.java".
    */
    class IfSample {
       public static void main(String args[]) {
         int x, y;

         x = 10;
         y = 20;

         if(x < y) System.out.println("x is less than y");

         x = x * 2;
         if(x == y) System.out.println("x now equal to y");

         x = x * 2;
         if(x > y) System.out.println("x now greater than y");

         // this won't display anything
         if(x == y) System.out.println("you won't see this");
      }
    }

The output generated by this program is shown here:

    x is less than y
    x now equal to y
    x now greater than y

Notice one other thing in this program. The line

    int x, y;

declares two variables, x and y, by use of a comma-separated list.

The for Loop

As you may know from your previous programming experience, loop statements are an important part of nearly any programming language. Java is no exception. In fact, as you will see in Chapter 5, Java supplies a powerful assortment of loop constructs. Perhaps the most versatile is the for loop. If you are familiar with C, C++, or C#, then you will be pleased to know that the for loop in Java works the same way it does in those languages. If you don’t know C/C++/C#, the for loop is still easy to use. The simplest form of the for loop is shown here:

          for(initialization; condition; iteration) statement;

In its most common form, the initialization portion of the loop sets a loop control variable to an initial value. The condition is a Boolean expression that tests the loop control variable. If the outcome of that test is true, the for loop continues to iterate. If it is false, the loop terminates. The iteration expression determines how the loop control variable is changed each time the loop iterates. Here is a short program that illustrates the for loop:

    /*
       Demonstrate the for loop.

       Call this file "ForTest.java".
    */
    class ForTest {
       public static void main(String args[]) {
         int x;

         for(x = 0; x<10; x = x+1)
         System.out.println("This is x: " + x);
       }
    }

This program generates the following output:

    This is x: 0
    This is x: 1
    This is x: 2
    This is x: 3
    This is x: 4
    This is x: 5
    This is x: 6
    This is x: 7
    This is x: 8
    This is x: 9

In this example, x is the loop control variable. It is initialized to zero in the initialization portion of the for. At the start of each iteration (including the first one), the conditional test x < 10 is performed. If the outcome of this test is true, the println( ) statement is executed, and then the iteration portion of the loop is executed. This process continues until the conditional test is false.

As a point of interest, in professionally written Java programs you will almost never see the iteration portion of the loop written as shown in the preceding program. 
That is, you will seldom see statements like this:

    x = x + 1;

The reason is that Java includes a special increment operator which performs this operation more efficiently. The increment operator is ++. (That is, two plus signs back to back.) The increment operator increases its operand by one. By use of the increment operator, the preceding statement can be written like this:

    x++;

Thus, the for in the preceding program will usually be written like this:

    for(x = 0; x<10; x++)

You might want to try this. As you will see, the loop still runs exactly the same as it did before.

Java also provides a decrement operator, which is specified as – –. This operator decreases its operand by one.