Java Programming: From the Ground Up Chapter 2 Expressions and Data Types.
-
Upload
fay-cameron -
Category
Documents
-
view
236 -
download
3
Transcript of Java Programming: From the Ground Up Chapter 2 Expressions and Data Types.
What is a computer program?
A computer program or application is a set of instructions, written in a programming language, that enables a computer to perform some specified task.
A First Program
Problem statement
Write program that displays the line of text:
“Peter Piper picked apart a pithy program”
Java Solution
1. // This application prints // "Peter Piper picked apart a pithy program." on the screen
2. public class TongueTwister 3. { 4. public static void main(String[] args) 5. { 6. System.out.println ("Peter Piper picked apart a pity program."); 7. } 8. }
Output :
Peter Piper picked apart a pithy program.
Line 1 1. // This application prints "Peter Piper picked apart a pithy program." on the screen
Line 1 is a comment.
A comment explains or clarifies the meaning of some section of a program.
A single line comment begins with the compound symbol //
(two forward slashes) Once the compiler recognizes the beginning of a single line
comment, the compiler skips all subsequent text on that line.
Line 2 2. public class TongueTwister
Line 2 begins with two special words – public and class.For now, a class is an application or program and every class begins with the words public and class followed by the class name.
TongueTwister is the name of the class. The class name
must be a valid Java identifier.
A valid Java identifier is a "word" of arbitrary length composed of letters and/or digits and/or two special characters $ (dollar sign) and _ (underscore), where the first character must be a letter.
Examples: R2D2 or HarryPotter
Line 2
Java is case sensitive. The name TongueTwister is considered different than TONGUEtwister.
Keywords or reserved words are words that may not be used as Java identifiers
A class name begins with an uppercase letter
Spaces may not be part of a name. Uppercase letters are commonly used to separate "words"
Lines 3 and 8{…..}
The curly braces “{“ and “}” on lines 3 and 8 mark the beginning and the end of the TongueTwister class that comprises our application.
A group of statements or instructions enclosed by curly braces is called a block.
The body or executable section of a class is contained
within these matching braces.
Lines 3 and 8
The general structure of a class is:
public class ClassName { // class body of block }
Lines 4 - 74. public static void main(String[] args)5. {6. System.out.println ("Peter Piper picked apart a pity program.");7. }
The line “public static void main ( String[] args)” is the first line or the heading of the class’s main method.
A method is a named section of a class that performs a task.
Lines 4, 5, and 7
The main method is automatically executed when a program runs.
The statements of the main method are executed first.
The main method is the starting point of every program. Every application must have a main method. Every main
method begins with the same first line.
The curly braces of lines 5 and 7 mark the beginning and the end of the main method.
The actions that the main method performs are included between these curly braces.
Lines 4, 5, and 7
A simple Java program has the following skeletal format:
public class ProgramName { public static void main (String args []) { // executable statements go here } }
Line 6 6. System.out.println ("Peter Piper picked apart a pity program.");
This line instructs the computer to print Peter Piper picked apart a pithy program on the screen.
The quoted text ("Peter Piper picked apart a pithy program") is called a string literal or more simply a string.
A string literal must be contained on a single line.
Line 6
The quotation marks are not part of the string literal.
The quotation marks indicate the beginning and the end of the string.
This line instructs the computer to display the string literal on the screen.
The statement also prints the newline character, that is, it advances the cursor to the next line.
Line 6
All statements are terminated with a semi-colon.
The program must be saved in a file named TongueTwister.java.
Variation
1. // This program prints "Peter Piper picked apart a pithy program." on the screen
2. public class AnotherTongueTwister 3. { 4. public static void main( String[] args) 5. { 6. System.out.print ("Peter Piper picked apart ");
// print NOT println 7. System.out.print ("a pithy program."); 8. } 9. }
Output
Peter Piper picked apart a pithy program.
Output using print instead of println does not include the
newline character.
Data Types and Expressions
Problem Statement
Write an application that calculates the number of minutes in a leap year using the fact that there are 525,600 minutes in a 365
day year.
Solution
1. //Calculates the number of minutes in a leap year 2. // Uses the fact that there are 525,600 minutes in a 365 day year 3. public class LeapYearMinutes 4. { 5. public static void main(String[] args) 6. { 7. System.out.print( "The number of minutes in a leap year is "); 8. System.out.println( 60*24 +525600);
// 60 min/hr times 24 hr/day + 525600 min 9. } 10. }
Output:
The number of minutes in a leap year is 527040.
Discussion
The argument supplied to the println method is a numerical expression: 60* 24 + 525600.
An expression is sequence of symbols that denotes, represents, or signifies a value.
The value of the expression 60* 24 + 525600 is 527040.
60 and 24 are multiplied and the product is added to 525600.
527040, is given to the println method.
* and + are called operators and the numbers 60, 24, and 525600 are called operands.
Data Types
A data type is a set of values together with an associated
collection of operators for manipulating those values.
Type int
The values associated with the data type int are integers in the range:
–2,147,483,648 to 2,147,483,647
The associated operators that manipulate integers are:
+ -- addition
– -- subtraction
* -- multiplication
/ -- division
% -- modulus
Type int
The / operator denotes integer division
a/b evaluates to a divided by b, discarding any remainder
5/2 evaluates to 2
−23/6 evaluates to −3
4/43 has the value 0
The expression a%b evaluates to the remainder of a divided by b
5%2 has the value 1
−23%3 has the value −2
Operator Precedence
The order in which operations are performed is the same as in ordinary arithmetic.
For integer expressions, operations are performed according to the following precedence (priority) rules:
Operator Precedence
*, /, and % have the highest precedence
*, /, and % are equal in precedence
+ and − are equal in precedence but lower than *, / and %
Operations of equal precedence have left to right associativity
Operator Precedence
You may explicitly change the order of operations by inserting parentheses into an expression.
An expression enclosed by parentheses must always be
fully evaluated before it can be used in a larger expression.
Operator Precedence
The day of the week for any date can be found with the following formula:
Day of the week = ((day +(13*((month+9)%12+1)-1)/5 + year%100+year
%100/4+ year/400–2*(year/100) )%7+7)%7 +1
Day of the week is a number between 1 and 7 (Sunday= 1, Monday =2 …, Saturday = 7),
Day is the day of the month (1...31),
Month is encoded as January = 1, February = 2...December = 12
Year is the four-digit year in question.
Operator Precedence
Problem Statement
Write an application that determines the day of the week for May 13, 1988
Operator Precedence
1. // Displays the number of the day (1-7) on which May 13, 1988 occurred. 2. public class DayFinder 3. { 4. public static void main(String[] args) 5. { 6. System.out.print ("May 13, 1988 fell on day number "); 7. //Uses the Zeller formula 8. System.out.println( ((13+ (13*((5+9)%12+1) –1)/5 // day = 13, month = 5 9. + 1988%100 // year = 1988 10. + 1988%100/4 11. + 1988/400 12. – 2*(1988/100))%7 +7) %7+1 ); 13. } 14. }
Output
May 13, 1988 fell on day number 6
Type double The values are decimal numbers in the range −1.7 x 10308 … 1.7
x 10308 with 14 significant digits of accuracy. The operators associated with type double are
+ -- addition
- -- subtraction
* -- multiplication
/ -- division
The division operator (/) denotes decimal or floating point division rather than integer division; so 5.0/2.0 has the value 2.5 but 5/2 has the value 2
Type char
Type char is the set of all characters found on the standard keyboard (in addition to thousands of other characters that are used for displaying text in languages that do not use the English alphabet).
A value of type char is enclosed in single quotes:
'5' is a value of type char,
"5" is a string literal, and
5 is an integer.
Type char
The ASCII code assigns a non-negative integer between 0 and 127 to each character
These values are stored as binary numbers, typically a leading 0 followed by a 7-bit code number between 0 to 127 inclusive
ASCII values can be stored using a single byte of memory; that is, one character requires just one byte of storage
Type char
Java uses the Unicode character set and allocates two bytes of memory for each character.
Using two bytes allows 65,536 characters.
Unicode set includes English characters and also characters for many other languages.
By design, the ASCII character set is a subset of Unicode.
Type char
Type type char includes several special characters that are represented by an escape sequence or escape character:
\n newline
\t tab
\b backspace
\r carriage return
\' single quote
\\ backslash
Type boolean
Type boolean has two values: true and false The associated operators:
'&&' -- 'and' '||' -- 'or'
'!' -- 'not'
Type boolean
'true && true' has the value true
'false || true' has the value true
'!true' has the value false
Type boolean
x && y is true if both operands are true. x || y is false when both operands are false.
! (not) has highest precedence, followed by && and finally ||.
Relational Operators
Java provides a set of relational operators, used in expressions that evaluate to true or false.
Each relational operator requires two operands, which may
be two integers, two decimal numbers, or two characters.
Relational Operators
The relational operators are:
< less than
<= less than or equal
> greater than
>= greater than or equal
== equals (has the same value)
!= not equal
Relational Operators
Character data are compared based upon Unicode /ASCII integer values.
‘A’ has the code value 65 and ‘C’ the value 67
‘A’ < ‘C’ evaluates to true since 65 <67
Relational Operators
Examples:
1. 5 < 3 || 6 > 2 false || true has the value true
2. 1+14 % 5 == 0 false
3. 'A' <'B' true (code for 'A' is 65; for B it is 66 : 65 < 66)
4. 'Z' < 'a' true (code for ‘Z’ is 90; and for 'a' it is 97:)
5. 1+1==2 ||1+1 == 3 true || false has the value true
6. 37/3 > .3333 true
7. 2<3 &&4<5 || 7<=5 && 2==3 true || false has the value true
8. 2<3 && ( 4<5 || 7<=5) && 2==3 true && true && false has the value false
9. false == false true
10. true != false true
Relational Operators
Expressions such as 2<3<4 are incorrect. Java attempts to evaluate this expression as:
(2<3) < 4true < 4
'true < 4' is invalid and generates an error
The Java equivalent of 2<3<4 is (2<3) && (3<4)
Relational Operators
Problem Statement
A leap year is any year divisible by four except those years divisible by 100 unless the year is also divisible by 400.”
Write a program that determines whether or not 1800 was a leap year.
Relational Operators
1. // A leap year is a year that is divisible by 4 // but not 100 unless it is divisible by 400
2. // This program determines whether or not //1800 meets all conditions of a leap year
3. public class LeapYear 4. { 5. public static void main(String[] args) 6. { 7. System.out.print("The year 1800 is a leap year? True or false: "); 8. //(divisible by 4 and not by 100) or (divisible by 400) 9. System.out.println( 1800%4 ==0 && 1800 %100 !=0 ||
1800%400 == 0); 10. } 11. }
Relational Operators
Output
The year 1800 is a leap year? True or false: false
Here is a fully parenthesized version of the expression on line 9:
(((1800%4) ==0) && ((1800 %100) !=0)) || ((1800%400 ) == 0)
Short Circuit Evaluation
Evaluates expressions involving operators && and ||.
Java stops the evaluation of an expression once the value of the expression is determined.
Example:
1<2 || 2<3 || 3<4
The value of this expression is true. This value can be determined after evaluating 1<2. No more of the expression need be considered.
Mixing Data Types in a Numerical Expression
A Java expression can be constructed from data of several
different types
The expression (22+3.0)/4 contains both integers (int) and decimal numbers (double)
Java first promotes or casts the operand of the “smaller” data type to the data type of the other operand
The range of values determines the “size” of a data type. Thus char is smaller than int, which, in turn, is smaller than double.
Mixing Data Types in a Numerical Expression
Example:
The expression (22+3.0)/4 has the value 6.25.
The expression is evaluated as follows:
(22+3.0)/4 The expression consists of decimal and integer types.
(22.0 +3.0)/4 The integer 22 is cast to 22.0 (an int is cast to a double).
25.0/4 This is floating point addition -- 22.0+3.0.
25.0/4.0 The integer 4 is cast to 4.0.
Mixing Data Types in a Numerical Expression
The expression 'A' + 1 has the value 66. The expression is evaluated as follows:
• 'A' + 1 The expression consists of character and integer data.
• 65 + 1 The character 'A' is cast to the integer 65 -- its ASCII code value.
• 66 This is integer addition.
Mixing Data Types in a Numerical Expression
The expression 'A' + 1.0 has the value 66.0. The expression is evaluated as follows:
• 'A' + 1.0 The expression consists of character and a decimal data.
• 65 + 1.0 The integer 65 is the ASCII code for ‘A’ i.e., ‘A’ is stored as 65.
• 65.0 + 1.0 The integer 65 is cast to 65.0.
• 66.0 This is floating point addition.
Mixing Data Types in a Numerical Expression
Numerical operators can be used with character operands.
Both operands are treated as integers.
Example:
The expression 'A'+ 'Z' has the value 155 since the ASCII values for 'A' and 'Z' are 65 and 90, respectively. Similarly, 'A' – 'Z' has the value −25.
The expression “A”+ “B” does not have the value 155. In this case, “A” and “B” are not character data but strings. The + operator may be used with strings but the result is not an integer.
The + Operator and Strings
If both operands, A and B, are strings then the expression A+B evaluates to another string, which is the concatenation (joining together) of A and B.
If only one operand is a string, then the other operand is first
cast to a string and the value of the expression is the concatenation of two strings.
The + Operator and Strings
Joining two strings:
"Bibbidi " + "Bobbidi " evaluates to a new string "Bibbidi
Bobbidi ", which is formed by joining, i.e. concatenating, "Bibbidi " and "Bobbidi ".
" Bibbidi " + "Bobbidi " + "Boo" evaluates to the string "Bibbidi Bobbidi Boo" which is formed by first joining "Bibbidi " and "Bobbidi " and then concatenating the result with "Boo."
The + Operator and Strings
Joining a string and a number:The expression:
2147483647 + " is not only the largest value of type int but also a prime number!"
evaluates to the string:
"2147483647 is not only the largest value of type int but also a prime number!"
The first operand is the integer 2147483647, which is cast to the string "2147483647" and then the two strings are concatenated.
The + Operator and Strings
Joining a string and a numerical expression: The expression “The sum of the two dice is " + (5+2) evaluates
to the string:
“The sum of the two dice is 7”
The expression in parentheses is evaluated first.
Parentheses can force a change in the usual precedence.
The + Operator and Strings
If the parentheses are omitted then the expression:
"The sum of the two dice is "+ 5 + 2
evaluates to the string:
"The sum of the two dice is 52."
The + Operator and Strings
("The sum of the two dice is " + 5 )+ 2
("The sum of the two dice is " + "5") + 2 The integer 5 is cast to string "5".
("The sum of the two dice is 5") + 2 "The sum of the two dice is " and "5“ are joined.
("The sum of the two dice is 5")+ "2" The integer 2 is cast to "2".
"The sum of the two dice is 52" "The sum of the two dice is 5" is concatenated with "2".
Numerical addition is not performed.
The + Operator and Strings
The expression:
"The product of the two dice is " + 5*2
Evaluates to the string:
"The product of the two dice is 10."
The * operation is performed first since * has higher
precedence than +.
The + Operator and Strings
The expression
"The difference of the two dice is" + 5 – 2
is ill formed and causes an error.
Left to right the expression is evaluated as:
("The difference of the two dice is " + 5)− 2
("The difference of the two dice is "+ "5") − 2
"The difference of the two dice is 5"− 2
Error occurs: the (−) operator cannot be applied to strings.
In the Beginning … Again
To produce the output:
The cost of 15 wickets is 375 dollars
An application might include three instructions:
1. System.out.print("The cost of 15 wickets is "); 2. System.out.print( 15* 25); 3. System.out.println(" dollars");
In the Beginning … Again
Java specifies that the print and println methods accept a single argument of any type.
Statements 1 and 3: the arguments are a string literal
Statement 2: the argument is an integer (375)
The previous three lines of code can be condensed to a single line:
System.out.print("The cost of 15 wickets is " + (15*25) + " dollars");
In the Beginning … Again
The mixed expression:
"The cost of 15 wickets is " + (15*257) + " dollars");
evaluates to the string: "The cost of 15 wickets is 375 dollars"
It is this string that is the argument to the println method.
In the Beginning … Again
Examples:
1. 'A'+ 'B' is 131 (int)
2. 'A'+ "B" is AB (string)
3. "A"+ "B" is AB (string)
4. ""+'A'+ 'B' is AB (string)
5. 'A'+ 'B'+"" is 131 (string)
6. 3+4+"" is 7 (string)
7. ""+3+4 is 34 (string)
Bugs
Initial versions of almost every program commonly contain errors or bugs.
There are three categories of errors:
1. Compilation errors. 2. Runtime errors.
3. Logical errors.
Compilation Errors
A compilation error occurs when a program violates one of the rules of Java, such as the omission of a semi-colon, a string's quotation mark, or a closing curly brace.
The compiler flags the error and tells you where the error
occurs.
A program must be free of such errors before it can be translated into bytecode.
Runtime Errors
A runtime error occurs during program execution.
A runtime error can occur when the program attempts some invalid operation such as division by zero.
A runtime error results in program termination.
Logical Errors
Even if the Java compiler detects no errors and a program runs to completion, a program may not do what it is supposed to do.
A program that converts degrees Fahrenheit to degrees Celsius using the erroneous expression:
(5/9)(F – 32), where F represents a Fahrenheit temperature;
// evaluates to 0 since 5/9 = 0 ( integer division)
rather than:
(5.0)/9.0)(F – 32) // correct, uses floating point division