Operators


Statements And Expressions

Java programs contain a series of statements and expressions. For the most part these statements are terminated by a semicolon. In fact, one type of valid statement in the Java programming language is the empty statement:

 ;

The empty statement is simply a semicolon. It could appear on a line by itself but it doesn’t have to. Two statements could appear on the same line like so:

 ;;

The following statement is known as an expression statement:

 int variable_name = 3;

A series of statements can be contained within a block. A block of statements is contained within a set of curly braces. Study the code shown in example 6.15.

Example 6.15: StatementTest.java

image from book
 1    public class StatementTest { 2 3      public static void main(String[] args){ 4       ; 5       ;; 6       enclosed_block_1: { 7          int variable_name = 3; 8          System.out.println(variable_name); 9        } 10 11      enclosed_block_2: { 12         int variable_name = 5; 13         System.out.println(variable_name); 14        } 15     } //end main() method body 16   } // end StatementTest class definition
image from book

The StatementTest class contains a main() method. The statements comprising the main() method are contained within its body which is denoted by the opening brace appearing at the end of line 3 and the closing brace appearing on line 15.

The main() method contains several types of statements. Line 4 has one empty statement and line 5 has two empty statements. Line 6 is interesting because it provides a labeled statement block named enclosed_block_1. The enclosed_block_1 statement block body is contained between its opening brace on line 6 and its closing brace on line 9. All variables declared and used within that block of code are said to be local to that block of code.

Line 11 begins another labeled statement block named enclosed_block_2. Notice that another variable named variable_name is declared and used within that statement block. Figure 6-15 shows the results of running example 6.15.

image from book
Figure 6-15: Results of running Example 6.15

You will be gradually introduced to the other types of Java statements and expressions as you progress through the text. But keep example 6.15 in mind because the points it illustrates will be very helpful to you when you learn how to declare class methods that contain local variables.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net