Programming and Problem Solving with Java: Chapter 2

Download Report

Transcript Programming and Problem Solving with Java: Chapter 2

Chapter 2
Java Syntax and Semantics,
Classes, and Objects
1
Chapter 2 Topics




Elements of Java Programs
Application Construction
Application Entry, correction, and
Execution
Classes and methods
2
What is syntax?

Syntax is a formal set of rules that defines
exactly what combinations of letters,
numbers, and symbols can be used in a
programming language

Syntax rules are written in a simple, precise
formal language called a metalanguage

Examples are Backus-Naur-Form, syntax
diagrams, and syntax templates
3
Identifier Syntax Template

Blue shading indicates an optional part of the
definition. Three dots . . . mean the preceding symbol
or shaded block can be repeated. A word not in color
can be replaced with another template.
Identifier
Letter
Letter
. . .
_
$
_
Digit
$
4
Letter
A a
B b
C c
D d
E e
F f
G g
H h
I I
J j
K k
L l
M m
N n
O o
P p
Q q
R r
S s
T t
U u
V v
Ww
X x
Y y
Z z
Digit
0
1
2
3
4
5
6
7
8
9
5
Java Identifiers

A Java identifier must start with a letter or
underscore or dollar sign, and be
followed by zero or more letters (A-Z, a-z),
digits (0-9), underscores, or dollar signs.
VALID
age_of_dog
HourlyEmployee
taxRateY2K
ageOfDog
NOT VALID (Why?)
age#
2000TaxRate
Age-Of-Dog
6
What is an Identifier?

An identifier names a class, a method
(subprogram), a field (a variable or a
named constant), or a package in a Java
application

Java is a case-sensitive language;
uppercase and lowercase letters are
different

Using meaningful identifiers is a good
programming practice
7
51 Java Reserved Words
abstract
catch
default
false
goto
int
null
return
switch
transient
while
boolean
char
do
final
if
interface
package
short
synchronized
true
break
class
double
finally
implements
long
private
static
this
try
byte
const
else
float
import
native
protected
strictfp
throw
void
case
continue
extends
for
instanceof
new
public
super
throws
volatile
Reserved words cannot be used as identifiers.
Samples of Java Data Values
int sample values
4578
-4578
0
double sample values
95.274
95.
char sample values
‘B’
‘d’
‘4’
.265
‘?’
‘*’
9
ASCII and Unicode

ASCII (pronounced ask-key) is an older
character set used to represent characters
internally as integers

ASCII is a subset of the newer Unicode
character set

The character ‘A’ is internally stored as integer
65, and successive alphabet letters are stored
as successive integers.
This enables character comparisons with ‘A’
less than ‘B’, etc.

10
Primitive Data Types in Java

Integral Types
 can represent whole numbers and their
negatives when declared as byte, int , short , or
long
 can represent single characters when declared
as char

Floating Point Types
 represent real numbers with a decimal point
 declared as float, or double
11
Java Primitive Data Types
primitive
integral
byte char
short
int
boolean
long
floating point
float
double
We cover boolean in Chapter 4.
12
Vocabulary Review






class (general sense: A description of a group of
objects with similar properties and behaviors
class (Java construct) A pattern for an object
Object (general sense) An entity or thing that is
relevant in the context of a problem
Object (Java) An instance of a class
Instantiation Creating an object, which is an
instance of a class
Method A subprogram that defines one aspect of
the behavior of a class
13
Simplest Java class
HEADING
class DoNothing
{
BODY
}
14
What’s in a class heading?
ACCESS MODIFIER
class
IDENTIFIER
public class PrintName
Block (Compound Statement)

A block is a sequence of zero or more
statements enclosed by a pair of curly braces
{ }.
Block
{
Statement
. . .
}
16
What is a Variable?

A variable is a location in memory to
which we can refer by an identifier, and
in which a data value that can be
changed is stored

Declaring a variable means specifying
both its name and its data type or class
17
What Does a Variable Declaration Do?
int ageOfDog;
A declaration tells the compiler toallocate enough
memory to hold a value of this data type, and to
associate the identifier with this location.
4 bytes for ageOfDog
18
Syntax for Declarations
Variable Declaration
Modifiers TypeName Identifier , Identifier . . . ;
Constant Declaration
Modifiers final TypeName Identifier = LiteralValue;
19
Java String Class

A string is a sequence of characters
enclosed in double quotes.

string sample values
“Today and tomorrow”
“His age is 23.”
“A” (a one character string)

The empty string contains no characters
and is written as “”
20
Actions of Java’s String class

String operations include
joining one string to another
(concatenation)
converting number values to strings
converting strings to number values
comparing 2 strings
21
What is a Named Constant?

A named constant is a location in memory to
which we can refer by an identifier, and in
which a data value that cannot be changed is
stored.
VALID NAMED CONSTANT DECLARATIONS
final
final
final
final
final
String
float
char
int
double
STARS = “****”;
NORMAL_TEMP = 98.6;
BLANK = ‘ ’;
VOTING_AGE = 18;
MAX_HOURS = 40.0;
22
Giving a value to a variable
You can assign (give) a value to a variable by
using the assignment operator =
VARIABLE DECLARATIONS
String firstName;
char
middleInitial;
char
letter;
int
ageOfDog;
VALID ASSIGNMENT STATEMENTS
firstName = “Fido”;
middleInitial = ‘X’;
letter = middleInitial;
ageOfDog = 12;
23

Why is String uppercase and char
lower case?
char is a built in type
String is a class that is provided
Class names begin with uppercase by
convention
24
Assignment Statement Syntax
Variable = Expression;
First, Expression on right is evaluated.
Then the resulting value is stored in the
memory location of Variable on left.
NOTE: The value assigned to Variable must be
of the same type as Variable.
String concatenation (+)

Concatenation uses the + operator.

A built-in type value can be concatenated
with a string because Java automatically
converts the built-in type value for you to a
string first.
26
Concatenation Example
final
final
final
String
int DATE = 2003;
String phrase1 = “Programming and Problem “;
String phrase2 = “Solving in Java “;
bookTitle;
bookTitle = phrase1 + phrase2;
System.out.println(bookTitle + “ has copyright “ + DATE);
27
Using Java output device
METHOD CALL SYNTAX
System.out.print (StringValue);
System.out.println (StringValue);
These examples yield the same output.
System.out.print(“The answer is, ”);
System.out.println(“Yes and No.”);
System.out.println(“The answer is, Yes and No.”);
28
Java Input Devices
More complex than Output Devices
 Must set one up from a more
primitive device

InputStreamReader inStream;
inStream = new
InputStreamReader(System.in);
// declare device inData
BufferedReader inData;
inData = new BufferedReader(inStream)
29
Using a Java Input Device
// Get device in one statement
inData = new BuffredReader(new
InputStreamReader(System.in));
String oneLine;
// Store one line of text into oneLine
oneLine = inData.readLine();
Where does the text come from?
30
Interactive Input




readLine is a value-returning method in
class BufferedReader
readLine goes to the System.in
window and inputs what the user types
How does the user know what to type?
The program (you) tell the user using
System.out
31
Interactive Output continued
BufferedReader inData;
inData = new BufferedReader(new
InputStreamReader(System.in));
String name;
System.out.print(“Enter name: ”);
name = inData.readLine();
Name contains what the user typed in response to
the prompt
32
A Java Application

Must contain a method called main()

Execution always begins with the first
statement in method main()

Any other methods in your program are
subprograms and are not executed until
they are sent a message
33
Java Program
// ******************************************************
// PrintName prints a name in two different formats
// ******************************************************
public class PrintName
{
public static void main (String[ ] args)
{
BufferedReader inData;
String first;
// Person’s first name
String last;
// Person’s last name
String firstLast;
// Name in first-last format
String lastFirst;
// Name in last-first format
inData = new BufferedReader(new
InputStreamReader(System.in));
34
Java program continued
System.out.print(“Enter first name: “);
first = inData.readLine();
System.out.print(“Enter last name: “);
last = inData.readLine();
firstLast = first + “ “ + last;
System.out.println(“Name in first-last format is ”
+ firstLast);
lastFirst = last + “, “ + first;
System.out.println(“Name in last-first format is ”
+ lastFirst);
}
}
35
Method Declaration Syntax
Method Declaration
Modifiers void Identifier (ParameterList)
{
Statement
. . .
}
36
Statement Syntax Template
Statement
NullStatement
LocalConstantDeclaration
LocalVariableDeclaration
AssignmentStatement
MethodCall
Block
NOTE: This is a partial list.
37
One Form of Java Comments

/*
Comments between /* and */ can extend
over several lines.
This is a Java comment.
than one line. */
It can extend over more
/* In this second Java comment the asterisk on the next line
* is part of the comment itself.
*/
38
Another Form of Java Comment

Using two slashes // makes the rest of the
line become a comment.
// ******************************************************
// PrintName prints a name in two different formats
// ******************************************************
String first;
// Person’s first name
String last;
// Person’s middle initial
39
Debugging Process
Enter program
Compile program
Compile-time errors?
Yes
No
Figure out errors,
get back into editor,
and fix errors in
program.
Run program
Logic errors?
No
Yes
Go back to algorithm
and fix design. Get
back into editor and
fix errors in program.
Success!
40
ClassesRevisited
class Name
{
String first;
String second;
}
Classes are active; actions, called
methods, are bound (encapsulated)
with the class variables
41
Methods

Method heading and block
void setName(String arg1, String arg2)
{
first = arg1;
second = arg2;
}

Method call (invocation)
Name myName;
myName.setName(“Nell”, “Dale”);
42
Some Definitions

Instance field A field that exists in ever
instance of a class
String first;
String second;

Instances method A method that exists in
every instance of a class
void setName(String arg1, String arg2);
myName.setName(“Chip”, “Weems”);
String yourName;
yourName.setName(“Mark”, “Headington”);
43
More Definitions

Class method A method that belongs to a class
rather than it object instances; has modifier
static
Date.setDefaultFormat(Date.MONTH_DAY_YEAR);

Class field A field that belongs to a class rather
than its object instances; has modifier static
Will cover class fields in later chapters
44
More Definitions

Constructor method Special method with
the same name as the class that is used
with new when a class is instantiated
public Name(String frst, String lst)
{
first = frst;
last = lst;
}
Name name;
name = new Name(“John”, “Dewey”);
Note: argument cannot be the same as field
45
Void Methods

Void method Does not return a value
System.out.print(“Hello”);
System.out.println(“Good bye”);
name.setName(“Porky”, “Pig”);
object method arguments
46
Value-Returning Methods

Value-returning method Returns a value to
the calling program
String first; String last;
Name name;
System.out.print(“Enter first name: “);
first = inData.readLine();
System.out.print(“Enter last name: “);
last = inData.readLine();
name.setName(first, last);
47
Value-returning example
public String firstLastFormat()
{
return first + “ “ + last;
}
System.out.print(name.firstLastFormat());
object
method
object method
Argument to print method is string returned from
firstLastFormat method
48