View
226
Download
0
Tags:
Embed Size (px)
Citation preview
Chapter 2
The Elements of Java
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
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
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
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
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
7
Grammar and Words
shading:optional
ellipsis (…): repetition
colored word:use as is
black word:another template
Syntax Template
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
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
10
Grammar and Words
Identifiers
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!
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
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
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
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
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?
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?
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
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
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?
21
Building Blocks
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Method call
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
23
Building Blocks
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():
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
26
Putting the Pieces Together
class DoNothing{}
Does it match the diagram?
Simplest class
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?
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
29
Putting the Pieces Together
import java.util.Scanner;
import java.io.*;
Needed for input
Needed for more output
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?
31
Putting the Pieces Together
Compilingand
runningcycle
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
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
34
Extending the Java Dictionary
State after declaration
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
36
Extending the Java Dictionary
But how do we get a value into a variable?
Yes, but what is an expression?
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
38
Extending the Java Dictionary
myChar = 'B';
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
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 " "?
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
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
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
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?)
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
46
User Input
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
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?
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
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?
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?
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();
}
53
Blocks
Rule forsemicolons:Terminate
each statement except a
block with a
semicolon
54
Extras
DataStorage
55
Extras
I was amathematician,
religiousphilosopher,
andinventor
Who was I?