Savitch`s-Chs-1-&-2-slides-INTERIM
Download
Report
Transcript Savitch`s-Chs-1-&-2-slides-INTERIM
Beginning Java:
Savitch’s Chapters 1 & 2
(with enhancements)
Charles Abzug, Ph.D.
Department of Computer Science
James Madison University
Harrisonburg, VA 22807
Voice Phone: 540-568-8746, E-mail:
[email protected]
Home Page: http://www.cs.jmu.edu/users/abzugcx
© 2001 Charles Abzug
Producing and Running a Program the
Traditional Way: Compilation
Step 1: Source Code
compiler
Object Code
The compiler converts ALL of the Source Code to Object Code in a
batch-type operation. Once the Object Code as been produced, the
Source Code is no longer needed for the program to run; it could be
discarded without affecting the ability of the program to run
successfully.
Step 2: Object Code
24-Oct-2001
run on the computer
much later
© 2001 Charles Abzug
Results
2
Producing and Running a Program in a
Different Way: Interpretation
line-by-line
interpreter
Step 1a: Source Code
Object Code
runs on the computer
as soon as it is generated
Step 1b: Object Code
Results
The Source Code is examined by the Interpreter line by line, and is
converted line by line to Object Code. The Object Code is run on the
computer line by line as it is generated. It is not retained, but is
discarded immediately after being run.
24-Oct-2001
© 2001 Charles Abzug
3
Ordinary Programming Languages: NOT Java
•
Compilation can be very efficient:
– Compilation can take a lot of time on the computer.
– However, compilation need be carried out only once per program.
– The object code can be run an unlimited number of times thereafter.
– Disadvantage: Compiled object code is specific to a particular hardware
architecture; code compiled on a MacIntosh won’t run on a “Wintel”
family machine, or on a Sun, or on a VAX or on an IBM RS/2000 or
on an SGI. (Underlined terms refer to computers of grossly different
architectural design.)
•
Interpretation is usually very inefficient.
– Every time the program is run, it is necessary to scan the Source Code
line by line and to convert it line by line to object code.
– Huge expenditure of processing overload.
– Advantage: Interpreters for a particular programming language can be
produced for machines of different architecture. Program source code
can then be run on all machines equipped with interpreters that
understand that language.
24-Oct-2001
© 2001 Charles Abzug
4
Producing and Running a Java Program:
BOTH Compilation AND Interpretation
Java compiler
Step 1: Source Code
“Byte” Code
Java Virtual Machine (interpreter)
Step 2a: “Byte” Code
runs on the computer
Step 2b: Object Code
Object
Code
Results
The Java “Byte” Code is examined by the Interpreter line by line, and is
converted line by line to Object Code. The Object Code is run on the
computer line by line as it is generated, and is discarded immediately
after being run.
24-Oct-2001
© 2001 Charles Abzug
5
Producing and Running a Java Program:
BOTH Compilation AND Interpretation
Java compiler
Step 1: Source Code
“Byte” Code
javac
myClassFile.java
myClassFile.class
Command Syntax: javac myClassFile.java
24-Oct-2001
© 2001 Charles Abzug
6
Producing and Running a Java Program:
BOTH Compilation AND Interpretation
Java Virtual Machine (interpreter)
Step 2a: “Byte” Code
Object
Code
runs on the computer
Step 2b: Object Code
Results
Java Virtual Machine (interpreter)
myClassFile.class
Results
Command Syntax: java myClassFile
24-Oct-2001
© 2001 Charles Abzug
7
Java Programs
For Java programs, the situation is unique.
Java source code is first compiled and converted to Java “byte code”. This is a
form of pseudo-object-code, which runs not on a real computer, but instead on a
“Java Virtual Machine”, which is a standardized kind of theoretical computer.
Each computer that runs Java code contains a “Java Real-Time Run Environment”,
which interprets the “byte code” of the idealized Java Virtual Machine on the
hardware of the actual computer.
The advantage of this outwardly labyrinthine process is that Java “byte code” can be
generated on one architectural family of machines, and can then run on a wide
variety of machines of grossly different hardware architecture.
The Java “byte code” is much closer to actual object code than is the Source Code
of a High-Level Language. Therefore, the interpretation of “byte code” is not so
inefficient as is the interpretation of High-Level-Language source code.
24-Oct-2001
© 2001 Charles Abzug
8
A Basic Java Program
1.
2.
Terms and conventions in Java are intended:
a)
to mimic our view of the non-programming world.
b)
to enhance the clarity of our program.
c)
to encourage modularity and abstraction.
Class (DEFINITION): a category of objects that share some common feature.
In Java, a class consists of a formal definition of a kind of object.
All objects of a certain kind are members of the same class.
3.
Object (DEFINITION): a unit which has a unique identity.
4.
Every class in Java is of type object.
24-Oct-2001
© 2001 Charles Abzug
9
A Basic Java Program (continued)
5.
A Java object represents an object in the real world. Examples:
a)
Vehicle
i.
ii.
iii.
iv.
Aircraft
Watercraft
Land-vehicle
Hybrid
b)
Person
i. Student
ii. Faculty
iii. Staff
c)
Book
i. Textbook
ii. Biography
iii. Novel
24-Oct-2001
© 2001 Charles Abzug
10
A Basic Java Program (continued)
6.
Every object has certain activities, or methods, in which it can engage.
These methods can subsume the entire class, or only a specific subclass.
a)
A vehicle can travel in a specific direction at a stated speed. A book
cannot, unless it is borne by a vehicle.
b)
An aircraft can move in three-dimensional space, whereas a land vehicle
moves in only two dimensions, and a monorail vehicle in only one.
7.
A class in Java is described in a source-code file that MUST bear the exact
name of the file, and the extension “.java”
8.
Java is Case-Sensitive:
“object1” and “Object1” are two DIFFERENT items in Java.
24-Oct-2001
© 2001 Charles Abzug
11
A Basic Java Program (continued)
9.
Naming rules and conventions:
a)
Allowed characters in a Java identifier:
i.
alphabetic characters (letters ‘A’ through ‘Z’ and
‘a’ through ‘z’)
ii.
numerals (‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, and ‘9’): not
allowed in first character position
iii. the underscore character (‘_’)
iv. the character ‘$’: reserved for special purposes: don’t use
it, except as will later be specified.
24-Oct-2001
© 2001 Charles Abzug
12
A Basic Java Program (continued)
9.
Naming rules and conventions:
b)
Conventions for Identifiers:
i.
The name of a class only begins with an Uppercase character.
ii.
Names of primitive data types, of variables, of objects, and
of methods all begin with lowercase letters.
iii. Names should be anti-laconic and fully descriptive of function,
e.g., “numberOfVarieties” rather than “numVar”.
iv. Multi-word identifiers are strongly recommended, because
these are more fully descriptive of function.
v.
Set off from each other the various words of a multi-word
identifier, by capitalizing the first letter of each word
that follows another word (i.e., of each word except
the first).
vi. Spell names of Constants with ALL capital letters. To set off
from each other the individual words in the Identifier of a
constant, use the Underscore character.
24-Oct-2001
© 2001 Charles Abzug
13
A Basic Java Program (continued)
9.
Naming rules and conventions:
c)
10.
Position your type and class declarations as closely as possible to the
top of the program (i.e., do not defer the declaration of a variable
or of a constant to immediately before you use it.
General format of a Java program:
public class DemonstrationOfASimpleJavaProgram
{
//Purpose: to demonstrate the simplest possible Java program. The
// program accomplishes absolutely nothing!
public static void main(String[] args)
{
} //end method main
} //end class DemonstrationOfASimpleJavaProgram
/* Note position of opening and closing “curly” braces: paired braces are
directly above and below each other. */
24-Oct-2001
© 2001 Charles Abzug
14
A Basic Java Program (continued)
11.
Comments
a)
Two kinds:
// This comment ends with NewLine: following line is Source Code.
/* This comment continues indefinitely, until it is explicitly brought
to a halt by means of the comment-termination character
sequence. */
b)
Extensive comments are required. No matter how good your code, you
MUST take the trouble to explain it.
c)
Identifiers with VERY specific and detailed names can do a lot to
lighten the burden of commenting your program, but they do NOT
entirely eliminate the necessity to explain your code.
d)
Standard boilerplate is required at the beginning of the program:
i.
ii.
iii.
iv.
24-Oct-2001
Your full name and the full date (day, month, & 4-digit year).
Course number and assignment number, OR Project Name.
Brief explanation of the function of the program.
Date and brief summary/explanation of each revision.
© 2001 Charles Abzug
15
A Basic Java Program (continued)
11.
12.
Comments (continued)
e)
Almost every close curly-bracket should be commented.
f)
Constants and variables should be explained, UNLESS the name is so
explicit as to render further explanation unnecessary.
g)
Further requirements for commenting will be declared throughout the
semester.
White Space
a)
The compiler ignores white space.
b)
Make use of white space to make apparent the different regions of
your program.
24-Oct-2001
© 2001 Charles Abzug
16
Simplest Possible Java Program
/*
Name:
Date:
Project:
Purpose:
Charles Abzug
08 Oct 2001
CS-139, illustrative program
To Demonstrate the very simplest possible Java program: barebones content; program accomplishes absolutely nothing!
*/
public class DemonstrationOfASimpleJavaProgram
{
public static void main(String[] args)
{
} //end method main
} //end class DemonstrationOfASimpleJavaProgram
24-Oct-2001
© 2001 Charles Abzug
17
A Not Quite So Simple Java Program
/*
*/
Name:
Date:
Project:
Purpose:
Charles Abzug
08 Oct 2001
CS-139, illustrative program
To Demonstrate the very simplest possible Java program: barebones content; program accomplishes absolutely nothing!
Revision01: 08 Oct 2001: Added a simple output operation.
public class DemonstrationOfASimpleJavaProgram
{
public static void main(String[] args)
{
System.out.println(“Hello, World!”);
} //end method main
} //end class DemonstrationOfASimpleJavaProgram
24-Oct-2001
© 2001 Charles Abzug
18
Required Program Structure
1.
Program Header: embedded in an extended comment
a)
Name of Programmer(s)
b)
Date
c)
Name of Project/Program
d)
Brief Description of Project
e)
Thorough and Complete Documentation of each and every revision
2.
Generous use of “white space” to delineate clearly different functional regions
of the source code
3.
Functionally matched pair of “curly brackets” placed directly above/below each
other
4.
Creative indentation
24-Oct-2001
© 2001 Charles Abzug
19
Required Program Structure (continued)
5.
Declarations of Variables and of Constants are to be bunched near the top of
the region of the program over which they have scope, even though the
language itself does NOT require this.
6.
ALL of Savitch’s recommendations regarding programming style are required.
7.
Further requirements regarding program structure and style to be added later.
24-Oct-2001
© 2001 Charles Abzug
20
Declaration of Variables and Constants
1.
A primitive Data Type defines:
a)
how much space needs to be allocated to store the data for each
variable of that type.
b)
how the data are represented within the storage location, i.e., how
specific values of the data are mapped to specific storage
representations.
c)
the range of values that can be accommodated.
d)
what operations are defined for the Data Type.
For example, all numeric Data Types can undergo addition,
subtraction, multiplication, and division. However, it makes no
sense to multiply or divide elements of character data (char).
24-Oct-2001
© 2001 Charles Abzug
21
Declaration of Variables and Constants (continued)
2.
A Class Type:
a)
must be defined before it can be used.
b)
usually includes several methods that specify permissible behavior of
variables declared to be of that type.
c)
may be provided as part of the standard Java package, or may be
programmed by the same person or group responsible for the
current project, or may be part of the organization’s
infrastructure or borrowed or purchased from an external source.
24-Oct-2001
© 2001 Charles Abzug
22
Primitive Data Types
1.
2.
Integer Data Types:
Storage
Space
Data
Type
Minimum Value
Maximum Value
1 Byte
byte
-128
+127
2 Bytes
short
-32,768
+32,767
4 Bytes
int
-2,147,483,648
+2,147,483,647
8 Bytes
long
< -9*1018
> +9*1018
Floating-Point Data Types: close correspondence between scientific and CS-FP
notation
24-Oct-2001
Storage
Space
Data
Type
Minimum Absolute
Value
Maximum
Absolute Value
4 Bytes
float
+1.4 … * 10-45
+3.4 … * 10+38
8 Bytes
double
+4.9 … * 10-324
+1.7 … * 10+308
© 2001 Charles Abzug
23
Primitive Data Types (continued)
3.
4.
Character Data Type:
Storage
Space
Data
Type
Permissible Range of Values
2 Bytes
char
All Unicode characters
Boolean Data Type:
24-Oct-2001
Storage
Space
Data
Type
Minimum Value
Maximum Value
1 bit
boolean
false
true
© 2001 Charles Abzug
24
Operator Symbols and Arithmetic Operations
(Numeric Data Types)
1.
Assignment Operator (simple assignment):
=
NOTE: This is NOT the mathematical equals-sign.
Example1: areaOfCircle = PI * radiusOfCircle * radiusOfCircle
Read: “Set the value of areaOfCircle to be PI times radiusOfCircle
times radiusOfCircle.”
Example2: salary = salary + (salary * PERCENT_RAISE)/100
Read: “Set the value of salary equal to the sum of the current value of
salary and the calculated raise.”
24-Oct-2001
© 2001 Charles Abzug
25
Operator Symbols and Arithmetic Operations (continued)
2.
Ordinary arithmetic operators (identical in functionality to mathematical
operators):
+ (addition),
- (subtraction), and
* (multiplication)
3.
Three different division operations:
a)
Floating point division: / (same as ordinary mathematical division)
b)
Integer division: / (returns an integer value; any possible fractional
component is truncated)
c)
Modulo division: % (discards the quotient and returns the value of the
remainder)
24-Oct-2001
© 2001 Charles Abzug
26
Operator Symbols and Arithmetic Operations (continued)
3.
Three different division operations (continued)
d)
Examples:
float preciseRatio = 13.0/4.0 ;
//returns a value of 3.25 (Floating-Point division).
4.
int
crudeRatio = 13/4 ;
//returns a value of 3 (Integer Division).
int
remainder = 13%4 ;
//returns a value of 1 (Modular Division).
Assignment compatibilities and Type Casting:
a)
Implicit conversion between types; Hierarchy of Primitive Data Types:
double float long int short byte
Reasoning underlying this hierarchy
24-Oct-2001
© 2001 Charles Abzug
27
Operator Symbols and Arithmetic Operations (continued)
4.
Assignment compatibilities and Type Casting (continued):
b)
Explicit conversion between types is called “type casting”.
Examples of Type Casting:
float preciseRatio = (float)13/(float)4 ;
//returns a value of 3.25 (Floating-Point Division).
24-Oct-2001
int
crudeRatio = (int)13.0/(int)4.0 ;
//returns a value of 3 (Integer Division).
int
asciiOfQ = (int)’Q’ ;
//returns a value of 81.
int
asciiOfQ = (int)’q’ ;
//returns a value of 113.
© 2001 Charles Abzug
28
Operator Symbols and Arithmetic Operations (continued)
5.
The Increment and Decrement Operators:
++variable (pre-increment)
and variable++ (post-increment)
--variable (pre-decrement) and variable–- (post-decrement)
Code Example:
int counter = 0;
System.out.println(“This is line number “ + counter++);
//prints “This is line number 0”, but thereafter counter=1
int counter = 0;
System.out.println(“This is line number “ + ++counter);
//prints “This is line number 1”, and thereafter counter=1
Shorthand Assignment Operators (complex assignment): +=, -=, *=, /=, %=
Example6a: salary = salary + (salary * PERCENT_RAISE)/100;
Example6b: salary += (salary * PERCENT_RAISE)/100;
NOTE: Example6b reads exactly the same as Example6a.
24-Oct-2001
© 2001 Charles Abzug
29
Character Data
1.
Formal name for character data type: char
2.
Character literals: delineated by “Single Quotes” (apostrophes).
3.
Underlying Representation: 2-Byte binary (216 possible values: UNICODE)
a)
First 256 items (i.e., 000016 through 00FF16) are identical in value to
ASCII (American Standard Code for Information Interchange), an
old 1-Byte code.
b)
Both printing and non-printing characters are represented.
c)
Many languages represented, including diacritical marks, accents, etc.
d)
To determine Sorting Order and underlying representation of printing
characters used in English, see Savitch’s Appendix 3.
e)
Upper-case and lower-case are clearly differentiated. ‘a’ != ‘A’, etc.
f)
For characters of the Latin alphabet, representation of the upper-case
and lower-case versions of the same letter differ by 32.
24-Oct-2001
© 2001 Charles Abzug
30
Character Data (continued)
4.
Type-Casting and Assignment Compatibility for char data:
double float long int char
Question: char is a 2-Byte variable; short is also 2-Byte.
Why not allow short char ?
24-Oct-2001
© 2001 Charles Abzug
31
The String Type
1.
String is a CLASS Type, not a PRIMITIVE Type. Therefore, the ‘S’ is
capitalized.
2.
A literal String is a String constant.
3.
Concatenation of Strings: ‘+’ serves as the concatenation operator.
4.
String literals and String variables can be concatenated both with each other
and with other types, e.g., with numeric types.
5.
Index ranges from 0 to (length – 1).
6.
String methods are invoked with “dot” notation.
24-Oct-2001
© 2001 Charles Abzug
32
String Methods
Method
Effect, or Value Returned
length()
equals(Other_String)
true or false
toLowerCase()
toUpperCase()
equalsIgnoreCase(Other_String)
true or false
indexOf(Some_Substring)
indexOf(Some_Substring,Starting_Index)
at or after Starting_Index
lastIndexOf(Some_Substring)
substring(Start_Index)
substring(Start_Index,One_Past_End_Index)
charAt(Index_Position)
trim(Some_String)
removes leading and trailing white space
compareTo(Some_Other_String)
negative integer if calling string is first;
“0”
if strings are equal;
positive
if calling string is last
24-Oct-2001
© 2001 Charles Abzug
33
Escape Characters
The name “escape character” suggests that the character “escapes” from its usual
meaning:
Normal
Character
Escape
Character
r
\r
Carriage Return (same line)
n
\n
New Line
\
\\
the actual “backslash” character
“
\”
the actual “Double Quotation Mark” character
‘
\’
the actual apostrophe (“Single Quotation Mark”) character
t
\t
Advance within the same line to the next Tab stop.
24-Oct-2001
Meaning of the Escape Character
© 2001 Charles Abzug
34
Literal Constants
1.
Integer literals: unary operator (optional for +) and numerals ONLY;
no commas, no decimal point
2.
Floating-Point literals: unary operator (optional for +), numerals AND decimal
point (required)
3.
Floating-Point literals: may be expressed in ComputerSpeak version of
Scientific Notation:
e.g., the speed of light (299,792,458 meters/sec) can be represented
as: 2.99792458e8
(mathematically, 2.99792458 x 108)
or: 29.9792458e7 or 299.792458e6 or . . 0.0299792458e10
or: 29979245800e-2
4.
Character (char) literals: ‘a’, ‘z’, ‘B’, ‘Y’
5.
String literals: delineated by (“Double”) quotes: “Hello, World!”
6.
boolean literals: true, false
24-Oct-2001
© 2001 Charles Abzug
35
Reasons for Using Named Constants Rather than Literals
1.
Identifier is explicatory of function; value might not be. Therefore,
readability of the program is enhanced.
2.
Declaration resides in one place. Modification of the value has widespread
scope.
e.g., PI = 3.1 3.14 3.142 3.1416 3.14159
INTEREST_RATE_PERCENT = 8.0 7.5 7.2 7.0
3.
Reduced chance of typographical error.
24-Oct-2001
© 2001 Charles Abzug
36
Declaration of a Named Constant
1.
Three reserved words are usually included in the declaration:
a)
public: denotes that the contents of the declared variable (that is, its
value) can be accessed from any class that references the
current class. NOT REQUIRED, but if the item is
declared to be private, then it can be accessed only from
within the current class.
b)
static: denotes that the value of the constant can be accessed by
reference to the name of the class in which it is defined,
in contrast to anon-static identifier, whose value can be
accessed only by reference to a specific instance of the
class in which it is used. NOT REQUIRED.
c)
final: denotes that the value, once assigned, can NOT be changed
(i.e., that the identifier denotes a constant and not a
variable). REQUIRED if the identifier denotes a constant
and not a variable.
2.
Following the three magic words, the Type is declared, followed by the
Identifier.
3.
Usually (but not always), the value is assigned to the constant in the
declaration, e.g.:
public static final float PI = 3.14159;
24-Oct-2001
© 2001 Charles Abzug
37
Identifiers: a second look
1.
Reserved Words: may NOT be used as identifiers for class types, variables,
parameters, constants, or methods.
abstract
extends
interface
static
boolean
final
long
super
break
finally
native
switch
byte
float
new
synchronized
case
for
null
this
catch
future
operator
throw
char
generic
outer
throws
class
goto
package
transient
const
if
private
try
continue
implements
protected
var
default
import
public
void
do
inner
rest
volatile
double
instanceof
return
while
else
int
short
24-Oct-2001
© 2001 Charles Abzug
38
Identifiers: a second look (continued)
2.
Poor Practice (and therefore disallowed in this course): differentiating
identifiers from each other, or from Reserved Words, by “clever” use
of case.
24-Oct-2001
© 2001 Charles Abzug
39
Wrapper Classes
1.
Primitive types have limited numbers of operations, and have no methods at all.
2.
Primitive types and class types differ in the way the assignment operator is
handled.
3.
Therefore, every primitive type is provided with a Wrapper Class (A table
showing all Wrapper Classes in shown in the next slide).
4.
Each Wrapper Class incorporates:
5.
a)
defined static constants.
b)
static methods.
The numeric Wrapper Classes all contain the static constants MAX_VALUE and
MIN_VALUE.
Examples:
24-Oct-2001
Integer.MIN_VALUE
Float.MAX_VALUE
© 2001 Charles Abzug
40
Wrapper Classes
Comment
Note the difference in spelling:
Note the difference in spelling:
24-Oct-2001
Wrapper Class
Related
Primitive Type
Byte
byte
Short
short
Integer
int
Long
long
Float
float
Double
double
Character
char
Boolean
boolean
© 2001 Charles Abzug
41
Wrapper Classes (continued)
6.
The numeric Wrapper Classes all contain static methods to convert a String
expression to the base primitive type.
Examples: Integer.parseInt(String-Expression-containing-Only-Numerals)
Float.parseFloat(String-Expression-containing-Numerals-&-a-period)
Similarly for Byte, Short, Long, and Double.
7.
Declaration and Initialization of a variable of one of the Wrapper Class types:
For a primitive type:
Alternatively:
For a class type:
Alternatively:
24-Oct-2001
int iterations;
iterations = 0;
int iterations = 0;
Integer counter;
counter = new Integer(37);
Integer counter = new Integer(37);
© 2001 Charles Abzug
42
Wrapper Classes (continued)
1.
Difference in details of underlying events upon declaration and initialization of
primitive types and class types
a)
Space reserved for the memory location bearing name of the variable:
primitive types:
class types:
b)
Contents of memory location bearing name of the variable:
primitive types:
class types:
24-Oct-2001
depends on type
uniform for all class types; depends upon
architecture of underlying hardware
actual value of the variable
address of the true storage site for variable
contents
© 2001 Charles Abzug
43
Output to the VDT
1.
System.out.print(Some_String_Variable_or_Constant); //ready to continue on
//same line.
2.
System.out.println(Some_String_Variable_or_Constant); //repositions after
//output to a new line.
NOTE: “System.out” is a class.
NOTE: “print” and “println” are methods of the class “System.out”.
NOTE: “Some_String_Variable_or_Constant” can be a String literal, or can
be the concatenation of any number of String variables and
String constants (including literal constants).
NOTE: “Some_String_Variable_or_Constant” is a parameter being passed to
the methods “print” or “println”.
NOTE: Numeric variables can be specified to be concatenated with strings;
this produces an automatic conversion of the numeric value to
a string.
24-Oct-2001
© 2001 Charles Abzug
44
Class SavitichIn: Operations Affecting Non-Numerics
Method
SavitchIn.readNonwhiteChar()
Comment
first char other than “White Space” on the line
SavitchIn.readLineNonwhiteChar()
SavitchIn.read()
returns the Unicode value of the first character on
the line
SavitchIn.readLine()
String ending in “\n” or “\r”
SavitchIn.readWord()
first String beginning with a NonwhiteSpace char
and followed by either a WhiteSpace char or
“\n” or “\r”
SavitchIn.readLineWord()
first String of NonwhiteSpace chars on the input
line
SavitchIn.readLineBoolean()
accepts “t” or “true” or “f” or “false” in any
mixture of case; returns boolean
24-Oct-2001
© 2001 Charles Abzug
45
Class SavitichIn: Operations Affecting Numerics
Method
SavitchIn.readByte()
Comment
String of numerals converted to byte
SavitchIn.readLineByte()
SavitchIn.readShort()
String of numerals converted to short
SavitchIn.readLineShort()
SavitchIn.readInt()
String of numerals converted to int
SavitchIn.readLineInt()
SavitchIn.readLong()
String of numerals converted to long
SavitchIn.readLineLong()
SavitchIn.readFloat()
String of numerals converted to float
SavitchIn.readLineFloat()
SavitchIn.readDouble()
String of numerals converted to double
SavitchIn.readLineDouble
24-Oct-2001
© 2001 Charles Abzug
46
Use of Class JOption.Pane
import javax.swing.*
//Make the class JOptionPane available to the program.
JOptionPane.showInputDialog(Some_String_Variable_or_Constant_or_Expression);
/* Displays a message in a Dialog Box on the user’s Video Display Tube or
other display device, and returns a value of type String, corresponding
to what the user types. */
JOptionPane.showMessageDialog(null, Some_String_Variable_or_Constant);
/* Displays a message in a Dialog Box on the user’s Video Display Tube or
other display device. Dialog Box disappears when user either clicks on
the “OK” button or presses the <Enter> key. */
Multi-Line outputs with “\n”.
24-Oct-2001
© 2001 Charles Abzug
47
Conditional Statements: the if statement
Two principal varieties:
1.
SIMPLE: if (condition) consequentialAction; /* Consequence is a simple Java
statement. */
variant: if (condition)
{ consequentialAction_1;
// Consequence is a complex (composite)
consequentialAction_2;
// Java statement.
. . .
consequentialAction n;
}
a)
Condition evaluates to true:
i. consequentialAction is executed.
ii. Execution continues with next statement after the “if”.
a)
Condition evaluates to false:
i. consequentialAction is skipped.
ii. Execution continues with next statement after the “if”.
24-Oct-2001
© 2001 Charles Abzug
48
Conditional Statements: the if statement (continued)
2.
COMPLEX: if (condition) consequenceForTrue;
else alternativeConsequenceForFalse;
VARIANT: if (condition)
{ consequenceForTrue_1;
consequenceForTrue_2;
. . .
consequenceForTrue j;
}
else
{ alternativeConsequenceForFalse_1;
alternativeConsequenceForFalse_2;
. . .
alternativeConsequenceForFalse k;
}
a)
Either consequenceForTrue or consequenceForFalse is executed, but not
both. Which one is executed depends upon the value of
“condition”.
b)
Subsequently, execution continues with the next statement following the
“if-else”.
24-Oct-2001
© 2001 Charles Abzug
49
Condition: an Expression of Type boolean
1.
Evaluates to either true or false.
2.
Comparison operators:
==
3.
!=
>
>=
<
<=
Compound boolean expressions:
e.g., ((variable_1 < variable_2) && (v_3 >= v_4))
a)
Entire expression must be enclosed in parentheses.
b)
Connect primitive boolean expressions with binary logical operators:
&& or ||
4.
Unary logical operator: ! (read as “not”)
example: ( ! (sellingPrice <= buyingPrice)) is logically equivalent to:
(sellingPrice > buyingPrice)
24-Oct-2001
© 2001 Charles Abzug
50
Condition: an Expression of Type boolean (continued)
5.
Equality for String types:
string_1.equals(string_2)
string_1.equalsIgnoreCase(string_2)
NOTE: A String literal (a “quoted string”) is treated identically to a String
variable, or to a defined String constant, or to an expression
that evaluates to a String.
NOTE the difference between the String methods equals and
equalsIgnoreCase, on the one hand, and the logical comparison
operator “==“ for String types, and the reason.
6.
Lexicographic ordering (i.e., Unicode value ordering) vs. Alphabetic ordering:
string_1.compareTo(string_2)
a negative value, if string_1 precedes string_2.
zero,
if the two strings are identical.
a positive value, if string_ 2 precedes string_1.
24-Oct-2001
© 2001 Charles Abzug
51
END
24-Oct-2001
© 2001 Charles Abzug
52