Wednesday 22 February 2017

Characters, Booleans & A Closer Look at Literals - Java Tutorials

Characters

In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for global portability.


           Here is a program that demonstrates char variables:

    // Demonstrate char data type.
    class CharDemo {
      public static void main(String args[]) {
        char ch1, ch2;

        ch1 = 88; // code for X
        ch2 = 'Y';

        System.out.print("ch1 and ch2: ");
        System.out.println(ch1 + " " + ch2);
      }
    }

This program displays the following output:

    ch1 and ch2: X Y

Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127 values in the Unicode character set. For this reason, all the “old tricks” that you have used with characters in the past will work in Java, too.

Even though chars are not integers, in many cases you can operate on them as if they were integers. This allows you to add two characters together, or to increment the value of a character variable. For example, consider the following program:

    // char variables behave like integers.
    class CharDemo2 {
      public static void main(String args[]) {
        char ch1;

        ch1 = 'X';
        System.out.println("ch1 contains " + ch1);

        ch1++; // increment ch1
        System.out.println("ch1 is now " + ch1);
      }
    }

The output generated by this program is shown here:

    ch1 contains X
    ch1 is now Y

In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence.



Booleans

Java has a simple type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, such as a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for.

Here is a program that demonstrates the boolean type:

    // Demonstrate boolean values.
    class BoolTest {
      public static void main(String args[]) {
        boolean b;

        b = false;
        System.out.println("b is " + b);
        b = true;
        System.out.println("b is " + b);

        // a boolean value can control the if statement
        if(b) System.out.println("This is executed.");

        b = false;
        if(b) System.out.println("This is not executed.");

        // outcome of a relational operator is a boolean value
        System.out.println("10 > 9 is " + (10 > 9));
      }
    }

The output generated by this program is shown here:

    b is false
    b is true
    This is executed.
    10 > 9 is true

There are three interesting things to notice about this program. First, as you can see, when a boolean value is output by println( ), “true” or “false” is displayed. Second, the value of a boolean variable is sufficient, by itself, to control the if statement. There is no need to write an if statement like this:

    if(b == true) ...

Third, the outcome of a relational operator, such as <, is a boolean value. This is why the expression 10 > 9 displays the value “true.” Further, the extra set of parentheses around 10 > 9 is necessary because the + operator has a higher precedence than the >.



A Closer Look at Literals

Literals were mentioned briefly in Chapter 2. Now that the built-in types have been formally described, let’s take a closer look at them.

Integer Literals

Integers are probably the most commonly used type in the typical program. Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are describing a base 10 number. There are two other bases which can be used in integer literals, octal (base eight) and hexadecimal (base 16). Octal values are denoted in Java by a leading zero. Normal decimal numbers cannot have a leading zero. Thus, the seemingly valid value 09 will produce an error from the compiler, since 9 is outside of octal’s 0 to 7 range. A more common base for numbers used by programmers is hexadecimal, which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15.

Integer literals create an int value, which in Java is a 32-bit integer value. Since Java is strongly typed, you might be wondering how it is possible to assign an integer literal to one of Java’s other integer types, such as byte or long, without causing a type mismatch error. Fortunately, such situations are easily handled. When a literal value is assigned to a byte or short variable, no error is generated if the literal value is within the range of the target type. Also, an integer literal can always be assigned to a long variable. However, to specify a long literal, you will need to explicitly tell the compiler that the literal value is of type long. You do this by appending an upper- or lowercase L to the literal. For example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long.

Floating-Point Literals

Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers. Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05, and 2e+100.

Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant. You can also explicitly specify a double literal by appending a D or d. Doing so is, of course, redundant. The default double type consumes 64 bits of storage, while the less-accurate float type requires only 32 bits.

Boolean Literals

Boolean literals are simple. There are only two logical values that a boolean value can have, true and false. The values of true and false do not convert into any numerical representation. The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared as boolean, or used in expressions with Boolean operators.

Character Literals

Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into integers and manipulated with the integer operators, such as the addition and subtraction operators. A literal character is represented inside a pair of single quotes. All of the visible ASCII characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and ‘@’. For characters that are impossible to enter directly, there are several escape sequences, which allow you to enter the character you need, such as ‘\’’ for the single-quote character itself, and ‘\n’ for the newline character. There is also a mechanism for directly entering the value of a character in octal or hexadecimal. For octal notation use the backslash followed by the three-digit number. For example, ‘\141’ is the letter ‘a’. For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. For example, ‘\u0061’ is the ISO-Latin-1 ‘a’ because the top byte is zero. ‘\ua432’ is a Japanese Katakana character. Table 3-1 shows the character escape sequences.

Character Escape Sequences

Escape Sequence               Description

\ddd                                     Octal character (ddd)

\uxxxx                                 Hexadecimal UNICODE character (xxxx)

\’                                          Single quote

\”                                         Double quote

\\                                          Backslash

\r                                          Carriage return

\n                                         New line (also known as line feed)

\f                                          Form feed

\t                                           Tab

\b                                          Backspace


String Literals

String literals in Java are specified like they are in most other languages—by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are

    “Hello World”
    “two\nlines”
    “\”This is in quotes\””

The escape sequences and octal/hexadecimal notations that were defined for character literals work the same way inside of string literals. One important thing to note about Java strings is that they must begin and end on the same line. There is no line-continuation escape sequence as there is in other languages.

As you may know, in some other languages, including C/C++, strings are implemented as arrays of characters. However, this is not the case in Java. Strings are actually object types. As you will see later in this book, because Java implements strings as objects, Java includes extensive string-handling capabilities that are both powerful and easy to use.

Monday 20 February 2017

Integers & Floating-Point Types - Java Tutorials

Integers

Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers. Many other computer languages, including C/C++, support both signed and unsigned integers. However, Java’s designers felt that unsigned integers were unnecessary. Specifically, they felt that the concept of unsigned was used mostly to specify the behavior of the high-order bit, which defined the sign of an int when expressed as a number. As you will see in Chapter 4, Java manages the meaning of the high-order bit differently, by adding a special “unsigned right shift” operator. Thus, the need for an unsigned integer type was eliminated.

The width of an integer type should not be thought of as the amount of storage it consumes, but rather as the behavior it defines for variables and expressions of that type. The Java run-time environment is free to use whatever size it wants, as long as the types behave as you declared them. In fact, at least one implementation stores bytes and shorts as 32-bit (rather than 8- and 16-bit) values to improve performance, because that is the word size of most computers currently in use.

The width and ranges of these integer types vary widely, as shown in this table:

Name         Width                          Range

long              64                 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int                  32                                –2,147,483,648 to 2,147,483,647
short              16                                –32,768 to 32,767
byte                8                                 –128 to 127

Let’s look at each type of integer.

byte

The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with raw binary data that may not be directly compatible with Java’s other built-in types. 

Byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called b and c:

    byte b, c;

short

short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used Java type, since it is defined as having its high byte first (called big-endian format). This type is mostly applicable to 16-bit computers, which are becoming increasingly scarce.

Here are some examples of short variable declarations:

    short s;
    short t;

Note:   “Endianness” describes how multibyte data types, such as short, int, and long, are stored in memory. If it takes 2 bytes to represent a short, then which one comes first, the most significant or the least significant? To say that a machine is big-endian, means that the most significant byte is first, followed by the least significant one. Machines such as the SPARC and PowerPC are big-endian, while the Intel x86 series is little-endian.

int

The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays. Any time you have an integer expression involving bytes, shorts, ints, and literal numbers, the entire expression is promoted to int before the calculation is done.

The int type is the most versatile and efficient type, and it should be used most of the time when you want to create a number for counting or indexing arrays or doing integer math. It may seem that using short or byte will save space, but there is no guarantee that Java won’t promote those types to int internally anyway. Remember, type determines behavior, not size. (The only exception is arrays, where byte is guaranteed to use only one byte per array element, short will use two bytes, and int will use four.)

long

long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed. For example, here is a program that computes the number of miles that light will travel in a specified number of days.

    // Compute distance light travels using long variables.
    class Light {
      public static void main(String args[]) {
        int lightspeed;
        long days;
        long seconds;
        long distance;

        // approximate speed of light in miles per second
        lightspeed = 186000;

        days = 1000; // specify number of days here

        seconds = days * 24 * 60 * 60; // convert to seconds

        distance = lightspeed * seconds; // compute distance

        System.out.print("In " + days);
        System.out.print(" days light will travel about ");
        System.out.println(distance + " miles.");
      }
    }

This program generates the following output:

    In 1000 days light will travel about 16070400000000 miles.

Clearly, the result could not have been held in an int variable.




Floating-Point Types

Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating-point type. Java implements the standard (IEEE–754) set of floating-point types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:

Name          Width in Bits              Approximate Range

double         64                                 4.9e–324 to 1.8e+308

float             32                                1.4e−045 to 3.4e+038

Each of these floating-point types is examined next.

float

The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision. For example, float can be useful when representing dollars and cents.

Here are some example float variable declarations:

    float hightemp, lowtemp;    

double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.

Here is a short program that uses double variables to compute the area of a circle:

    // Compute the area of a circle.
    class Area {
      public static void main(String args[]) {
        double pi, r, a;

        r = 10.8; // radius of circle
        pi = 3.1416; // pi, approximately
        a = pi * r * r; // compute area
        System.out.println("Area of circle is " + a);
      }
    }

Saturday 18 February 2017

Lexical Issues & The Simple Types - Java Tutorials

Lexical Issues

Now that you have seen several short Java programs, it is time to more formally describe the atomic elements of Java. Java programs are a collection of whitespace, identifiers, comments, literals, operators, separators, and keywords. The operators are described in the next chapter. The others are described next.

Whitespace

Java is a free-form language. This means that you do not need to follow any special indentation rules. For example, the Example program could have been written all on one line or in any other strange way you felt like typing it, as long as there was at least one whitespace character between each token that was not already delineated by an operator or separator. In Java, whitespace is a space, tab, or newline.

Identifiers

Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. They must not begin with a number, lest they be confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value. Some examples of valid identifiers are:

AvgTemp                count                a4                $test                this_is_ok

Invalid variable names include:

2count                high-temp                Not/ok

Literals

A constant value in Java is created by using a literal representation of it. For example, here are some literals:

100                98.6                ‘X’                “This is a test”

Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character constant, and the last is a string. A literal can be used anywhere a value of its type is allowed.

Comments

As mentioned, there are three types of comments defined by Java. You have already seen two: single-line and multiline. The third type is called a documentation comment. This type of comment is used to produce an HTML file that documents your program. The documentation comment begins with a /** and ends with a */.

Separators

In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements. The separators are shown in the following table:

Symbol -  ( )                                  

Name -     Parentheses              

Purpose - Used to contain lists of parameters in method definition and invocation. Also used for defining precedence in expressions, containing expressions in control statements, and surrounding cast types.


Symbol -  { }            

Name -     Braces                      

Purpose - Used to contain the values of automatically initialized arrays. Also used to define a block of code, for classes, methods, and local scopes.

  
Symbol -   [ ]              

Name -     Brackets                    

Purpose - Used to declare array types. Also used when dereferencing array values.


Symbol -   ;                

Name -     Semicolon                  

Purpose - Terminates statements.

Symbol -   ,                

Name -     Comma                      

Purpose - Separates consecutive identifiers in a variable declaration. Also used to chain statements together inside a for statement.


Symbol -  .                

Name -  Period                        

Purpose - Used to separate package names from subpackages and classes. Also used to separate a variable or method from a reference variable.



The Java Keywords

There are 49 reserved keywords currently defined in the Java language. These keywords, combined with the syntax of the operators and separators, form the definition of the Java language. These keywords cannot be used as names for a variable, class, or method.

Java Reserved Keywords

abstract,   continue,   goto,   package,   synchronized,   assert,   default,   if,   private,   this,   boolean,   do,   implements,   protected,   throw,   break,   double,   import,   public,   throws,   byte,   else,    instanceof,   return,   transient,   case,   extends,   int,   short,   try,   catch,   final,   interface,   static,   void,   char,   finally,   long,   strictfp,   volatile,   class,   float,   native,   super,   while,   const,   for,   new,   switch

The keywords const and goto are reserved but not used. In the early days of Java, several other keywords were reserved for possible future use. However, the current specification for Java only defines the keywords 

In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java. You may not use these words for the names of variables, classes, and so on.



The Simple Types

Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups:

■ Integers This group includes byte, short, int, and long, which are for wholevalued signed numbers.

■ Floating-point numbers This group includes float and double, which represent numbers with fractional precision.

■ Characters This group includes char, which represents symbols in a character set, like letters and numbers.

■ Boolean This group includes boolean, which is a special type for representing true/false values.

You can use these types as-is, or to construct arrays or your own class types. Thus, they form the basis for all other types of data that you can create.

The simple types represent single values—not complex objects. Although Java is otherwise completely object-oriented, the simple types are not. They are analogous to the simple types found in most other non–object-oriented languages. The reason for this is efficiency. Making the simple types into objects would have degraded performance too much.

The simple types are defined to have an explicit range and mathematical behavior. Languages such as C and C++ allow the size of an integer to vary based upon the dictates of the execution environment. However, Java is different. Because of Java’s portability requirement, all data types have a strictly defined range. For example, an int is always 32 bits, regardless of the particular platform. This allows programs to be written that are guaranteed to run without porting on any machine architecture. While strictly specifying the size of an integer may cause a small loss of performance in some environments, it is necessary in order to achieve portability.

Let’s look at each type of data in turn.

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.

Thursday 16 February 2017

A First Simple Program & Using Blocks of Code - Java Tutorials

A First Simple Program

look at some actual Java programs. Let’s start by compiling and running the short
sample program shown here. As you will see, this involves a little more work than
you might imagine.

/*
   This is a simple Java program.
   Call this file "Example.java".
*/
class Example {
  // Your program begins with a call to main().
  public static void main(String args[]) {
   System.out.println("This is a simple Java program.");
  }
}

Note:  The descriptions that follow use the standard Java 2 SDK (Software Development Kit), which          is available from Sun Microsystems. If you are using a different Java development environment,         then you may need to follow a different procedure for compiling and executing Java programs.            In this case, consult your compiler’s documentation for details.

Entering the Program

For most computer languages, the name of the file that holds the source code to a program is arbitrary. However, this is not the case with Java. The first thing that you must learn about Java is that the name you give to a source file is very important. For this example, the name of the source file should be Example.java. Let’s see why. 

In Java, a source file is officially called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension. Notice that the file extension is four characters long. As you might guess, your operating system must be capable of supporting long filenames. This means that DOS and Windows 3.1 are not capable of supporting Java. However, Windows 95/98 and Windows NT/2000/XP work just fine.

As you can see by looking at the program, the name of the class defined by the program is also Example. This is not a coincidence. In Java, all code must reside inside a class. By convention, the name of that class should match the name of the file that holds the program. You should also make sure that the capitalization of the filename matches the class name. The reason for this is that Java is case-sensitive. At this point, the convention that filenames correspond to class names may seem arbitrary. However, this convention makes it easier to maintain and organize your programs.

Compiling the Program

To compile the Example program, execute the compiler, javac, specifying the name of the source file on the command line, as shown here:

   C:\>javac Example.java

The javac compiler creates a file called Example.class that contains the bytecode version of the program. As discussed earlier, the Java bytecode is the intermediate representation of your program that contains instructions the Java interpreter will execute. Thus, the output of javac is not code that can be directly executed.

To actually run the program, you must use the Java interpreter, called java. To do so, pass the class name Example as a command-line argument, as shown here:

   C:\>java Example

When the program is run, the following output is displayed:

   This is a simple Java program.

When Java source code is compiled, each individual class is put into its own output file named after the class and using the .class extension. This is why it is a good idea to give your Java source files the same name as the class they contain—the name of the source file will match the name of the .class file. When you execute the Java interpreter as just shown, you are actually specifying the name of the class that you want the interpreter to execute. It will automatically search for a file by that name that has the .class extension. If it finds the file, it will execute the code contained in the specified class.

A Closer Look at the First Sample Program

Although Example.java is quite short, it includes several key features which are common to all Java programs. Let’s closely examine each part of the program. 
The program begins with the following lines:

   /*
   This is a simple Java program.
   Call this file "Example.java".
   */

This is a comment. Like most other programming languages, Java lets you enter a remark into a program’s source file. The contents of a comment are ignored by the compiler. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code. In this case, the comment describes the program and reminds you that the source file should be called Example.java. Of course, in real applications, comments generally explain how some part of the program works or what a specific feature does.

Java supports three styles of comments. The one shown at the top of the program is called a multiline comment. This type of comment must begin with /* and end with */.  Anything between these two comment symbols is ignored by the compiler. As the name suggests, a multiline comment may be several lines long. 
The next line of code in the program is shown here:

   class Example {

This line uses the keyword class to declare that a new class is being defined. Example is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace ({) and the closing curly brace (}). The use of the curly braces in Java is identical to the way they are used in C, C++, and C#. For the moment, don’t worry too much about the details of a class except to note that in Java, all program activity occurs within one. This is one reason why all Java programs are (at least a little bit) object-oriented.
The next line in the program is the single-line comment, shown here:

   // Your program begins with a call to main().

This is the second type of comment supported by Java. A single-line comment begins with a // and ends at the end of the line. As a general rule, programmers use multiline comments for longer remarks and single-line comments for brief, line-by-line descriptions.
The next line of code is shown here:

   public static void main(String args[]) {

This line begins the main( ) method. As the comment preceding it suggests, this is the line at which the program will begin executing. All Java applications begin execution by calling main( ). (This is just like C/C++.) The exact meaning of each part of this line cannot be given now, since it involves a detailed understanding of Java’s approach to encapsulation. However, since most of the examples in the first part of this book will use this line of code, let’s take a brief look at each part now.

The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.) In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values. If all this seems a bit confusing, don’t worry. All of these concepts will be discussed in detail in subsequent chapters.

As stated, main( ) is the method called when a Java application begins. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main( ) method.

Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If there are no parameters required for a given method, you still need to include the empty parentheses. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. (Arrays are collections of similar objects.) Objects of type String store character strings. In this case, args receives any command-line arguments present when the program is executed. This program does not make use of this information, but other programs shown later in this book will.

The last character on the line is the {. This signals the start of main( )’s body. All of the code that comprises a method will occur between the method’s opening curly brace and its closing curly brace.

One other point: main( ) is simply a starting place for your program. A complex program will have dozens of classes, only one of which will need to have a main( ) method to get things started. When you begin creating applets—Java programs that are embedded in Web browsers—you won’t use main( ) at all, since the Web browser uses a different means of starting the execution of applets. 
The next line of code is shown here. Notice that it occurs inside main( ).

   System.out.println("This is a simple Java program.");

This line outputs the string “This is a simple Java program.” followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. In this case, println( ) displays the string which is passed to it. As you will see, println( ) can be used to display other types of information, too. The line begins with System.out. While too complicated to explain in detail at this time, briefly, System is a predefined class that provides access to the system, and out is the output stream that is connected to the console.

As you have probably guessed, console output (and input) is not used frequently in real Java programs and applets. Since most modern computing environments are windowed and graphical in nature, console I/O is used mostly for simple, utility programs and for demonstration programs. Later in this book, you will learn other ways to generate output using Java. But for now, we will continue to use the console I/O methods.

Notice that the println( ) statement ends with a semicolon. All statements in Java end with a semicolon. The reason that the other lines in the program do not end in a semicolon is that they are not, technically, statements.

The first } in the program ends main( ), and the last } ends the Example class definition.



Using Blocks of Code

Java allows two or more statements to be grouped into blocks of code, also called code blocks. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for Java’s if and for statements. Consider this if statement:

    if(x < y) { // begin a block
      x = y;
      y = 0;
    } // end of block

Here, if x is less than y, then both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and one statement cannot execute without the other also executing. The key point here is that whenever you need to logically link two or more statements, you do so by creating a block.

Let’s look at another example. The following program uses a block of code as the target of a for loop.

    /*
      Demonstrate a block of code.

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

      y = 20;

      // the target of this loop is a block
      for(x = 0; x<10; x++) {
        System.out.println("This is x: " + x);
        System.out.println("This is y: " + y);
        y = y - 2;
      }
    }
  }

The output generated by this program is shown here:

This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2

In this case, the target of the for loop is a block of code and not just a single statement. Thus, each time the loop iterates, the three statements inside the block will be executed. This fact is, of course, evidenced by the output generated by the program.

As you will see later in this book, blocks of code have additional properties and uses. However, the main reason for their existence is to create logically inseparable units of code.