SlideShare a Scribd company logo
Chapter 2 Getting Started with Java
Objectives After you have read and studied this chapter, you should 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 JOptionPane standard classes Develop Java programs, using the incremental development approach
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 .
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
Program Diagram for Ch2Sample1 setSize(300, 200) setTitle(“My First Java Program”) myWindow : JFrame Ch2Sample1 setVisible(true)
Dependency Relationship 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 . myWindow : JFrame Ch2Sample1
Object Declaration JFrame    myWindow; Account customer; Student jan, jim, jon; Vehicle car1, car2; More Examples Object Name One object is declared here. Class Name This class must be defined before this declaration can be stated.
Object Creation myWindow  =  new  JFrame  (  ) ; customer  = new Customer( ); jon = new Student(“John Java”); car1 = new Vehicle( ); More Examples Object Name Name of the object we are creating here. Class Name An instance of this class is created. Argument No arguments are used here.
Declaration vs. Creation Customer  customer; customer  =  new  Customer( ); 1. The identifier  customer  is declared and space is allocated in memory. 2. A  Customer  object is created and the identifier  customer  is set to refer to it. 1 2 customer 2 : Customer customer 1
State-of-Memory vs. Program customer : Customer State-of-Memory Notation customer : Customer Program Diagram Notation
Name vs. Objects Customer  customer; customer  =  new  Customer( ); customer  =  new  Customer( ); Created with the first  new . Created with the second  new . Reference to the first Customer object is lost. customer : Customer : Customer
Sending a Message myWindow  .   setVisible  (  true  )  ; account.deposit( 200.0 ); student.setName(“john”); car1.startEngine(  ); More Examples Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Argument The argument we are passing with the message.
Program Components A Java program is composed of comments, import  statements, and class declarations.
Program Component: Comment /* 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 ); } } Comment
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.
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 today’s date, you can * use this class for stopwatch functions. */ javadoc Comments
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 ); } } Import Statement
Import Statement Syntax and Semantics <package name>  .   <class name>  ; e.g.  dorm  .   Resident; import   javax.swing.JFrame; import   java.util.*; import   com.drcaffeine.simplegui.*; More Examples Class Name The name of the class we want to import. Use asterisks to import all classes. Package Name Name of the package that contains the classes we want to use.
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
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 ); } } Method Declaration
Method Declaration Elements public  static  void   main(  String[ ] args  ){ JFrame myWindow; 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
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); } } Import Statements Class Name Comment Method Body
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:  JOptionPane  String Date SimpleDateFormat.
JOptionPane Using  showMessageDialog  of the  JOptionPane  class is a simple way to display a result of a computation to the user. JOptionPane.showMessageDialog ( null ,  “I Love Java” ) ; This dialog will appear at the center of the screen.
Displaying Multiple Lines of Text We can display multiple lines of text by separating lines with a new line marker  \n . JOptionPane.showMessageDialog ( null ,  “ one\ntwo\nthree” ) ;
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 .
String is an Object 1. The identifier  name  is declared and space is allocated in memory. 2. A  String  object is created and the identifier  name  is set to refer to it. 1 2 1 2 name String  name; name  =  new  String(“Jon Java”); : String Jon Java name
String Indexing The position, or index, of the first character is 0.
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.
Examples: substring text.substring(6,8) text.substring(0,8) text.substring(1,5) text.substring(3,3) text.substring(4,2) String text =  “Espresso” ; “ so” “ Espresso” “ spre” error   “”
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.
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
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.
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
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.
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?”
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( ); “ Fri Oct 31 10:05:18 PST 2003”
SimpleDateFormat The  SimpleDateFormat  class allows the  Date  information to be displayed with various format. Table 2.1 page 64 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”
JOptionPane for Input Using  showInputDialog  of the  JOptionPane  class is a simple way to input a string. String name; name = JOptionPane.showInputDialog ( null ,  “What is your name?” ) ; This dialog will appear at the center of the screen ready to accept an input.
Problem Statement Problem statement: Write a program that asks for the user’s first, middle, and last names and replies with their initials. Example: input:  Andrew Lloyd Weber output:  ALW
Overall Plan Identify the major tasks the program has to perform.  We need to know what to develop before we develop! Tasks: Get the user’s first, middle, and last names Extract the initials and create the monogram Output the monogram
Development Steps We will develop this program in two steps: Start with the program template and add code to get input Add code to compute and display the monogram
Step 1 Design The program specification states “get the user’s name” but doesn’t say how. We will consider “how” in the Step 1 design We will use JOptionPane for input Input Style Choice #1 Input first, middle, and last names separately Input Style Choice #2 Input the full name at once We choose Style #2 because it is easier and quicker for the user to enter the information
Step 1 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step1/Ch2Monogram.java */ import  javax.swing.*; class  Ch2Monogram  { public static void  main  ( String [ ]  args ) { String name; name = JOptionPane.showInputDialog( null ,    &quot;Enter your full name (first, middle, last):“ ) ; JOptionPane.showMessageDialog ( null , name ) ; } }
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
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)
Step 2 Design (cont’d) Given the valid input, we can compute the monogram 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”
Step 2 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step 2/Ch2MonogramStep2.java */ import  javax.swing.*; class  Ch2Monogram  { public static void main   ( String [ ]  args ) { String name, first, middle, last,  space, monogram; space =  &quot; “ ; //Input the full name name = JOptionPane.showInputDialog ( null ,    &quot;Enter your full name (first, middle, last):“   ) ;
Step 2 Code (cont’d) //Extract first, middle, and last names first = name.substring ( 0, name.indexOf ( space )) ; name = name.substring ( name.indexOf ( space ) +1,  name.length ()) ; middle = name.substring ( 0, name.indexOf ( space )) ; last = name.substring ( name.indexOf ( space ) +1,  name.length ()) ; //Compute the monogram monogram = first.substring ( 0, 1 )  +  middle.substring ( 0, 1) +  last.substring ( 0,1 ) ; //Output the result JOptionPane.showMessageDialog ( null ,  &quot;Your  monogram is &quot;  + monogram ) ; } }
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 have to try out many different types of (valid) input values.
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

More Related Content

PPTX
Generic process model
PPT
Problem solving using Computer
PDF
Collections in Java Notes
PDF
sparse matrix in data structure
PPTX
Data Structures - Lecture 3 [Arrays]
PDF
Red black tree
PPT
B tree
PPT
Generic process model
Problem solving using Computer
Collections in Java Notes
sparse matrix in data structure
Data Structures - Lecture 3 [Arrays]
Red black tree
B tree

What's hot (20)

PPTX
Doubly & Circular Linked Lists
PPTX
Program development life cycle
PPT
Compiler Construction introduction
PPTX
linked list in Data Structure, Simple and Easy Tutorial
PDF
Python exception handling
PPT
PPTX
heap Sort Algorithm
PPTX
Data Structures - Lecture 7 [Linked List]
PPTX
Graph representation
PPTX
Triggers
PPTX
Passes of Compiler.pptx
PPTX
Double Linked List (Algorithm)
PDF
Elementary data structure
PPTX
Types and roles
PDF
Data structure ppt
PPT
Structure and Enum in c#
PPTX
Recovery with concurrent transaction
PPT
Coupling and cohesion
PPTX
Process state in OS
PPTX
Normal forms
Doubly & Circular Linked Lists
Program development life cycle
Compiler Construction introduction
linked list in Data Structure, Simple and Easy Tutorial
Python exception handling
heap Sort Algorithm
Data Structures - Lecture 7 [Linked List]
Graph representation
Triggers
Passes of Compiler.pptx
Double Linked List (Algorithm)
Elementary data structure
Types and roles
Data structure ppt
Structure and Enum in c#
Recovery with concurrent transaction
Coupling and cohesion
Process state in OS
Normal forms
Ad

Viewers also liked (14)

PDF
What is Python?
PPT
Chapter2 java oop
PPT
Chapter 7 - Defining Your Own Classes - Part II
PPT
Chapter 4 - Defining Your Own Classes - Part I
PPT
Datos Numéricos parte 1
DOCX
Assignment 7
PPS
String and string buffer
PPT
Chapter1 - Introduction to Object-Oriented Programming and Software Development
PDF
X physics full notes chapter 5
PDF
Getting Started with Java (TCF 2014)
DOC
Physics numericals
PPT
Physics Numerical Problem, Metric Physics, Kinematic Problems Karachi, Federa...
PPT
Chapter 6 Work Energy Power
PDF
Variables y tipos de datos - fundamentos de la programación
What is Python?
Chapter2 java oop
Chapter 7 - Defining Your Own Classes - Part II
Chapter 4 - Defining Your Own Classes - Part I
Datos Numéricos parte 1
Assignment 7
String and string buffer
Chapter1 - Introduction to Object-Oriented Programming and Software Development
X physics full notes chapter 5
Getting Started with Java (TCF 2014)
Physics numericals
Physics Numerical Problem, Metric Physics, Kinematic Problems Karachi, Federa...
Chapter 6 Work Energy Power
Variables y tipos de datos - fundamentos de la programación
Ad

Similar to Chapter 2 - Getting Started with Java (20)

PPTX
Java Basics 1.pptx
PPTX
Introduction to JcjfjfjfkuutyuyrsdterdfbvAVA.pptx
KEY
Java Building Blocks
PDF
Lec 5 13_aug [compatibility mode]
PPTX
CAP615-Unit1.pptx
PPT
Core_java_ppt.ppt
DOCX
Unit2 java
PDF
M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)
PDF
Basic Java Programming
PPTX
Android webinar class_java_review
PPTX
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
PPTX
Multi Threading- in Java WPS Office.pptx
PDF
ITFT - Java
PPT
Java Intro
PDF
Javanotes
PPTX
Java introduction
PPTX
Java Programming
PDF
Javaprogbasics
PPTX
UNIT 1 : object oriented programming.pptx
PPTX
Mod_5 of Java 5th module notes for ktu students
Java Basics 1.pptx
Introduction to JcjfjfjfkuutyuyrsdterdfbvAVA.pptx
Java Building Blocks
Lec 5 13_aug [compatibility mode]
CAP615-Unit1.pptx
Core_java_ppt.ppt
Unit2 java
M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)
Basic Java Programming
Android webinar class_java_review
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
Multi Threading- in Java WPS Office.pptx
ITFT - Java
Java Intro
Javanotes
Java introduction
Java Programming
Javaprogbasics
UNIT 1 : object oriented programming.pptx
Mod_5 of Java 5th module notes for ktu students

More from Eduardo Bergavera (6)

PPTX
CLP Session 5 - The Christian Family
PPT
Chapter 13 - Inheritance and Polymorphism
PPT
Chapter 12 - File Input and Output
PPT
Chapter 11 - Sorting and Searching
PPT
Chapter 9 - Characters and Strings
PPT
Chapter 8 - Exceptions and Assertions Edit summary
CLP Session 5 - The Christian Family
Chapter 13 - Inheritance and Polymorphism
Chapter 12 - File Input and Output
Chapter 11 - Sorting and Searching
Chapter 9 - Characters and Strings
Chapter 8 - Exceptions and Assertions Edit summary

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Electronic commerce courselecture one. Pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Spectroscopy.pptx food analysis technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
PDF
cuic standard and advanced reporting.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Electronic commerce courselecture one. Pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectroscopy.pptx food analysis technology
The AUB Centre for AI in Media Proposal.docx
Chapter 3 Spatial Domain Image Processing.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Per capita expenditure prediction using model stacking based on satellite ima...
MIND Revenue Release Quarter 2 2025 Press Release
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.
cuic standard and advanced reporting.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Advanced methodologies resolving dimensionality complications for autism neur...

Chapter 2 - Getting Started with Java

  • 1. Chapter 2 Getting Started with Java
  • 2. Objectives After you have read and studied this chapter, you should 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 JOptionPane standard classes Develop Java programs, using the incremental development approach
  • 3. 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 .
  • 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
  • 5. Program Diagram for Ch2Sample1 setSize(300, 200) setTitle(“My First Java Program”) myWindow : JFrame Ch2Sample1 setVisible(true)
  • 6. Dependency Relationship 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 . myWindow : JFrame Ch2Sample1
  • 7. Object Declaration JFrame myWindow; Account customer; Student jan, jim, jon; Vehicle car1, car2; More Examples Object Name One object is declared here. Class Name This class must be defined before this declaration can be stated.
  • 8. Object Creation myWindow = new JFrame ( ) ; customer = new Customer( ); jon = new Student(“John Java”); car1 = new Vehicle( ); More Examples Object Name Name of the object we are creating here. Class Name An instance of this class is created. Argument No arguments are used here.
  • 9. Declaration vs. Creation Customer customer; customer = new Customer( ); 1. The identifier customer is declared and space is allocated in memory. 2. A Customer object is created and the identifier customer is set to refer to it. 1 2 customer 2 : Customer customer 1
  • 10. State-of-Memory vs. Program customer : Customer State-of-Memory Notation customer : Customer Program Diagram Notation
  • 11. Name vs. Objects Customer customer; customer = new Customer( ); customer = new Customer( ); Created with the first new . Created with the second new . Reference to the first Customer object is lost. customer : Customer : Customer
  • 12. Sending a Message myWindow . setVisible ( true ) ; account.deposit( 200.0 ); student.setName(“john”); car1.startEngine( ); More Examples Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Argument The argument we are passing with the message.
  • 13. Program Components A Java program is composed of comments, import statements, and class declarations.
  • 14. Program Component: Comment /* 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 ); } } Comment
  • 15. 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.
  • 16. 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 today’s date, you can * use this class for stopwatch functions. */ javadoc Comments
  • 17. 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 ); } } Import Statement
  • 18. Import Statement Syntax and Semantics <package name> . <class name> ; e.g. dorm . Resident; import javax.swing.JFrame; import java.util.*; import com.drcaffeine.simplegui.*; More Examples Class Name The name of the class we want to import. Use asterisks to import all classes. Package Name Name of the package that contains the classes we want to use.
  • 19. 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
  • 20. 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 ); } } Method Declaration
  • 21. Method Declaration Elements public static void main( String[ ] args ){ JFrame myWindow; 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
  • 22. 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); } } Import Statements Class Name Comment Method Body
  • 23. 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: JOptionPane String Date SimpleDateFormat.
  • 24. JOptionPane Using showMessageDialog of the JOptionPane class is a simple way to display a result of a computation to the user. JOptionPane.showMessageDialog ( null , “I Love Java” ) ; This dialog will appear at the center of the screen.
  • 25. Displaying Multiple Lines of Text We can display multiple lines of text by separating lines with a new line marker \n . JOptionPane.showMessageDialog ( null , “ one\ntwo\nthree” ) ;
  • 26. 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 .
  • 27. String is an Object 1. The identifier name is declared and space is allocated in memory. 2. A String object is created and the identifier name is set to refer to it. 1 2 1 2 name String name; name = new String(“Jon Java”); : String Jon Java name
  • 28. String Indexing The position, or index, of the first character is 0.
  • 29. 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.
  • 30. Examples: substring text.substring(6,8) text.substring(0,8) text.substring(1,5) text.substring(3,3) text.substring(4,2) String text = “Espresso” ; “ so” “ Espresso” “ spre” error “”
  • 31. 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.
  • 32. 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
  • 33. 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.
  • 34. 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
  • 35. 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.
  • 36. 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?”
  • 37. 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( ); “ Fri Oct 31 10:05:18 PST 2003”
  • 38. SimpleDateFormat The SimpleDateFormat class allows the Date information to be displayed with various format. Table 2.1 page 64 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”
  • 39. JOptionPane for Input Using showInputDialog of the JOptionPane class is a simple way to input a string. String name; name = JOptionPane.showInputDialog ( null , “What is your name?” ) ; This dialog will appear at the center of the screen ready to accept an input.
  • 40. Problem Statement Problem statement: Write a program that asks for the user’s first, middle, and last names and replies with their initials. Example: input: Andrew Lloyd Weber output: ALW
  • 41. Overall Plan Identify the major tasks the program has to perform. We need to know what to develop before we develop! Tasks: Get the user’s first, middle, and last names Extract the initials and create the monogram Output the monogram
  • 42. Development Steps We will develop this program in two steps: Start with the program template and add code to get input Add code to compute and display the monogram
  • 43. Step 1 Design The program specification states “get the user’s name” but doesn’t say how. We will consider “how” in the Step 1 design We will use JOptionPane for input Input Style Choice #1 Input first, middle, and last names separately Input Style Choice #2 Input the full name at once We choose Style #2 because it is easier and quicker for the user to enter the information
  • 44. Step 1 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step1/Ch2Monogram.java */ import javax.swing.*; class Ch2Monogram { public static void main ( String [ ] args ) { String name; name = JOptionPane.showInputDialog( null , &quot;Enter your full name (first, middle, last):“ ) ; JOptionPane.showMessageDialog ( null , name ) ; } }
  • 45. 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
  • 46. 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)
  • 47. Step 2 Design (cont’d) Given the valid input, we can compute the monogram 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”
  • 48. Step 2 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step 2/Ch2MonogramStep2.java */ import javax.swing.*; class Ch2Monogram { public static void main ( String [ ] args ) { String name, first, middle, last, space, monogram; space = &quot; “ ; //Input the full name name = JOptionPane.showInputDialog ( null , &quot;Enter your full name (first, middle, last):“ ) ;
  • 49. Step 2 Code (cont’d) //Extract first, middle, and last names first = name.substring ( 0, name.indexOf ( space )) ; name = name.substring ( name.indexOf ( space ) +1, name.length ()) ; middle = name.substring ( 0, name.indexOf ( space )) ; last = name.substring ( name.indexOf ( space ) +1, name.length ()) ; //Compute the monogram monogram = first.substring ( 0, 1 ) + middle.substring ( 0, 1) + last.substring ( 0,1 ) ; //Output the result JOptionPane.showMessageDialog ( null , &quot;Your monogram is &quot; + monogram ) ; } }
  • 50. 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 have to try out many different types of (valid) input values.
  • 51. 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