Upload
david-beasley
View
218
Download
4
Embed Size (px)
Citation preview
Chapter 4
Variables and Constants
Goals and Objectives1. Understand simple data
types (int, boolean, double).2. Declare and initialize
variables using the appropriate data type.
3. Choose legal identifiers that follow good programming style.
4. Differentiate between primitive types and objects (abstract data types).
5. Describe classes.6. Explain how to access
members of a package.7. Identify reusable
components from existing code using classes and class libraries.
8. Demonstrate how to read data through an input stream.
9. Write numeric expressions.10. Declare and initialize
constants using the appropriate data type.
11. Use type casting appropriately.
12. Format numeric output.13. Identify Java keywords.14. Categorize errors as
compile-time, run-time, logic.
15. Understand run-time exceptions.
16. Read and understand a problem description, purpose, and goals.
Declaring VariablesVariable – is a meaningful name for a value stored in memory with.Variables make code easier to read, understand, and modify.Declaration – all variables must be declared before it is used. Form of a declaration:– <data type> <name>
Two parts of a declaration:– 1. Data Type – determines the type of data
the variable will store.– 2 . Identifier - is the variable name.
Primitive Data Types8 primitive data types:– byte – represents Integer values.– short – represents Integer values.– int – represents Integer values.– long – represents Integer values.– float – represents Real values.– double – represents Real values.– char – represents character values
(a single letter).– boolean – represents True or False
Primitive Data Types
Type Storage Requiredbyte 1 bytesshort 2 bytesint 4 bytes **APlong 8 bytesfloat 4 bytesdouble 8 bytes **APchar 2 bytesboolean 1 bit **AP
Sizes
BIT – Binary digIT – 1 or 0 smallest memory unit.Nibble – 4 bitsByte (1 byte) – 8 bits Half Word (2 bytes) – 16 bitsWord (4 bytes) – 32 bitsLong Word (8 bytes)– 64 bitsThe term byte was coined by Dr. Werner Buchholz in July 1956, during the early design phase for the IBM Stretch computer The term byte stems from bite, as in the largest amount of data a computer could bite at once
Naming VariablesName should be descriptive and avoid using single letters.Rules:– First character should be a letter followed
by letters, digits, and under score.– No spaces– When using two words, the second word
first letter should capitalized.Examples:int mySum, f67th34; //validInvalid:– 5temp, my Total,
Assignment Statement (Initialization)
An assignment statement gives a value to a variable.
Assignment can take several forms:
x = 5; a literal (5) is assigned to x
x = y + 2; the value of an expression (y + 2) is assigned to x
x = z; the value of another variable (z) is assigned to x
Variable Assignment
A variable can store only one value at any time.
int x;x = 5;x = 10;
x
510
Abstract Data Types
A variable declared with a class is called an object. For example, the object spot is type Circle:
Circle spot = new Circle(4);spot
getRadius()area()
Java Packages Numerous packages are included with JDK
Packages contain classes
Packages can be added to an application with an import statement. For example, the statement
import java.util.Scanner;makes the Scanner class and its methods accessible to the application.
The Scanner Class Part of the java.util package
A Scanner object processes text and numbers from the input stream
Methods include:next()nextLine()nextInt()nextDouble()nextBoolean()nextLine().charAt(0) //use for single letterclose()
Integer Division
Integer division (/) is performed when both operands are integers. Only the integer portion of the quotient is returned:
Real Division
Real division (/) is performed when one or both operands are type double. The entire quotient, including the decimal portion is returned:
double result;result = 20.0/7.0; //result is 2.857
Modulus Division
Modulus division (%) returns the remainder of a division operation:
Operator PrecedenceOperators in Java have the following precedence:
1. multiplication and division
2. addition and subtraction
Operators of the same precedence are evaluated in order from left to right. For example, multiplication is performed first, then division, and finally addition:
5 + 6 * 4 / 2 = 17
Changing the Order of Operations
The order in which operators are evaluated can be changed by using parentheses. For example, addition is performed first, then multiplication, and finally division:
(5 + 6) * 4 / 2 = 22
Type CastingType Casting converts a number of one type to a number of a different, but compatible type. Type casting is used to:
1. make the operand types in an expression match. For example, wholeNum = (int)y * 2
2. truncate the decimal portion of a double. For example, wholeNum = (int)z
3. change the way in which a division (/) operation will be performed. For example, realDivision = (double)a / (double)b
Assignment Operators
Operator Operation+= addition and then assignment-= subtraction and then assignment*= multiplication and then
assignment/= division and then assignment%= modulus division and then
assignment
Compound operators
Examples:x += 3 x = x + 3;y/=5 y = y / 5;k %= 8 k = k % 8;b *= 9 b = b * 9;count /= 6 count = count / 6;You should avoid using single letters as variable’s names.
Named Constants
A named memory location that cannot be changed from its initial value.
The keyword final is used in a constant declaration.
Constant identifiers are typically all uppercase with an underscore (_) separating words within the identifier name.
Example:
final double TOTAL_TAX = 0.07;
Java Keywordsabstract double int strictfp
boolean else interface super
break extends long switch
byte final native synchronized
case finally new this
catch float package throw
char for private throws
class goto protected transient
const if public try
continue implements return void
default import short volatile
do instanceof static while
Programming Errors
Syntax errors violate the rules of Java.
Logic errors, also called semantic errors, occur in statements that are syntactically correct, but produce undesired or unexpected results.
Run-time errors, also called exceptions, halt program execution at the statement that cannot be executed. One type of exception is called InputMismatchException.
Dividing by zero will be a run-time error.
Flowchart Symbols
process
The BirthdayGame Flowchart