DOC

InputStreamReader(Systemin))

By Frederick Willis,2014-05-21 12:20
13 views 0
InputStreamReader(Systemin))

Chapter 1

    An Overview of the Java

    Language

    1 Introduction

    The purpose of this chapter is to give you a brief introduction to the Java language. It is not a tutorial on how to program, and even less a guide to how to program well. We'll spend a large part of this book discussing how programs should be written, but the aim of this chapter is simply to introduce you to the most basic syntax and intuitive semantics of Java. If you already know Java, you can probably just skim the chapter. We assume that you already have experience programming in a high level language (such as C, C++ or Pascal), including such basic programming concepts as variables, assignment, simple input and output (I/O), conditional execution, loops, and subroutines (called methods in

    Java parlance). If you don't know how to program, this chapter won't help you. We take a spiral approach to introducing Java concepts, introducing just enough at first to get you going, and adding details later. This approach works well pedagogically, but makes for a frustrating reference. We recommend that you have an introductory Java text handy that contains a detailed reference section.

    It is not necessary to read and master this chapter all at one time. We have concentrated the Java language material in this one chapter rather than spreading it out through the book. You should read the first sections of this chapter before going on to Chapter 2, but other sections can wait until you are ready to read later chapters. Each section in this chapter is keyed to later chapters. Similarly, each chapter has a prerequisite section telling which sections of this chapter are required reading. So, let's begin.

2 A first program

    The simplest Java program is a sequence of zero statements; interesting programs are necessarily longer. We'll begin by introducing the parts of the language necessary for the

    ? 2001 Donald F. Stanat and Stephen F. Weiss

    Chapter 1 Java Overview Page 2

    1 Look over the program. Some of it may look familiar; other parts following program.

    look like magic incantations (and in some ways they are). Program output is shown on

    the next page.

1The programs of this chapter are meant to illustrate the characteristics of the Java language, and

    although we will make an effort not to violate rules of good programming practice, many of the

    programs will be neither exemplary nor interesting.

    2010-5-21 12:21 PM

Chapter 1 Java Overview Page 3

/*********************************** Program 0: A very gentle introduction to Java Description: This program greets the user, requests two integers, then displays the sum, product, and quotient of the integers. */ import java.io.*; public class Program0 { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); int num1; // Holds the two integers entered. int num2; String name; // Holds name. // Greet the user. System.out.println("Hello"); System.out.print("What is your name? -> "); name=stdin.readLine(); System.out.println("Hello "+name); // Request and read two integers. System.out.print("Please enter the first integer. -> "); num1=Integer.parseInt(stdin.readLine()); System.out.print("Please enter the second integer. -> "); num2=Integer.parseInt(stdin.readLine()); // Display sum, product and quotient of two integers. System.out.println("\nThe sum of "+num1+" and "+num2+ " is "+(num1+num2)); System.out.println("The product of "+num1+" and "+num2+ " is "+(num1*num2)); System.out.println("The quotient of "+num1+" and "+num2+ " is "+(((double)num1)/num2)); // Wait before quitting. System.out.println("\nPlease hit enter to quit."); name=stdin.readLine(); System.out.println("\nEnd of job"); } // End of main method. } // End of Program0 class.

2010-5-21 12:21 PM

Chapter 1 Java Overview Page 4

This program contains comments that are directed to the reader of the program,

    declarations of variables, expressions that calculate values, assignment statements that store the values of expressions in variables and input and output statements.

3 Program annotations: Comments

    Comments are program annotations that are intended to aid a reader in understanding a

    program -- what it does, how it works, limitations, etc. Comments do not affect program

    execution in any way.

    Java comments occur in two distinct forms. A comment of any size and covering any

    number of lines can be inserted anywhere in a Java program by enclosing the comment

    /* and */, which serve as left and right brackets for the comment. For text within

    example:

     /* Read in the radius of a circle and the length of a side of a square and display the areas of the circle and the square. */

    Comments delimited by the /* and */ can, in fact, occur in the midst of a program

    statement; thus

    sam = george /* This is not usually a good idea. */ + bill;

    will have exactly the same effect as

    2010-5-21 12:21 PM

Chapter 1 Java Overview Page 5

    sam = george + bill;

    Note that comments that are begun with /* must be explicitly terminated with a */.

    The second comment form is commonly used for brief comments. Two consecutive

    slashes (//) signal the beginning of the comment; the comment is terminated by the 'return' character that terminates each line of the program. For example, in the following

    program segment, the first line contains variable declarations followed by a comment,

    while the next non-blank line contains only a one line comment.

    int radius, side; // The lengths of the radius and the side. // Prompt for and read input.

    4 Java Identifiers The power of a programming language is largely a function of the support it provides for

    abstraction. An abstraction is usually represented by a name. Two rules are needed. The

    first rule establishes what names are acceptable. The second rule establishes the scope of

    a name; that is, where in a program a name will be recognized, or “make sense." We will

    look at names first and scope a little later.

    4.1 Identifier Names

    Program entities are either named or anonymous. Identifiers are names given by a

    programmer to program entities, including variables, constants, methods, classes, etc.

    There are two rules plus some guidelines for creating identifiers. First, a Java identifier

    must begin with a letter, which can then be followed by an arbitrary number of letters,

    digits, and the underscore character. Upper and lower case letters are different. Second,

    the identifiers must not duplicate Java's reserved words. As we learn Java, we will

    encounter most of these reserved words. Your Java reference will have a complete list.

    The following identifiers are all legal and all different.

     Rate_of_pay rate_of_pay rateOfPay r2d2 Average average

    The following names are all illegal for the reasons indicated.

    2010-5-21 12:21 PM

Chapter 1 Java Overview Page 6

     3D Starts with something other than a letter Rate of pay Contains illegal characters: blanks. Rate-of-pay Contains illegal characters: dashes. Delta* Contains an illegal character: asterisk. for Java reserved word.

    In addition to these rules, there are several guidelines for creating names. First, the name

    should be mnemonic, that is, suggestive of the thing being named. While it is completely

    legal to name a variable that holds the number of hours an employee worked in a week in

    honor of your spouse, your dog, or your favorite wrestler, it is far better to use something

    like hourWorkedThisWeek. Second, Java has established some naming conventions that relate the name to the thing being named. Class names begin with a capital letter;

    identifiers within a class begin with a lower case letter, but can use subsequent upper case

    letters for readability (e.g. in rateOfPay), and constants are named with all upper case

    letters (e.g. PI). Finally, while there is no limit on the length of identifiers, making them

    too long can get tedious and can increase the possibility of making a typing error. So

    while

     the_number_of_days_I_worked_a_full_day_this_week

    is a legal name, it is probably not a very good idea.

    5 Java primitive data types Java supports four basic primitive data types: integers (optionally signed numbers with no

    fractional part), real numbers (optionally signed numbers with a fractional part, even if

    the fractional part is zero), booleans (true and false), and single characters (such as 'a', '3',

    and '%'). The integers and real numbers come in several flavors.

    5.1 Integers

    Java supports four flavors of integer data, each implemented using a different amount of

    memory and each having a different range of possible values. The table below shows the

    four types: byte, short, int, and long, along with the number of bytes each occupies

    and the range of values.

     type memory required range byte 1 byte -128...127 short 2 bytes -32,768...32,767 int 4 bytes -2,147,483,648...2,147,483,647 long 8 bytes -9,223,372,036,854,775,808... 9,223,372,036,854,775,807

    Notice the asymmetry in the range; there is one more negative number than positive. One

    byte, for example can hold any one of 256 values from 00000000 through 11111111. If

    one of those values represents zero, that leaves an odd number of values to represent the

    nonzero numbers. The integer representation used by most computers represents zero as

    2010-5-21 12:21 PM

Chapter 1 Java Overview Page 7

    00000000, the positive numbers with a leading zero (for example, 00000001 through

    01111111), and the negative numbers with a leading 1 (10000000 through 1111111).

    That gives one more negative number than positive since zero is taken out of the positive

    side.

    5.2 Real numbers

    float, which uses four bytes and double, which Java has two flavors of real numbers:

    uses eight bytes. Reals are represented in memory in scientific notation with a magnitude 24and exponent (for example, 6.02x10, although computers use a power of 2 rather than

    10 as the exponent base). As a concession to the keyboard, Java, and most other

    programming languages use the letter 'E' to mean "times ten to the power." Hence in Java 24we will write 6.02E24 to represent 6.02x10.

     type memory required range (approximate)

    38 float 4 bytes Approx. ?3.4x10 with 7 significant digits

     308 double 8 bytes Approx. ?1.7x10 with 15 significant digits

While float and double numbers can be astronomically large or incredibly small, they

    cannot represent all real numbers. We shouldn't be surprised that irrational numbers such

    as pi cannot be represented exactly nor can nonterminating numbers such as 1/3. But lots

    of numbers that seem very innocent in our decimal system, such as 0.1, cannot be

    represented exactly using float or double. This can lead to some small, yet insidious errors in computation.

    5.3 Booleans

    Boolean data types, denoted by boolean, can take on one of only two possible values:

    true or false. Boolean values generally represent the result of a test or a flag.

    5.4 Character

    The character data type, denoted by char, can represent a single character. Java uses the

    single quotes to denote a character, for example 'a', '3', and '%'. Note that the space, ' ', is a valid character; it just has no associated graphic. An obvious question is "how

    do I indicate the quote character?" Java uses escape sequences a backslash followed by a character indicating which character is intended. The two-character escape sequence is

    treated as a single character.

    2010-5-21 12:21 PM

Chapter 1 Java Overview Page 8

     \b backspace \t tab \n new line \r carriage return \" double quote \' single quote \\ backslash

    While there is lots we can do with these four basic data types, we quickly discover the

    need for additional types. We will see soon how Java implements additional data types

    and how you can create your own.

5.5 Variables

    An instance of one of the primitive types, called a variable, is created by using the name of the type followed by the name of a variable followed by a semicolon. For example,

     int counter;

    creates a 4-byte integer variable with the name counter. You can optionally initialize the value of the variable as follows.

     int counter = 0;

    Variables of the other types can be created and initialized similarly.

     int hoursWorked = 40; double interestRate = 3.456; boolean finished = false; char initial = 'A';

    If you don't initialize a variable, Java will usually (but not always we will see an exception later) initialize the variable automatically to something reasonable (0 for

    numeric variables; false for boolean; the null character for char). However, it is best not

    to rely on Java's implicit initialization.

    5.6 Constants

    The value of a variable can change over the course of a program's execution (and hence

    the name "variable"). But sometimes we want to represent numbers or other values

    whose value is fixed. These are called, appropriately, constants. Java allows constants to be defined much like variables, but with the keyword "final" preceding the type. The initialization part of the constant definition is required. And once the value is set, it

    cannot be changed. Notice we follow the convention of naming constants using all upper

    case letters.

    2010-5-21 12:21 PM

Chapter 1 Java Overview Page 9

     final int STANDARD_WEEK = 40; // Number of hours in a // standard work week final double PI = 3.14159; final LAST_LETTER = 'Z';

5.7 Expressions

    Values can be combined into an expression using a variety of Java operators. The table

    below summarizes just some of the operations.

     Arithmetic operations (expressions have an arithmetic value)

     + addition

    - subtraction

     * multiplication

     / division

     % modulo (the remainder after integer division)

     Logical operators (expressions have a boolean value)

     == equality test

     != not equal

     > >= greater than, greater than or equal to

     < <= less than, less than or equal to

     Boolean operators (require boolean operands and

     has boolean value)

     && boolean and (true if both operands are true)

     || boolean or (true if either or both operands are true)

     ! boolean not (opposite of operand)

As with virtually all programming languages, operators have different precedence; higher

    precedence operators in expressions are evaluated before lower precedence operators.

    Multiplicative operations (multiplication, division, and modulo) are performed before

    additive operations (addition and subtraction). In case of ties, operations are preformed

    left to right. You can always override the implicit precedence by using parentheses. A

    piece of an expression inside the parentheses is evaluated before the part outside the

    parentheses. Redundant parentheses are not wrong and can actually help in

    understanding by making the precedence explicit. Below are some sample expressions

    and their value.

     1+2+3 6

     1+2*3 7 (multiplication is performed first)

     (1+2)*3 9 (parentheses force addition to be done first)

     4-3-2 -1 (subtractions done left to right)

     4-(3-2) 3 (parentheses force 3-2 to be perfumed first)

Variables can also be used in expressions; the value of the expression depends on the

    values of the variables involved and the operations performed.

    2010-5-21 12:21 PM

Chapter 1 Java Overview Page 10

    If all the operands in an expression are of the same type, then the value of the expression

    is also of the that type. This seems completely reasonable when adding, subtracting, or

    multiplying integers; the value is always an integer. But division of integers in Java also

    yields an integer quotient. Essentially, any fractional part resulting from the division of

    integers is thrown away. If an expression contains a mixture of integers and reals, then

    the value is real.

     6/2 3

     5/2 2 (fractional part is lost)

     1/3 0 (fractional part is lost)

     1.0/3 .33333 (real value)

     1.5+10/4 3.5 (integer subexpression 10/4 is evaluated first yielding

     2 which is then added to 1.5 yielding 3.5)

    Types can be changed by casting preceding a value of one type by the name of another type in parentheses. Hence, for example, the expression

     (double)5

    has the double value 5.0. And the value of

     (int)3.95

    is the int value 3. The fractional part is thrown away when casting a real as an integer.

    Casting has the highest precedence. The expression

     1.25+(double)10/4

    has the double value 3.75. The casting turns 10 into 10.0, which is then divided by 4.

    The mixed type division yields the double value of 2.5, which is then added to 1.25. Characters can be cast as the corresponding integer in the Java character code (see your

    Java reference). Conversely, an integer in the appropriate range can be cast to a character.

     (int) 'a' has the value 97 (char) 90 has the value 'Z'

    Boolean expressions generally involve comparison of operands and yield a boolean value.

     3==4 false 5==5 true 3+1==5-1 true (arithmetic operators have higher precedence than the comparison) 3>=5 false !(4<=5) false (4<=5 has the value true; the not operator (!) reverses the value.

Again valuables can be used anywhere in the expressions.

    Java evaluates boolean expressions using lazy or short circuit evaluation. This means

    that Java evaluates a boolean expression from left to right until the final value is known,

    then stops. For example, the expression

    2010-5-21 12:21 PM

Report this document

For any questions or suggestions please email
cust-service@docsford.com