Upload
joshua-rosenstein
View
224
Download
0
Embed Size (px)
Citation preview
7/31/2019 Chapter 2 Animated
1/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 1
Chapter 2
Getting Started with Java
Animated Version
7/31/2019 Chapter 2 Animated
2/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 2
Objectives
After you have read and studied this chapter, youshould be able to
Identify the basic components of Java programs
Write simple Java programs Describe the difference between object declaration and creation
Describe the process of creating and running Java programs
Use the Date, SimpleDateFormat, String, and Scanner standard
classes
Develop Java programs, using the incremental development
approach
7/31/2019 Chapter 2 Animated
3/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 3
The First Java Program
The fundamental OOP concept illustrated by theprogram:
An object-oriented program usesobjects.
This program displays a window on the screen.
The size of the window is set to 300 pixels wideand 200 pixels high. Its title is set to My First Java
Program.
7/31/2019 Chapter 2 Animated
4/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 4
Program Ch2Sample1
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(My First Java Program);
myWindow.setVisible(true);
}
}
Declare a name
Create an object
Use an object
7/31/2019 Chapter 2 Animated
5/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 5
Program Diagram for Ch2Sample1
myWindow : JFrame
Ch2Sample1
setTitle(My First Java Program)
7/31/2019 Chapter 2 Animated
6/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 6
Dependency Relationship
myWindow : JFrame
Ch2Sample1
Instead of drawing all messages, we summarize it by showing
only the dependency relationship. The diagram shows thatCh2Sample1depends on the service provided by myWindow.
7/31/2019 Chapter 2 Animated
7/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 7
MoreExamples
Object Declaration
JFrame myWindow;
Account customer;Student jan, jim, jon;
Vehicle car1, car2;
Object NameOne object is declaredhere.
Class Name
This class must bedefined before this
declaration can be stated.
7/31/2019 Chapter 2 Animated
8/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 8
Object Creation
myWindow = new JFrame ( ) ;
MoreExamples
customer = new Customer( );
jon = new Student(John Java);car1 = new Vehicle( );
Object NameName of the object we
are creating here.
Class Name
An instance of this classis created.
Argument
No arguments are usedhere.
7/31/2019 Chapter 2 Animated
9/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 9
Declaration vs. Creation
Customer customer;
customer = new Customer( );
Customer customer;
customer = new Customer( );
1. The identifiercustomeris
declared and space is
allocated in memory.
2. A Customerobject is
created and the identifier
customeris set to refer to it.
1
2
customer
1
: Customer2
7/31/2019 Chapter 2 Animated
10/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 10
State-of-Memory vs. Program
customer
: Customer
State-of-Memory
Notation
customer : Customer
Program Diagram
Notation
7/31/2019 Chapter 2 Animated
11/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 11
Name vs. Objects
Customer customer;
customer = new Customer( );
customer = new Customer( );
Customer customer;
customer
customer = new Customer( );
customer = new Customer( );
: Customer : CustomerCreated with
the first new.
Created with the second
new. Reference to the firstCustomer object is lost.
7/31/2019 Chapter 2 Animated
12/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 12
Sending a Message
myWindow . setVisible ( true ) ;
MoreExamples
account.deposit( 200.0 );
student.setName(john);car1.startEngine( );
Object NameName of the object to
which we are sending a
message.
Method NameThe name of the
message we are sending.
ArgumentThe argument we are
passing with the
message.
7/31/2019 Chapter 2 Animated
13/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 13
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle
(My First Java Program);
myWindow.setVisible(true);
Execution Flow
myWindow.setSize(300, 200);
Jframe myWindow;
myWindow
myWindow.setVisible(true);
State-of-Memory Diagram
: JFrame
width
height
title
visible
200
My First Java
300
true
myWindow = new JFrame( );
myWindow.setTitle
(My First Java Program);
The diagram shows only four of the many data
members of a JFrame object.
Program Code
7/31/2019 Chapter 2 Animated
14/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 14
Program Components
A Java program is composed of
comments,
import statements, and
class declarations.
7/31/2019 Chapter 2 Animated
15/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 15
/*Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java
*/
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(My First Java Program);
myWindow.setVisible(true);
}
}
Program Component: Comment
Comment
7/31/2019 Chapter 2 Animated
16/54
The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 2 - 16
Matching Comment Markers
/* This is a comment on one line */
/*
Comment number 1
*/
/*
Comment number 2
*/
/*
/*
/*This is a comment
*/
*/
Error: No matching
beginning marker.
These are part of the
comment.
7/31/2019 Chapter 2 Animated
17/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 17
Three Types of Comments
/*
This is a comment with
three lines of
text.
*/
Multiline Comment
Single line Comments
// This is a comment
// This is another comment
// This is a third comment
/**
* This class provides basic clock functions. In addition
* to reading the current time and todays date, you can
* use this class for stopwatch functions.
*/
javadoc Comments
7/31/2019 Chapter 2 Animated
18/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 18
Import Statement
/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java
*/
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(My First Java Program);
myWindow.setVisible(true);
}
}
ImportStatement
7/31/2019 Chapter 2 Animated
19/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 19
Import Statement Syntax and Semantics
. ;e.g. dorm . Resident;
MoreExamples
import javax.swing.JFrame;import java.util.*;
import com.drcaffeine.simplegui.*;
Class Name
The name of the class wewant to import. Use asterisks
to import all classes.
Package Name
Name of the package thatcontains the classes we
want to use.
7/31/2019 Chapter 2 Animated
20/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 20
Class Declaration
/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java
*/
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(My First Java Program);
myWindow.setVisible(true);
}
}
Class
Declaration
7/31/2019 Chapter 2 Animated
21/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 21
Method Declaration
/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java
*/
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(My First Java Program);
myWindow.setVisible(true);
}
}
MethodDeclaration
7/31/2019 Chapter 2 Animated
22/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 22
Method Declaration Elements
public static void main( String[ ] args ){
JFramemyWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(My First Java Program);
myWindow.setVisible(true);
}
Method Body
Modifier Modifier Return Type Method Name Parameter
7/31/2019 Chapter 2 Animated
23/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 23
Template for Simple Java Programs
/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java
*/
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(
My First Java Program);
myWindow.setVisible(true);
}
}
ImportStatements
Class Name
Comment
Method Body
7/31/2019 Chapter 2 Animated
24/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 24
Why Use Standard Classes
Dont reinvent the wheel. When there are existingobjects that satisfy our needs, use them.
Learning how to use standard Java classes is thefirst step toward mastering OOP. Before we can
learn how to define our own classes, we need tolearn how to use existing classes
We will introduce four standard classes here: Scanner
String
Date
SimpleDateFormat.
7/31/2019 Chapter 2 Animated
25/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 25
Standard Output
Using print ofSystem.out (an instance of thePrintStream class) is a simple way to display aresult of a computation to the user.
System.out.print(I Love Java);
The result appears onthe console window.
The actual appearance
of the console window
differs depending on
the Java tool you use
I Love Java
7/31/2019 Chapter 2 Animated
26/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 26
Using the print Method
The print method will continue printing from theend of the currently displayed output.
System.out.print(How do you do? );
System.out.print(My name is );
System.out.print(Jon Java. );
How do you do? My name is Jon Java.
7/31/2019 Chapter 2 Animated
27/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 27
Using the println Method
The println method will skip to the next line afterprinting out its argument.
System.out.println(How do you do? );
System.out.println(My name is );
System.out.println(Jon Java. );
How do you do?My name is
Jon Java.
7/31/2019 Chapter 2 Animated
28/54
7/31/2019 Chapter 2 Animated
29/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 29
String is an Object
1. The identifiername isdeclared and space is
allocated in memory.
2. A String object is created
and the identifiername is
set to refer to it.
1
2
name
1
String name;
name = new String(Jon Java);
String name;
name = new String(Jon Java);
2
: String
Jon Java
7/31/2019 Chapter 2 Animated
30/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 30
String Indexing
The position, or index, of
the first character is 0.
7/31/2019 Chapter 2 Animated
31/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 31
Definition: substring
Assume str is a String object and properlyinitialized to a string.
str.substring( i, j ) will return a new string byextracting characters of str from position i toj-1where 0 i length of str, 0 j length of str,and i j.
If str is programming , then str.substring(3, 7)will create a new string whose value is gram
because g is at position 3 and m is at position6.
The original string strremains unchanged.
7/31/2019 Chapter 2 Animated
32/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 32
Examples: substring
String text = Espresso;
text.substring(6,8)
text.substring(0,8)
text.substring(1,5)
text.substring(3,3)
text.substring(4,2)
so
Espresso
spre
error
7/31/2019 Chapter 2 Animated
33/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 33
Definition: length
Assume str is a String object and properlyinitialized to a string.
str.length( ) will return the number of
characters in str.
If str is programming , then str.length( ) willreturn 11 because there are 11 characters in it.
The original string strremains unchanged.
7/31/2019 Chapter 2 Animated
34/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 34
Examples: length
String str1, str2, str3, str4;
str1 = Hello ;str2 = Java ;
str3 = ; //empty string
str4 = ; //one space
str1.length( )
str2.length( )
str3.length( )
str4.length( )
5
4
1
0
7/31/2019 Chapter 2 Animated
35/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 35
Definition: indexOf
Assume str and substr are String objects andproperly initialized.
str.indexOf( substr ) will return the first positionsubstr occurs in str.
If str is programming and substr is gram ,then str.indexOf(substr ) will return 3 becausethe position of the first character of substr in stris 3.
If substr does not occur in str, then1 isreturned.
The search is case-sensitive.
7/31/2019 Chapter 2 Animated
36/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 36
Examples: indexOf
String str;str = I Love Java and Java loves me. ;
str.indexOf( J )
str2.indexOf( love )
str3. indexOf( ove )
str4. indexOf( Me )
7
21
-1
3
3 7 21
7/31/2019 Chapter 2 Animated
37/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 37
Definition: concatenation
Assume str1 and str2 are String objects andproperly initialized.
str1 + str2 will return a new string that is a
concatenation of two strings.
If str1 is pro and str2 is gram , then str1 +str2 will return program.
Notice that this is an operator and not a method
of the String class. The strings str1 and str2 remains the same.
7/31/2019 Chapter 2 Animated
38/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 38
Examples: concatenation
String str1, str2;str1 = Jon ;
str2 = Java ;
str1 + str2
str1 + + str2
str2 + , + str1
Are you + str1 + ?
JonJava
Jon Java
Java, Jon
Are you Jon?
7/31/2019 Chapter 2 Animated
39/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 39
Date
The Date class from thejava.util package is used
to represent a date.
When a Date object is created, it is set to today
(the current date set in the computer)
The class has toString method that converts theinternal format to a string.
Date today;
today = new Date( );
today.toString( );
Fri Oct 31 10:05:18 PST 2003
7/31/2019 Chapter 2 Animated
40/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 40
SimpleDateFormat
The SimpleDateFormat class allows the Dateinformation to be displayed with various format.
Table 2.1 page 62 shows the formatting options.
Date today = new Date( );
SimpleDateFormat sdf1, sdf2;
sdf1 = new SimpleDateFormat( MM/dd/yy );
sdf2 = new SimpleDateFormat( MMMM dd, yyyy );
sdf1.format(today);
sdf2.format(today);
10/31/03
October 31, 2003
7/31/2019 Chapter 2 Animated
41/54
7/31/2019 Chapter 2 Animated
42/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 42
Reading from Standard Input
After the Scanner object is set up, we can read data. The following inputs the first name (String):
System.out.print (Enter your first name: );
Enter your first name: ENTERGeorge
Nice to meet you, George.
1. Prompt is displayed
2. Data is entered
3. Result is printed
String firstName = scanner.next();
System.out.println(Nice to meet you, +firstName +.);
7/31/2019 Chapter 2 Animated
43/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 43
Problem Statement
Problem statement:Write a program that asks for the users first,
middle, and last names and replies with their
initials.
Example:
input: Andrew Lloyd Weber
output: ALW
7/31/2019 Chapter 2 Animated
44/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 44
Overall Plan
Identify the major tasks the program has to
perform.
We need to know what to develop before we develop!
Tasks:
Get the users first, middle, and last names
Extract the initials and create the monogram
Output the monogram
7/31/2019 Chapter 2 Animated
45/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 45
Development Steps
We will develop this program in two steps:
1. Start with the program template and add code to
get input
2. Add code to compute and display the monogram
7/31/2019 Chapter 2 Animated
46/54
7/31/2019 Chapter 2 Animated
47/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 47
Step 1 Code
/*
Chapter 2 Sample Program: Displays the MonogramFile: Step1/Ch2Monogram.java
*/
import javax.swing.*;
class Ch2Monogram {
public static void main (String[ ] args) {
String name;
name = JOptionPane.showInputDialog(null,"Enter your full name (first, middle, last):);
JOptionPane.showMessageDialog(null, name);
}
}
7/31/2019 Chapter 2 Animated
48/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 48
Step 1 Test
In the testing phase, we run the program and
verify that
we can enter the name
the name we enter is displayed correctly
7/31/2019 Chapter 2 Animated
49/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 49
Step 2 Design
Our programming skills are limited, so we will
make the following assumptions:
input string contains first, middle, and last names
first, middle, and last names are separated by
single blank spaces Example
John Quincy Adams (okay)
John Kennedy (not okay)
Harrison, William Henry (not okay)
7/31/2019 Chapter 2 Animated
50/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 50
Step 2 Design (contd)
Given the valid input, we can compute themonogram by breaking the input name into first, middle, and last
extracting the first character from them
concatenating three first characters
Aaron Ben Cosner
Aaron Ben Cosner
Ben Cosner
ABC
7/31/2019 Chapter 2 Animated
51/54
7/31/2019 Chapter 2 Animated
52/54
7/31/2019 Chapter 2 Animated
53/54
The McGraw-Hill Companies, Inc. Permissionrequired for reproduction or display. Chapter 2 - 53
Step 2 Test
In the testing phase, we run the program and
verify that, for all valid input values, correct
monograms are displayed.
We run the program numerous times. Seeing
one correct answer is not enough. We haveto try out many different types of (valid) input
values.
7/31/2019 Chapter 2 Animated
54/54
Program Review
The work of a programmer is not done yet.
Once the working program is developed, we
perform a critical review and see if there are
any missing features or possible
improvements One suggestion
Improve the initial prompt so the user knows the
valid input format requires single spaces between
the first, middle, and last names