1 chapter 2 java syntax and semantics, classes, and objects

48
1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

Post on 22-Dec-2015

237 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

1

Chapter 2

Java Syntax and Semantics,

Classes, and Objects

Page 2: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

2

Chapter 2 Topics

Elements of Java Programs Application Construction Application Entry, correction, and

Execution Classes and methods

Page 3: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

3

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

Page 4: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

4

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 $ $

Identifier Syntax Template

Page 5: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

5

A aB bC cD dE eF fG gH hI IJ jK kL lM mN nO oP pQ qR rS sT tU uV vW wX xY yZ z

Letter

0123456789

Digit

Page 6: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

6

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 taxRateY2KHourlyEmployee ageOfDog

NOT VALID (Why?)age# 2000TaxRate Age-Of-Dog

Page 7: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

7

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

Page 8: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

51 Java Reserved Words

abstract boolean break byte case

catch char class const continue

default do double else extends

false final finally float for

goto if implements importinstanceof

int interface long native new

null package private protected public

return short static strictfp super

switch synchronized this throw throws

transient true try void volatile

while

Reserved words cannot be used as identifiers.

Page 9: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

9

Samples of Java Data Values

int sample values 4578 -4578 0

double sample values95.274 95. .265

char sample values

‘B’ ‘d’ ‘4’ ‘?’ ‘*’

Page 10: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

10

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.

Page 11: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

11

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

Page 12: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

12

Java Primitive Data TypesJava Primitive Data Types

primitive

integral floating point

byte char short int long float double

boolean

We cover boolean in Chapter 4.

Page 13: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

13

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

Page 14: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

14

Simplest Java class

class DoNothing

{

}

HEADING

BODY

Page 15: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

What’s in a class heading?

public class PrintName

ACCESS MODIFIER class IDENTIFIER

Page 16: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

16

A block is a sequence of zero or more statements enclosed by a pair of curly braces { }.

Block

{

Statement

. . .

}

Block (Compound Statement)

Page 17: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

17

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

Page 18: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

18

What Does a Variable Declaration Do?

A declaration tells the compiler toallocate enough memory to hold a value of this data type, and to associate the identifier with this location.

int ageOfDog;

4 bytes for ageOfDog

Page 19: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

19

Variable Declaration

Modifiers TypeName Identifier , Identifier . . . ;

Constant Declaration

Modifiers final TypeName Identifier = LiteralValue;

Syntax for Declarations

Page 20: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

20

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 “”

Page 21: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

21

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

Page 22: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

22

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 String STARS = “****”;

final float NORMAL_TEMP = 98.6;

final char BLANK = ‘ ’;

final int VOTING_AGE = 18;

final double MAX_HOURS = 40.0;

Page 23: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

23

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;

Page 24: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

24

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

Page 25: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

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.

Assignment Statement Syntax

Page 26: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

26

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.

Page 27: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

27

Concatenation Example

final int DATE = 2003;

final String phrase1 = “Programming and Problem “;

final String phrase2 = “Solving in Java “;

String bookTitle;

bookTitle = phrase1 + phrase2;

System.out.println(bookTitle + “ has copyright “ + DATE);

Page 28: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

28

System.out.print (StringValue);

System.out.println (StringValue);

Using Java output device

METHOD CALL SYNTAX

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.”);

Page 29: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

29

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 inDataBufferedReader inData; inData = new BufferedReader(inStream)

Page 30: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

30

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?

Page 31: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

31

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

Page 32: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

32

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

Page 33: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

33

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

Page 34: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

34

// ******************************************************

// 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));

Java Program

Page 35: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

35

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);

} }

Page 36: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

36

Method Declaration

Modifiers void Identifier (ParameterList)

{

Statement

. . .

}

Method Declaration Syntax

Page 37: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

37

Statement Syntax TemplateStatement

NullStatement

LocalConstantDeclaration

LocalVariableDeclaration

AssignmentStatement

MethodCall

Block

NOTE: This is a partial list.

Page 38: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

38

/* This is a Java comment. It can extend over more

than one line. */

/* In this second Java comment the asterisk on the next line

* is part of the comment itself.

*/

One Form of Java Comments

Comments between /* and */ can extend over several lines.

Page 39: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

39

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

Page 40: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

40

Debugging Process

Enter program

Compile program

Compile-time errors?

Run program

Logic errors?

Success!

Figure out errors,get back into editor, and fix errors inprogram.

Go back to algorithmand fix design. Getback into editor and fix errors in program.

No

No

Yes

Yes

Page 41: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

41

ClassesRevisited

class Name{ String first; String second;}

Classes are active; actions, called methods, are bound (encapsulated) with the class variables

Page 42: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

42

Methods

Method heading and blockvoid setName(String arg1, String arg2)

{

first = arg1;

second = arg2;

}

Method call (invocation) Name myName;

myName.setName(“Nell”, “Dale”);

Page 43: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

43

Some Definitions

Instance field A field that exists in ever instance of a classString 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”);

Page 44: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

44

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

Page 45: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

45

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

Page 46: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

46

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

Page 47: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

47

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);

Page 48: 1 Chapter 2 Java Syntax and Semantics, Classes, and Objects

48

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