Download Chapter 2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Notes adopted from “Java Programming-Thomson Learning”
Chapter 2
Chapter Overview
In this chapter, students will learn the basics of programming in Java. Fundamental topics include data
types, arithmetic operations, precedence rules, type casting, input and output, and assignment operators.
The chapter also covers the basic structure of a Java program, including the import statement and
commenting.
Chapter Objectives
In this chapter, students will:
• Become familiar with the basic components of a Java program, including methods, special symbols,
and identifiers
• Explore primitive data types
• Discover how to use arithmetic operators
• Examine how a program evaluates arithmetic expressions
•
•
•
•
•
•
•
Explore how mixed expressions are evaluated
Learn about type casting
Become familiar with the String type
Learn what an assignment statement is and what it does
Discover how to input data into memory by using input statements
Become familiar with the use of increment and decrement operators
Examine ways to output results using output statements
•
•
•
Learn how to import packages and why they are necessary
Discover how to create a Java application program
Explore how to properly structure a program, including using comments to document a program
Introduction
A computer program, or a program, is a sequence of statements whose objective is to accomplish a task.
Programming is a process of planning and creating a program. Learning a programming language
requires direct interaction with the tools. You must have a fundamental knowledge of the language, and
you must test your programs on the computer to make sure that each program does what it is supposed to
do.
The Basics of a Java Program
A programming language is a set of rules, symbols, and special words. The syntax rules of a language
determine which instructions are valid. The semantic rules determine the meaning of the instructions.
Together these rules enable you to write programs to solve problems. The smallest individual unit of a
program written in any programming language is called a token. Java’s tokens are divided into special
symbols, word symbols, and identifiers.
Chapter2_1
Notes adopted from “Java Programming-Thomson Learning”
The following are special symbols in Java.
+-*/
.;?,
<= != == >=
The first row of symbols includes mathematical symbols for addition, subtraction, multiplication, and
division. In Java, commas are used to separate items in a list. Semicolons are used to end a Java
statement. The symbols in the third row are used for comparisons.
Word symbols are called reserved words, or keywords and include int, float, double, char, void, public,
static, throws, return.
A Java identifier consists of letters, digits, the underscore character ( _), and the dollar sign ($), and must
begin with a letter, underscore, or the dollar sign.
Data Types
The objective of a Java program is to manipulate data. A Data type is a set of values together with a set
of operations. Only certain operations can be performed on a particular type of data. There are three
primitive data types: integral, floating-point, and boolean.
The integral data type deals with integers, or numbers without a decimal part.
categories: char, byte, short, int, long.
It is classified into five
The char data type is used to represent single characters such as letters, digits, and special symbols. It
can represent any key on your keyboard. Each character represented is enclosed within single quotation
marks. Only one symbol can be placed between the single quotation marks. The char data type is used
to represent integers between 0 and 65535.
The int data type is used to represent integers between –2147483648 and 2147483647.
The data type short is used to represent integers between –32768 and 32767.
The floating-point data type deals with decimal numbers. To represent real numbers, Java uses a form
of scientific notation called floating-point notation. The data types float and double are used to
manipulate decimal numbers. Floats represent any real number between –3.4E+38 and 3.4E+38. The
memory allocated for the float data type is 4 bytes. Doubles are used to represent any real number
between –1.7E+308 and 1.7E+308.The memory allocated for the double data type is 8 bytes. The
maximum number of significant digits in float values is 6 or 7, while the maximum number of
Chapter2_2
Notes adopted from “Java Programming-Thomson Learning”
significant digits in double values is 15.
Arithmetic Operators and Operator Precedence
There are five arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% mod (modulus) operator
An arithmetic expression is constructed by using arithmetic operators and numbers. The numbers in the
expression are called operands. Moreover, the numbers used to evaluate an operator are called the
operands for that operator. Operators that have only one operand are called unary operators.
Operators that have two operands are called binary operators.
Java uses operator precedence rules to determine the order in which operations are performed to evaluate
the expression. According to the order of precedence rules for arithmetic operators, *, /, % have a
higher level of precedence than + and -. When operators have the same level of precedence, operations
are performed from left to right.
Expressions
If all operands in an expression are integers, the expression is called an integral expression. If all
operands in an expression are floating-point numbers, the expression is called a floating-point or decimal
expression. Evaluating an integral or a floating-point expression is straightforward. The precedence
rules for operators are simply followed.
1. When evaluating an operator in a mixed expression:
a. If the operator has the same types of operands (that is, both are integers or both are floating-point
numbers), the operator is evaluated according to the type of the operand. Integer operands yield an
integer result; floating-point numbers yield a floating-point number result.
b. If the operator has both types of operands (that is, one is an integer and the other is a floating-point
number), during calculation the integer is changed to a floating-point number with the decimal part of
zero, and then the operator is evaluated. The result is a floating-point number.
2. The entire expression is evaluated according to the precedence rules. The multiplication, division, and
modulus operators are evaluated before the addition and subtraction operators. Operators having the
same level of precedence are evaluated from left to right. Grouping is allowed for clarity.
Type Conversion (Casting)
When a value of one data type is automatically changed to another data type, implicit type coercion has
Chapter2_3
Notes adopted from “Java Programming-Thomson Learning”
occurred. To avoid implicit type coercion, Java provides for explicit type conversion through the use of
a cast operator. The cast operator, also called the type conversion or type casting, takes the following
form:
(dataTypeName) expression
First, the expression is evaluated. Its value is then converted to a value of the type specified by
dataTypeName. When using the cast operator to convert a floating-point (decimal) number to an integer,
you simply drop the decimal part of the floating-point number. You can also use cast operators to
explicitly convert char data values into int data values, and int data values into char data values. To
convert char data values into int data values, you use a collating sequence.
The class String
A string is a sequence of zero or more characters. Strings in Java are enclosed in double quotation marks.
To process strings effectively, Java provides the class String. The class String contains various
operations to manipulate a string. A string that contains no characters is called a null or empty string.
A string consisting of only integers or decimal numbers is called a numeric string. In order to be
manipulated as numbers these strings must be converted into numeric form. The following Java
expressions perform the necessary conversions:
1. Integer.parseInt(strExpression) converts a string consisting of an integer to a value of the type int.
2. Float.parseFloat(strExpression) converts a string consisting of a decimal number to a value of the type
float.
3. Double.parseDouble(strExpression) converts a string consisting of a decimal number to a value of the
type double.
Input
In order to store data in the computer’s memory you must first instruct the computer to allocate memory
and then include statements in the program to put data into the allocated memory.
When you instruct the computer to allocate memory, you tell it what names to use for each memory
location, and what type of data to store in those memory locations. Knowing the location of data is
essential because data stored in one memory location might be needed at several places in the program.
It is also critical to know whether your data must remain fixed throughout program execution or whether
it should change.
A named constant instructs a program to mark memory locations in which data is fixed throughout
Chapter2_4
Notes adopted from “Java Programming-Thomson Learning”
program execution. Declaration statements allocate memory. The syntax to declare a named constant is:
static final dataType IDENTIFIER = value;
static and final are both reserved words. The reserved word final specifies that the value stored in the
identifier is fixed and cannot be changed. The reserved word static may or may not appear when a
named constant is declared. Using a named constant to store fixed data, rather than using the data value
itself, has one major advantage. If the fixed data changes, you do not need to edit the entire program and
change the old value to the new value. Instead, you can make the change at just one place, recompile the
program, and execute it using the new value throughout. In addition, by storing a value and referring to
that memory location whenever the value is needed, you avoid typing the same value again and again
and you prevent typos.
Memory cells whose contents can be modified during program execution are called variables. The
syntax for declaring one variable or multiple variables is:
dataType identifier1, identifier2, ..., identifierN;
You can place data into a variable by using assignment statements or input (read) statements.
assignment statement takes the following form:
variable = expression;
The
The value of the expression should match the data type of the variable. The expression on the right side
is evaluated, and its value is assigned to the variable (and thus to a memory location) on the left side. A
variable is initialized the first time a value is placed in the variable. In Java, = (the equals sign) is called
the assignment operator.
To save the value of an expression and use it in a later expression, do the following:
1. Declare a variable of the appropriate data type. For example, if the result of the expression is an
integer, declare an int variable.
2. Use the assignment statement to assign the value of the expression to the variable that was declared.
This action saves the value of the expression into the variable.
3.
Wherever the value of the expression is needed, use the variable holding the value.
Java might not automatically initialize all the variables, therefore Java allows you to initialize variables
while they are being declared.
Putting data into variables from the standard input device is accomplished by using the standard input
stream object, System.in. The data entered from the standard input device are characters, and the object
System.in extracts data in the form of bytes from the input stream. Therefore, using System.in, we must
first create another input stream object to read characters from the input stream.
Chapter2_5
Notes adopted from “Java Programming-Thomson Learning”
To read characters from the input stream, you declare and initialize a variable as follows:
InputStreamReader charReader = new InputStreamReader(System.in);
To read the entire line of characters you must declare and initialize another input stream variable as
follows:
BufferedReader keyboard = new BufferedReader(charReader);
BufferedReader and InputStreamReader are stream classes that provide the necessary operations for
inputting data into a program. Variables such as keyboard and charReader are called input stream objects
of the classes InputStreamReader and BufferedReader, respectively.
Any data you enter from the keyboard (whether numbers or letters or spaces) is a sequence of characters.
Therefore, the numeric data is also read as a sequence of characters.
The method read (associated with the class BufferedReader) reads a single character and returns the
integer value of the character.
Consider the following declaration:
int feet;
You can initialize the variable feet to a value of 35 either by using the assignment statement:
feet = 35;
or by executing the following statement and entering 35 during program execution:
feet = Integer.parseInt(keyboard.readLine());
By using an input statement, each time the program runs, you are prompted to enter a value, and the
value entered is stored in feet. Sometimes it is necessary to initialize a variable by using an assignment
statement. This is especially true if the variable is used only for internal calculation and not for reading
and storing data.
Increment and Decrement Operators
Java provides the increment operator, ++, which increases the value of a variable by 1, and the
decrement operator, --, which decreases the value of a variable by 1. Increment and decrement operators
each have two forms, pre and post. The syntax of the increment operator is:
Pre-increment: ++variable
Chapter2_6
Notes adopted from “Java Programming-Thomson Learning”
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: --variable
Post-decrement: variable-The pre-increment adds 1 to the variable before the expression is evaluated, while the post-increment
adds 1 to the variable after the expression is evaluated. Similarly, the pre-decrement subtracts 1 from
the variable before it is evaluated in an expression, while post-decrement subtracts the value 1 from the
variable after the expression is evaluated.
Strings and the Operator +
The operator + can be used to concatenate two strings, as well as a string and a numeric value or a
character.
Example:
String str1 = “Hello”;
String str2 = “World”;
String str3 = str1 + “ “ + str2;
The value in str3 is “Hello World”
Output
In Java, output on the standard output device is accomplished by using the standard output object
System.out. The object System.out has access to two methods, print and println, to output a string on the
standard output device.
The syntax to use the object System.out and the methods print and println is:
System.out.print(stringExp);
System.out.println(stringExp);
The following escape sequences exist in Java:
\n Newline: Insertion point moves to the beginning of the next line
\t Tab: Insertion point moves to the next tab stop
\b Backspace: Insertion point moves one space to the left
\r Return: Insertion point moves to the beginning of the current line (not the
next line)
\\ Backslash: Backslash is printed
Chapter2_7
Notes adopted from “Java Programming-Thomson Learning”
\' Single quotation: Single quotation mark is printed
\" Double quotation: Double quotation mark is printed
Packages, Classes, Methods and the Import Statement
A package is a collection of related classes. Moreover, every package has a name. The term class is
used to create Java programs—either application or applet; it is used to group a set of related operations;
and it is used to allow users to create their own data types. Each of these operations is implemented
using the Java mechanism of methods. A method is a set of instructions designed to accomplish a
specific task. To make use of the existing classes, methods, and identifiers, you must specify the
packages that contain the appropriate information using the reserved word import and importing the
contents of the package into the program as follows:
import packageName.*;
Creating a Java Application Program
The basic unit of a Java program is called a class. A Java application program is, therefore, a collection
of one or more classes. One of the classes in a Java application program must have the method called
main. Moreover, there can be only one method main in a Java program. If a Java application program
has only one class, it must contain the method main. Statements to declare memory spaces (named
constants and variables), statements to create input stream objects, statements to manipulate data (such
as assignments), and statements to input and output data will be placed within the class. Statements to
declare named constants and input stream objects are usually placed outside the method main, and
statements to declare variables are usually placed within the method main. Statements to manipulate data,
and input and output statements are placed within the method main.
The syntax of a class to create a Java application program is:
public class ClassName
{
classMembers
}
where ClassName is a user-defined Java identifier; classMembers consists of data members and methods
(such as the method main). In Java, public and class are reserved words.
The general syntax of the method main is:
public static void main(String[] args) throws clause
Chapter2_8
Notes adopted from “Java Programming-Thomson Learning”
{
statement1
.
.
.
statementn
}
where throws clause consists of exceptions thrown by the method main. If there is more than one
exception, they are separated by commas. An exception is an occurrence of an undesirable situation that
can be detected during program execution.
The import statements and the program statements constitute the Java source code. This source code
must be saved in a file, called a source file that has the name extension .java. The name of the class
and the name of the file containing the Java program must be the same.
public static void main(String[] args) throws clause is called the heading of the method main.
The statements enclosed between curly braces ({ and }) form the body of the method main. The body of
the method main contains two types of statements: Declaration statements and Executable statements.
Declaration statements are used to declare things such as variables. Executable statements perform
calculations, manipulate data, create output, accept input, and so on. Variables or identifiers can be
declared anywhere in the program, but must be declared before they can be used.
Skeleton of a program:
import statements if any
public class ClassName
{
declare named constants and or stream objects
public static void main(String[] args) throws IOException
{
variable declaration
executable statements
Chapter2_9
Notes adopted from “Java Programming-Thomson Learning”
}
}
Programming Style and Form
Every Java application program must satisfy certain language rules. It must also satisfy the syntax rules.
The syntax rules of a language tell what is legal and what is illegal. Errors in syntax are detected during
compilation. Correct syntax errors in the order in which the compiler lists them. Some general rules
for programming in Java follow.
Use blanks to separate numbers when data is input. They are also used to separate reserved words and
identifiers from each other and from other symbols. They must never appear within a reserved word or
identifier. All Java statements must end with a semicolon. The semicolon is also called a statement
terminator.
The set of rules that gives meaning to a language is called semantics. The clarity of the rules of syntax
and semantics frees you to adopt formats that are pleasing to you and easier to understand.
A well-documented program is easier to understand and modify, even a long time after you originally
write it. You use comments to document programs. Comments should appear in a program to explain the
purpose of the program, identify who wrote it, and explain the purpose of particular statements. Single
line comments begin with //, can be placed anywhere in the line, and everything after the // is ignored by
the compiler. Multiple line comments are enclosed between /* and */. The compiler ignores anything
that appears between /* and */.
When naming identifiers, choose self-documenting names.
Traditionally, identifiers used by Java programmers to name named constants, variables, and classes
follow these rules:
1. An identifier used to name a named constant is all uppercase. If the identifier is a run-together-word,
then the words are separated with the underscore character.
2. An identifier used to name a variable is lowercase. If the identifier is a run-together-word, then the
first
letter of each word, except the first word, is uppercase.
3. An identifier used to name a class is all lowercase with the first letter of each word in uppercase.
Prompt lines are executable statements that inform the user what to do.
More on Assignment Statements
Chapter2_10
Notes adopted from “Java Programming-Thomson Learning”
In general, using the compound operator *=, you can rewrite the simple assignment statement
variable = variable * (expression);
as
variable *= expression;
Similar conventions apply to the other arithmetic compound operators. For example, using the
compound operator +=, you can rewrite the simple assignment statement
variable = variable + (expression);
as
variable += expression;
The compound assignment statement lets you write simple assignment statements in a concise fashion
by combining an arithmetic operator with an assignment operator.
Programming Example: Convert Length
This program converts measurements in feet and inches into centimeters using the formula that 1 inch is
equal to 2.54 centimeters. It uses the following steps to come up with the final code solution.
Step 1: Problem Analysis and Algorithm Design
Step 2: Declaring Variables
Step 3: Stating Named Constant
Step 4: Main Algorithm
Step 5: Putting it all together and producing final code
The main algorithm for this program is:
1. Prompt the user for the input. (Without a prompt line, the user will stare at a blank screen and not
know what to do.)
2. Get the data using the readLine method.
3. Echo the input—output what the program read as input.(Without this step, after the program has
executed, you will not know what the input was.)
4. Find the length in inches.
5. Output the length in inches.
6. Convert the length to centimeters.
Chapter2_11
Notes adopted from “Java Programming-Thomson Learning”
7. Output the length in centimeters.
Programming Example: Make Change
Given any amount of change expressed in cents, this program computes the number of half-dollars,
quarters, dimes, nickels, and pennies to be returned, returning as many half-dollars as possible, then
quarters, dimes, nickels, and pennies, in that order. It uses the steps outlined in the last section to come
up with the following algorithm and then displays the final java code solution.
Main Algorithm:
1. Prompt the user for input.
2. Get input using readLine method and convert input string into integer using Interger.parseInt method.
3. Echo the input by displaying the entered change on the screen.
4. Compute and print the number of half-dollars.
5. Calculate the remaining change.
6. Compute and print the number of quarters.
7. Calculate the remaining change.
8. Compute and print the number of dimes.
9. Calculate the remaining change.
10.Compute and print the number of nickels.
11.Calculate the remaining change.
12.Print the remaining change.
Key Terms
Binary operator: An operator that has two operands.
Data type: A set of values together with a set of operations.
Identifier: A Java identifier consists of letters, digits, the underscore character ( _), and the dollar
sign ($), and must begin with a letter, underscore, or the dollar sign.
Mixed expression: An expression that has operands of different data types.
Named constant: A memory location whose content is not allowed to change during program
execution.
Programming language: A set of rules, symbols, and special words.
Semantic rules: determine the meaning of instructions in a programming language.
Syntax rules: determine the validity of instructions in a programming language.
Token: The smallest individual unit of a program written in any programming language.
Unary operator: An operator that has only one operand.
Variable: A memory location whose content may change during program execution.
Chapter2_12