55
Chapter 2 The Elements of Java

Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

  • View
    226

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

Chapter 2

The Elements of Java

Page 2: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

2

Knowledge Goals

• Understand the difference between syntax and semantics

• Understand the distinction between built-in types and objects

• Recognize how the char type and String class are related and differ

• See the difference between objects in general and their use in Java

Page 3: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

3

Knowledge Goals

• Understand the difference between a named constant and a variable

• See why it is important to use meaningful identifiers in Java

• Understand what happens in an assignment operation

• Recognize how void and value-returning methods differ in their use

Page 4: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

4

Skill Goals

• Read and understand the formal syntax governing Java programs

• Distinguish between reserved words and identifiers

• Create and recognize legal Java identifiers• Write simple output statements using the System.out class

• Construct a Java application

Page 5: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

5

Skill Goals

• Declare fields of type char and String• Assign values to variables• Construct string expressions• Use comments to clarify programs• Instantiate a Scanner object• Write String input operations using the Scanner class

• Design and interactive user interface

Page 6: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

6

Grammar and Words

Syntax The formal rules governing how valid instructions are written in a programming languageSemanticsThe set of rules that determines the meaning of instructions written in a programming languageMetalanguageA language that is used to write the syntax rules

Syntax says how to write an instructionSemantics says how to interpret an instruction

Page 7: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

7

Grammar and Words

shading:optional

ellipsis (…): repetition

colored word:use as is

black word:another template

Syntax Template

Page 8: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

8

Grammar and Words

Reserved Word

A word that has a specific predefined meaning

public class HelloWorld

{

public static void main(String[] args)

{

System.out.println("Hello World!");

}

} Underlined are reserved

Page 9: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

9

Grammar and Words

Identifiers

A word that we define to name something in an application; should be meaningful

public class HelloWorld

{

public static void main(String[] args)

{

System.out.println("Hello World!");

}

}Bold are identifiers

Page 10: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

10

Grammar and Words

Identifiers

Page 11: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

11

Grammar and Words

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 taxRateY2K TaxRaeY2KHourlyEmployee ageOfDog

Not valid (Why?)age# 2000TaxRate Age-Of-Dog

class char

Beware: Java is case sensitive!

Page 12: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

12

Grammar and Words

Identifier (revised)

A name associated with a package, class, method, or field and used to refer to that element

Method

A subprogram in Java; an operation that carries out a responsibility

Field

A named place in memory that holds data

Page 13: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

13

51 Java Reserved Wordsabstract assert boolean break byte

case catch char classconst continue default dodouble else enum extends false*

final finally float forgoto if implements import

instanceof int interface long nativenew null* packageprivate protectedpublic return short static strictfp

super switch synchronized thisthrow throws transient true*

try void volatile while

*false, null, and true are technically not reserved words. They are predefined literals that cannot be used as identifiers

Reserved words cannot be used as identifiers

Page 14: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

14

Building Blocks

Data Type

Each piece of data has a specific type that determines how the data is represented in a computer

Standard (built-in) types

A data type that is automatically available for use in every Java application

Primitive type

Any of the built-in types that represent integral, real, characters, or Boolean values

Page 15: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

15

Java Primitive Data TypesJava Primitive Data Types

primitive

integral floating point

byte char short int long float double

boolean

We cover char here, the rest of the integral types and floating-point types in Chapter 4, and Boolean in Chapter 5

Page 16: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

16

Building Blocks

Character Set

A list of letters, digits, and symbols with corresponding binary representations in the computer

ASCII (pronounced ask-key)

A character set made up of English letters plus numbers and symbols; each character was 16 bits

Unicode

A superset of ASCII in which each character is represented by 32 bits

Why do we need 32-bits for a character?

Page 17: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

17

Building Blocks

char data type

A built-in type consisting of one alphanumeric character

Examples: 'A' 'a' '1' '?' 'x'

Collating sequence

The ordering of characters, with respect to one another, within a character set

Uppercase letters are ordered Lowercase letters are ordered Numbers are ordered

Why do we putquotes arounda character?

Page 18: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

18

Building Blocks

Classes and ObjectsReview of vocabulary

Object (general sense) An entity or thing that is relevant in the context of a problem

Object (Java) An entity containing data in fields with associated operations

Class (general sense) A description of the attributes and behavior of a group of objects with similar properties and behaviors

class (Java construct) A pattern for an object containing fields and methods

Page 19: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

19

Building Blocks

Responsibility An operation associated with a class

Method A subprogram that defines one aspect of the behavior of a class (a responsibility)

Instance A way of referring to an object as being an example of its class

Instantiation Creating an object, which is an instance of a class

Page 20: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

20

Building Blocks

String (general sense)

A sequence of characters, such as a word, name, or sentence, enclosed in double quotes

String (Java sense)

An object; an instance of the String class

Actually, Java strings are written in a program

like general strings: within double quotes

Can you explain why char is lowercase

and String is uppercase?

Page 21: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

21

Building Blocks

public class HelloWorld

{

public static void main(String[] args)

{

System.out.println("Hello World!");

}

}

Method call

Page 22: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

22

Building Blocks

Call

A statement that causes a method to be executed; in Java we call a method by writing its name, followed by a list of arguments enclosed in parentheses

Argument

An expression used to communicate values to a method

Page 23: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

23

Building Blocks

Page 24: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

24

Building Blocks

System: class name (uppercase)

out: object name (lowercase)

println: method, print and go to new line

print: method, print and remain on same

line

What is printed by

System.out.print("Hi");

System.out.println("neighbor");

System.out.println():

Page 25: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

25

Building Blocks

Call (another view)

Sends a message to an object to execute a responsibility

System.out.println("neighbor");

sends a message to System.out to execute its println responsibility; "neighbor" is the information that println needs to carry out its responsibility

Page 26: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

26

Putting the Pieces Together

class DoNothing{}

Does it match the diagram?

Simplest class

Page 27: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

27

Putting Pieces Together

Where's the action?To be a program (application) there must be a method main with this exact heading

public static void main(String[] args)

{

// Code for doing something

}

What do you think String[] args is?

Page 28: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

28

Putting the Pieces Together

Access modifiers

Reserved words in Java that specify where a class, method, or field may be accessed; private and public are access modifiers

Page 29: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

29

Putting the Pieces Together

import java.util.Scanner;

import java.io.*;

Needed for input

Needed for more output

Page 30: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

30

Putting the Pieces Together

public class MessageOut

{

public static void main(String[] args)

{

System.out.println("Good morning neighbor!");

System.out.println("What a beautiful day!");

System.out.print("What is on your agenda?");

System.out.println();

}

}

How do we know this is an application?

Page 31: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

31

Putting the Pieces Together

Compilingand

runningcycle

Page 32: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

32

Extending the Java Dictionary

How do we define problem-related words?Declaration

A statement that associates an identifier with field, a method, a class, or a package so that the programmer can refer to it by name

char myChar;

String myFirstName;

String myLastName;

String myName;

myChar,myFirstName,myLastName,

myNameare all

variables

Page 33: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

33

Extending the Java Dictionary

Variable

A location in memory, referenced by an identifier, that contains a data value that can be changed

Typespecifieswhat canbe stored

in thevariable

Page 34: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

34

Extending the Java Dictionary

State after declaration

Page 35: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

35

Extending the Java Dictionary

The compiler allocates enough memory to hold a value of the char data type (2 bytes) and associates the identifier myInitial with this location

What does this declaration actually do?

char myInitial;

myInitial

Page 36: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

36

Extending the Java Dictionary

But how do we get a value into a variable?

Yes, but what is an expression?

Page 37: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

37

Extending the Java Dictionary

Assignment statement

A statement that stores the value of an expression into a variable

Expression

An arrangement of identifiers, values, and operators that can be evaluated to compute a value of a given type

Evaluate

To compute a new value by performing a specified set of operations on given values

Page 38: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

38

Extending the Java Dictionary

myChar = 'B';

Page 39: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

39

Extending the Java Dictionary

myChar = 'B';

myFirstName = "Susy";

myLastName = "Sunshine";

myName = myFirstName + ' ' + myChar +

myLastName;

System.out.println(myName);

Characters are in single quotesStrings are in double quotes+ is the concatenation operator

Page 40: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

40

Extending the Java Dictionary

Initializer expressions

char myChar = 'B';

String myFirstName = "Susy";

String myLastName = "Sunshine";

String myName = myFirstName + " " +

myChar + ' ' + myLastName;

What is the difference between ' ' and " "?

Page 41: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

41

Extending the Java Dictionary

What do these declarations actually do?char myChar = 'B';

String myFirstName = "Susy";

The compiler creates the following in memory

B

myChar myFirstname

S u s y

Assignment of primitive types vs. objects

Page 42: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

42

Extending the Java Dictionary

Literal constant

Any value written directly in Java

Named (symbolic) constant

A location in memory, referenced by an identifier, that contains a data value that cannot be changed

final String BORDER = "*********";

final char BLANK = ' ';

final isthe

keyword

Page 43: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

43

Extending the Java Dictionary

No, we haven't forgotten to define static ; we have just ignored it

Class fields

Fields that belong to the class as a whole; there is one copy for the class

Instance fields

Fields that belong to an instance of a class; each instance has its own field

static fields are class fields

Page 44: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

44

Extending Java Dictionary

Local declarations

Declarations that are defined within a method

Thus there are three kinds of declarations class (marked static) instance (marked private or public) local (carry not modifiers) (Why?)

Page 45: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

45

Extending Java Dictionary

Documentation

The written text and comments that make an application easier for others to understand, use, and modify

Implicit documentation

Use of coding conventions to give meaning to identifiers

constants: all uppercase classes: begin with uppercase variables and methods: begin with lowercase

Page 46: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

46

User Input

Page 47: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

47

User Input

import java.util.Scanner;

Scanner in;

in = new Scanner(System.in);

Access Scanner class

Declare Scanner variable

Instantiate Scanner object

The name of a class used on the right of an equal sign following word new is a call to the class's constructor, which

creates and returns an instance of the class, which is then stored in the variable on the left of the equal sign

Page 48: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

48

User Input

String firstName;

System.out.println("Enter first name");

firstName = in.nextLine();

System.out.println("Welcome " + firstName);

If the user types in "Sarah", what is printed?

Page 49: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

49

User Input

String firstName;

System.out.println("Enter first name");

firstName = in.nextLine();

Place to store input

Prompt for input

Method call to in objectLine of typing is stored

in firstName

Page 50: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

50

User Input

firstName = in.nextLine();

nextLine is a value-returning method; it returns the next line of input, which is then stored into firstName

Why is there no expressionbetween the parentheses?

Page 51: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

51

User Input

Value-returning method

A method that is called from within an expression and returns a value that can be used in the expression

void method

A method that is called as a separate statement; when it returns, processing continues with the next statement

Can you give an example of each?

Page 52: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

52

Blocks

public static void main(String[] args)

{

System.out.println("Good morning neighbor!");

System.out.println("What a beautiful day!");

System.out.print("What is on your agenda?");

System.out.println();

}

Page 53: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

53

Blocks

Rule forsemicolons:Terminate

each statement except a

block with a

semicolon

Page 54: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

54

Extras

DataStorage

Page 55: Chapter 2 The Elements of Java. 2 Knowledge Goals Understand the difference between syntax and semantics Understand the distinction between built-in types

55

Extras

I was amathematician,

religiousphilosopher,

andinventor

Who was I?