Java Programming
Getting Started with Java
Chapter 2 - 1
Objectives
• 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
Chapter 2 - 2
The First Java Program
• The fundamental OOP concept illustrated by the program:
An object-oriented program uses objects.
• This program displays a window on the screen.
• The size of the window is set to 300 pixels wide and 200 pixels high.
Its title is set to My First Java Program.
Chapter 2 - 3
Program Ch2Sample1 Output
Chapter 2 - 4
Program Ch2Sample1
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
Declare a name
myWindow = new JFrame( );
Create an object
myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}
Use an object
Chapter 2 - 5
Program Diagram for Ch2Sample1
Ch2Sample1 setSize(300, 200
)
setTitle(“My First Java Program”)
myWindow : JFrame
(true )
setVisible
Chapter 2 - 6
Dependency Relationship
Ch2Sample1
myWindow : JFrame
Instead of drawing all messages, we summarize it by showing
only the dependency relationship. The diagram shows that
Ch2Sample1 “depends” on the service provided by myWindow.
Chapter 2 - 7
Object Declaration
Class Name
This class must be Object Name
defined before this One object is declared
declaration can be here.
stated.
JFrame myWindow;
Account customer;
More Student jan, jim, jon;
Examples Vehicle car1, car2;
Chapter 2 - 8
Object Creation
Class Name Argument
Object Name
An instance of this class No arguments are used
Name of the object we
is created. here.
are creating here.
myWindow = new JFrame ( );
customer = new Customer( );
More jon = new Student(“John Java”);
Examples car1 = new Vehicle( );
Chapter 2 - 9
Declaration vs. Creation
1 Customer
Customer customer;
customer;
customer = new Customer( );
2 customer = new Customer( );
1. The identifier customer is
customer declared and space is
1 allocated in memory.
2. A Customer object is
: Customer
2 created and the identifier
customer is set to refer to it.
Chapter 2 - 10
State-of-Memory vs. Program
customer
customer : Customer
: Customer
State-of-Memory Program Diagram
Notation Notation
Chapter 2 - 11
Name vs. Objects
Customer
Customer customer;
customer;
customer = new Customer( );
customer = new Customer( );
customer = new Customer( );
customer = new Customer( );
customer
Created with the second
Created with : Customer : Customer new. Reference to the first
the first new. Customer object is lost.
Chapter 2 - 12
Sending a Message
Object Name Method Name Argument
Name of the object to The name of the The argument we are
which we are sending a message we are sending. passing with the
message. message.
myWindow . setVisible ( true ) ;
account.deposit( 200.0 );
student.setName(“john”);
More
car1.startEngine( );
Examples
Chapter 2 - 13
Execution Flow
Program Code State-of-Memory Diagram
myWindow
Jframe myWindow;
: JFrame
myWindow = new JFrame( );
myWindow.setSize(300, 200); width 300
myWindow.setTitle height 200
(“My First Java Program”);
myWindow.setVisible(true); title My First Java …
visible true
The diagram shows only four of the many data
members of a JFrame object.
Chapter 2 - 14
Program Components
• A Java program is composed of
– comments,
– import statements, and
– class declarations.
Chapter 2 - 15
Three Types of Comments
/*
This is a comment with
three lines of
text. Multiline Comment
*/
// This is a comment
// This is another comment
// This is a third comment Single line Comments
/**
* This class provides basic clock functions. In addition
* to reading the current time and today’s date, you can
* use this class for stopwatch functions. javadoc Comments
*/
Chapter 2 - 16
Comment and Import Statement
/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java
*/
import javax.swing.*; Import
Statement
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);
}
}
Chapter 2 - 17
Class Declaration
/*
Chapter 2 Sample Program: Displaying a Window Class
Declaration
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);
}
}
Chapter 2 - 18
Method Declaration
/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java Method
*/ Declaration
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);
}
}
Chapter 2 - 19
Method Declaration Elements
Modifier Modifier Return Type Method Name Parameter
public static void main( String[ ] args ){
JFrame myWindow;
Method Body
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
Chapter 2 - 20
Access specifier
Table 4.1: Scope by access specifier (x means “in scope”)
Location Private No modifier Protected Public
Same class x x x x
Subclass in the same - x x x
package
Non-subclass in the same - - x x
package
Subclass in another package - - x x
Non-subclass in another - - - x
package
Why Use Standard Classes
• Don’t reinvent the wheel. When there are existing objects that
satisfy our needs, use them.
• Learning how to use standard Java classes is the first step toward
mastering OOP. Before we can learn how to define our own classes,
we need to learn how to use existing classes
• We will introduce four standard classes here:
– Scanner
– String
– Date
– SimpleDateFormat.
Chapter 2 - 22
Standard Output
• Using print of System.out (an instance of the PrintStream class) is a
simple way to display a result of a computation to the user.
System.out.print(“I Love Java”);
The result appears on
I Love Java the console window.
The actual
appearance of the
console window differs
depending on the Java
tool you use
Chapter 2 - 23
Using the print Method
• The print method will continue printing from the
end 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.
Chapter 2 - 24
Using the println Method
• The println method will skip to the next line after
printing 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.
Chapter 2 - 25
String
• The textual values passed to the showMessageDialog method
are instances of the String class.
• A sequence of characters separated by double quotes is a
String constant.
• There are close to 50 methods defined in the String class. We
will introduce three of them here: substring, length, and
indexOf.
• We will also introduce a string operation called
concatenation.
Chapter 2 - 26
String is an Object
1 String
String name;
name;
name = new String(“Jon Java”);
2 name = new String(“Jon Java”);
name 1. The identifier name is
declared and space is
1 allocated in memory.
: String
2
2. A String object is created
Jon Java and the identifier name is
set to refer to it.
Chapter 2 - 27
String Indexing
The position, or index, of
the first character is 0.
Chapter 2 - 28
Definition: substring
• Assume str is a String object and properly initialized to a
string.
• str.substring( i, j ) will return a new string by extracting
characters of str from position i to j-1 where 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 position 6.
• The original string str remains unchanged.
Chapter 2 - 29
Examples: substring
String text = “Espresso”;
text.substring(6,8)
“so”
text.substring(0,8)
“Espresso”
text.substring(1,5)
“spre”
text.substring(3,3)
“”
text.substring(4,2)
error
Chapter 2 - 30
Definition: length
• Assume str is a String object and properly initialized to a
string.
• str.length( ) will return the number of characters in str.
• If str is “programming” , then str.length( ) will return 11
because there are 11 characters in it.
• The original string str remains unchanged.
Chapter 2 - 31
Examples: length
String str1, str2, str3, str4;
str1 = “Hello” ;
str2 = “Java” ;
str3 = “” ; //empty string
str4 = “ “ ; //one space
str1.length( )
5
str2.length( )
4
str3.length( )
0
str4.length( )
1
Chapter 2 - 32
Definition: indexOf
• Assume str and substr are String objects and properly
initialized.
• str.indexOf( substr ) will return the first position substr occurs
in str.
• If str is “programming” and substr is “gram” , then
str.indexOf(substr ) will return 3 because the position of the
first character of substr in str is 3.
• If substr does not occur in str, then –1 is returned.
• The search is case-sensitive.
Chapter 2 - 33
Examples: indexOf
String str;
str = “I Love Java and Java loves me.” ;
3 7 21
str.indexOf( “J” )
7
str2.indexOf( “love” )
21
str3. indexOf( “ove” )
3
str4. indexOf( “Me” )
-1
Chapter 2 - 34
Definition: concatenation
• Assume str1 and str2 are String objects and properly
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.
Chapter 2 - 35
Examples: concatenation
String str1, str2;
str1 = “Jon” ;
str2 = “Java” ;
str1 + str2
“JonJava”
str1 + “ “ + str2
“Jon Java”
str2 + “, “ + str1
“Java, Jon”
“Are you “ + str1 + “?”
“Are you Jon?”
Chapter 2 - 36
Date
• The Date class from the java.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 the internal format to a
string.
Date today;
today = new Date( );
today.toString( );
“Thu Dec 18 18:16:56 PST 2008”
Chapter 2 - 37
SimpleDateFormat
• The SimpleDateFormat class allows the Date
information 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); “12/18/08”
sdf2.format(today); “December 19, 2008”
Chapter 2 - 38
Standard Input
• Using a Scanner object is a simple way to input data from the
standard input System.in, which accepts input from the keyboard.
• First we need to associate a Scanner object to System.in as
follows:
import java.util.Scanner;
Scanner scanner;
scanner = new Scanner(System.in);
Chapter 2 - 39
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: ”);
String firstName = scanner.next();
System.out.println(“Nice to meet you, ” +
firstName + “.”);
Enter your first name: George ENTER
1. Prompt is displayed
Nice to meet you, George.
2. Data is entered
3. Result is printed
Chapter 2 - 40
References
• An introduction to object-oriented programming with Java
(Fifth Edition), C. Thomas Wu
• Java 8 Programming Black Book (2015 Edition), DT
Editorial Services, Comprehensive Problem Solver.
Chapter 2 - 41
Exercises: No. 20, 26, 28
Chapter 2 - 42