Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to OOP with Java, C. Thomas Wu Getting Started with Java

Similar presentations


Presentation on theme: "Intro to OOP with Java, C. Thomas Wu Getting Started with Java"— Presentation transcript:

1 Intro to OOP with Java, C. Thomas Wu Getting Started with Java
Chapter 2 Getting Started with Java Animated Version ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

2 Intro to OOP with Java, C. Thomas Wu
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 McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

3 Intro to OOP with Java, C. Thomas Wu
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. It’s kind of obvious, but the most fundamental important concept in OOP is the use of objects in a program. We will illustrate this key concept in the first sample program. The program, when executed, will display a window on the screen. The text displayed in the window’s title bar will be My First Java Program. The size of the window is set to 300 pixels wide and 200 pixels high. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

4 Intro to OOP with Java, C. Thomas Wu
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 Based on what you learned about objects in the previous lessons and the description of the program in previous slide, can you make some sense from this program code? The three key tasks shown in the program are Declaring a name we use to refer to an object Create the actual object which the declared name will refer to Use this object by sending messages to it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

5 Program Diagram for Ch2Sample1
Intro to OOP with Java, C. Thomas Wu Program Diagram for Ch2Sample1 Ch2Sample1 setSize(300, 200) myWindow : JFrame setTitle(“My First Java Program”) setVisible(true) This program diagram depicts the program structure graphically. From this diagram, we can tell that there is one class and one object, an instance of JFrame, in this program, and that three messages are sent from Ch2Sample1 to myWindow. When many messages are sent from one class or an object to another class or object, then drawing all messages makes the diagram too cluttered. To avoid cluttering, we show only dependency relationships (see next slide). ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

6 Dependency Relationship
Intro to OOP with Java, C. Thomas Wu Dependency Relationship Ch2Sample1 myWindow : JFrame Here’s an example of dependency relationship. To get a big picture, we are not that interested in seeing all the messages sent from one sender to a receiver. Instead, we would like to see who depends on whom. In this diagram, we see that Ch2Sample1 sends messages to myWindow. In other words, Ch2Sample1 depends on the services provided by myWindow to perform its tasks. 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. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

7 Intro to OOP with Java, C. Thomas Wu
Object Declaration Class Name This class must be defined before this declaration can be stated. Object Name One object is declared here. JFrame myWindow; More Examples To use an object in a program, we first declare and create an object, and then we send messages to it. The first step in using an object is to declare it. An object declaration designates the name of an object and the class to which the object belongs to. In this declaration, we are declaring the name myWindow, which we will use to refer to a JFrame object. Any valid identifier that is not reserved for other uses can be used as an object name. An identifier is a sequence of letters, digits, and the dollar sign with the first one being a letter. We use an identifier to name a class, object, method, and others. No spaces are allowed in an identifier. Remember that upper- and lowercase letters are distinguished in Java. Account customer; Student jan, jim, jon; Vehicle car1, car2; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

8 Intro to OOP with Java, C. Thomas Wu
Object Creation 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. myWindow = new JFrame ( ) ; More Examples An object declaration simply declares the name (identifier), which we use to refer to an object. The declaration does not create an object. To create the actual object, we need to invoke the new operation. Make sure you understand the distinction between object declaration and object creation. customer = new Customer( ); jon = new Student(“John Java”); car1 = new Vehicle( ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

9 Declaration vs. Creation
Intro to OOP with Java, C. Thomas Wu Declaration vs. Creation 1 Customer customer; customer = new Customer( ); Customer customer; 2 customer = new Customer( ); 1. The identifier customer is declared and space is allocated in memory. customer 1 : Customer 2 This shows the distinction between object declaration and creation by showing the effect of executing the two statements in memory allocation. Notice that the memory space for a Customer object does not happen until the correct new command is executed. 2. A Customer object is created and the identifier customer is set to refer to it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

10 State-of-Memory vs. Program
Intro to OOP with Java, C. Thomas Wu State-of-Memory vs. Program customer : Customer State-of-Memory Notation customer : Customer Program Diagram Notation This shows two different dagrams showing the same information. Namely, there’s a Customer object and the name we’re using to refer to it is customer. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

11 Intro to OOP with Java, C. Thomas Wu
Name vs. Objects Customer customer; customer = new Customer( ); Customer customer; customer = new Customer( ); customer = new Customer( ); customer Is this code fragment valid? Yes, the name and the object itself are two different things. The same name can refer to different objects at different times while the program is running. This example shows the same name pointing to two different objects (at different times, of course). Since there is no reference to the first Customer object when the second new statement, it will eventually be erased and returned to the system. Remember that when an object is created, a certain amount of memory space is allocated for storing this object. If this allocated but unused space is not returned to the system for other uses, the space gets wasted. This returning of space to the system is called deallocation, and the mechanism to deallocate unused space is called garbage collection. Created with the first new. : Customer : Customer Created with the second new. Reference to the first Customer object is lost. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

12 Intro to OOP with Java, C. Thomas Wu
Sending a Message 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. myWindow setVisible ( true ) ; More Examples This is the Java syntax for seding a message to an object or a class. In this example, we are sending the setVisible method to myWindow with an argument true, so the window indeed becomes visible. If we want to hide it, then we pass the argument false. The name of the message we send to an object or a class must be the same as the method’s name, so we use the phrase “calling an object’s method” and “sending a message to an object” interchangeably. account.deposit( ); student.setName(“john”); car1.startEngine( ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

13 Intro to OOP with Java, C. Thomas Wu
Execution Flow Program Code State-of-Memory Diagram myWindow JFrame myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle (“My First Java Program”); myWindow.setVisible(true); : JFrame width height title visible Jframe myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); 300 myWindow.setTitle (“My First Java Program”); 200 Let’s look at the effect of executing these statements to a JFrame object. When we call an object’s method, the object will carry a task, change its state, or both. The effect of the setSize method is changing the value of width and height. The effect of the setTitle method is changing the title string to the passed argument. And the effect of setVisible is the changing the value of visible to true, and as a result, the appearance of the window on the screen. myWindow.setVisible(true); My First Java … true The diagram shows only four of the many data members of a JFrame object. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

14 Intro to OOP with Java, C. Thomas Wu
Program Components A Java program is composed of comments, import statements, and class declarations. Three key elements are comments, import statements, and class declarations. Strictly speaking, you can write a Java program that does not include comments or import statements, but such program is either very trivial or not well designed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

15 Program Component: Comment
Intro to OOP with Java, C. Thomas Wu Program Component: Comment 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); } A comment is any sequence of text that begins with the marker /* and terminates with another marker */. Although not required to run the program, comments are indispensable in writing easy-to-understand code. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

16 Matching Comment Markers
Intro to OOP with Java, C. Thomas Wu 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. The beginning and ending markers are matched in pairs; that is, every beginning marker must have a matching ending marker. A beginning marker is matched with the next ending marker that appears. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

17 Three Types of Comments
Intro to OOP with Java, C. Thomas Wu 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 The sample comments shown in previous slides are called multiline comments. There are two additional types of comments used in Java. The second type of comment is called a single-line comment. A single-line comment starts with double slashes //. Any text between the double-slash marker and the end of a line is a comment. The third type of comment is called a javadoc comment. It is a specialized comment that can appear before the class declaration and other program elements yet to be described in the book. Javadoc comments begin with the /** marker and end with the */ marker. We won’t worry about javadoc comments now. At this point, you are only required just to be aware of it. If you are curious about javadoc comments, you can find information on javadoc and samle Web documentation pages that are generated from javadoc comments at techdocs/api/ /** * 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 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

18 Intro to OOP with Java, C. Thomas Wu
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 The import statement allows the program to use classes and their instances defined in the designated package. We develop object-oriented programs by using predefined classes whenever possible and defining our own classes when no suitable predefined classes are available. In Java, classes are grouped into packages. The Java compiler comes with over 2000 standard classes organized into several hundred packages. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

19 Import Statement Syntax and Semantics
Intro to OOP with Java, C. Thomas Wu Import Statement Syntax and Semantics Package Name Name of the package that contains the classes we want to use. Class Name The name of the class we want to import. Use asterisks to import all classes. <package name> <class name> ; e.g dorm Resident; More Examples To use the Resident class in the dorm package, we write dorm.Resident; which we read as “dorm dot Resident.” This notation is called dot notation. Notice that the import statement is terminated by a semicolon. A package can include subpackages, forming a hierarchy of packages. The notation javax.swing.JFrame means the JFrame class is located in the package swing, which itself is contained in the top-level javax package. If you need to import more than one class from the same package, then instead of using an import statement for every class, you can import them all using asterisk notation: <package name> . * ; For example, when we write import java.util.*; then we are importing all class from the java.util package. import javax.swing.JFrame; import java.util.*; import com.drcaffeine.simplegui.*; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

20 Intro to OOP with Java, C. Thomas Wu
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 A Java program is composed of one or more classes, some of them are predefined classes, while others are defined by ourselves. In this sample program, there are two classes—JFrame and Ch2Sample1. The JFrame class is from the java.util package and the Ch2Sample1 class is the class we define ourselves. The word class is a reserved word used to mark the beginning of a class declaration. We can use any valid identifier to name the class. One of the classes in a program must be designated as the main class. The main class of the sample program is Ch2Sample1. For now, we only learn how to define the main class. Later in the course, we’ll learn how to define other non-main classes. The main class must include a method called main, because when a Java program is executed, the main method of a main class is executed first. In other words, it is the entry point of program execution. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

21 Intro to OOP with Java, C. Thomas Wu
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 Here’s the main method of the class. We can include any valid statements in the main method, but the structure is fixed and cannot be changed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

22 Method Declaration Elements
Intro to OOP with Java, C. Thomas Wu Method Declaration Elements Modifier Return Type Method Name Parameter 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 The syntax for method declaration is <modifiers> <return type> <method name> ( <parameters> ) { <method body> } where <modifiers> is a sequence of terms designating different kinds of methods, <return type> is the type of data value returned by a method, <method name> is the name of a method, <parameters> is a sequence of values passed to a method, and <method body> is a sequence of statements. We will explain the meanings of modifies, return types, and parameters in detail gradually as we progress through the course. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

23 Template for Simple Java Programs
Intro to OOP with Java, C. Thomas Wu Template for Simple Java Programs /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample { 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 Import Statements Class Name Method Body Comment: Use a comment to describe the program Import Statements: Include a sequence of import statements. Most of the early sample applications require only import javabook.*; Class Name: Give a descriptive name to the main class. Method Body: Include a sequence of instructions. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

24 Why Use Standard Classes
Intro to OOP with Java, C. Thomas Wu 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. Java comes with over 2000 standard classes. Developing complex Java programs involves defining our own classes and using existing standard classes. Whenever possible, we should use existing classes and avoid reinventing the wheel. Also, being able to use existing classes is a necessary foundation for us to learn how define our own classes. In this lesson, we will introduce four standard classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

25 Intro to OOP with Java, C. Thomas Wu
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”); JOptionPane provides a convenient method for displaying shot messages. In this example, we are displaying a message I Love Java. The dialog with the specified message appears on the center of the screen. The argument null indicates that there is no containing frame. This indication results in a dialog appearing at the center of the screen. If we wish to position a dialog at the center of another window, then we pass a JFrame object instead of null as in JFrame win = new JFrame( ); win.setSize(500, 300); win.setVisible(true); JOptionPane.showMessageDialog(win, “I’m at the center of another window”); This dialog will appear at the center of the screen. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

26 Displaying Multiple Lines of Text
Intro to OOP with Java, C. Thomas Wu 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”); We can only pass a single line text to the showMessageDialog method, but it is possible to display it as multiple lines of text. The key is to embed a nonprintable new line marker \n. Notice that in the actual display, the new line markers are not shown. This new line and other nonprintable markers are called control characters because they are not for display but for controlling the test is displayed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

27 Intro to OOP with Java, C. Thomas Wu
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 manipulation is so fundamental to computer programs, it is critical to master the String class. We begin our study of the String class with its three frequently used methods and one string operation called concatenation. This operation puts two strings together to form a new string. We will learn more String methods as we progress through the course. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

28 Intro to OOP with Java, C. Thomas Wu
String is an Object 1 String name; name = new String(“Jon Java”); String name; 2 name = new String(“Jon Java”); 1. The identifier name is declared and space is allocated in memory. name 1 2 : String Jon Java It is very important to remember that a string is full-fledged object in Java. As such, we use the new operator to create an instance as this example shows. Remember the distinction between the name of an object and the object itself. For the String class only, we can designate a new string without using new as in String name = “Ms. Latte”; 2. A String object is created and the identifier name is set to refer to it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

29 Intro to OOP with Java, C. Thomas Wu
String Indexing A string is viewed as an indexed sequence of characters with the first character at index position 0. This fact will be the key in understanding how the three String methods work. The position, or index, of the first character is 0. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

30 Definition: substring
Intro to OOP with Java, C. Thomas Wu 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. Let’s study how the substring method works. You pass two arguments i and j to this method. The first argument is the beginning index and the second argument is the ending index. The method returns a new string that is a substring of str extracting characters from position i to j-1. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

31 Intro to OOP with Java, C. Thomas Wu
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” Here are some examples of the substring method. Notice the last example is an error. The first argument must be the same or smaller than the second parameter. Also, notice that if the first and the second arguments are the same, then the new string created is an empty string. “” error ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

32 Intro to OOP with Java, C. Thomas Wu
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. The length method is very straightforward. It returns the number of characters in the string. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

33 Intro to OOP with Java, C. Thomas Wu
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 Here are some examples of the length method. Notice asking the length of an empty string is not an error. The value returned is 0. If the name does not refer to a real String object, however, it is an error, of course. For example, String str; str.length( ); will result in an error (specifically NullPointerException). 1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

34 Intro to OOP with Java, C. Thomas Wu
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. The indexOf method returns the position of the first character of a search string (substring) in a given string. If there are more than one occurrence of the same substing in a string, the position of the first occurrence is returned. If no match is found, then –1 is returned. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

35 Intro to OOP with Java, C. Thomas Wu
Examples: indexOf String str; str = “I Love Java and Java loves me.” ; 3 7 21 str.indexOf( “J” ) str2.indexOf( “love” ) str3. indexOf( “ove” ) str4. indexOf( “Me” ) 7 21 Here are some examples of the indexOf method. When there are more than one match, then the position of the first match is returned as the first example shows. If there’s no match, then –1 is returned. The search is case-sensitive so the last example returns –1. 3 -1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

36 Definition: concatenation
Intro to OOP with Java, C. Thomas Wu 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. The concatenation operator forms a new string by putting two strings together. The original two strings remain the same. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

37 Examples: concatenation
Intro to OOP with Java, C. Thomas Wu Examples: concatenation String str1, str2; str1 = “Jon” ; str2 = “Java” ; str1 + str2 str1 + “ “ + str2 str2 + “, “ + str1 “Are you “ + str1 + “?” “JonJava” “Jon Java” Here are some examples of the concatenation operator. “Java, Jon” “Are you Jon?” ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

38 Intro to OOP with Java, C. Thomas Wu
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( ); Date manipulation is a very common task in computer programs. A Date object actually keeps track of time also. We will learn more about this class later in the course. “Fri Oct 31 10:05:18 PST 2003” ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

39 Intro to OOP with Java, C. Thomas Wu
SimpleDateFormat The SimpleDateFormat class allows the Date information to be displayed with various format. Table 2.1 page 68 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); We use a SimpleDateFormat to display the Date information in the format we like. Follow this example and you can experiment with the different formatting options listed in Table 2.1 on page 68 of the textbook. “10/31/03” “October 31, 2003” ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

40 Intro to OOP with Java, C. Thomas Wu
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?”); The showInputDialog method allows a program to accept a string data from the enduser. The method returns the data entered by the enduser as a String object, so we can assign it to a variable. This dialog will appear at the center of the screen ready to accept an input. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

41 Intro to OOP with Java, C. Thomas Wu
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 In this beginning course, we concentrate on three stages of the software lifecycle: design, coding, and testing. We view the problem statement as the requirement specification produced during the analysis phase of the lifecycle. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

42 Intro to OOP with Java, C. Thomas Wu
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 It may not be obvious for a simple program like this one, but identifying and recording the program tasks are indispensable because the development steps are based on the identified tasks. If the tasks are not identified, we can’t develop them. Notice this program follows the universal pattern of computer programs, namely, the pattern of input, computation, and output. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

43 Intro to OOP with Java, C. Thomas Wu
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 In Step 1, we will use the program template for simple Java programs introduced in Lesson 2-2 as the starting point. We design and code the input routine. Once the Step 1 code is tested, we move on to Step 2 to complete the program by adding the code compute and display the monogram. When we finish the testing of the Step 2 code, we are done with the development. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

44 Intro to OOP with Java, C. Thomas Wu
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 The specification tells “what” must be done (get the user’s input), but not “how” to do it. In the design stage, we will determine the “how.” First, we will use JOptionPane for input. This is no brainer because it is the only way we know how to input data at this point in the course. Second, how exactly should we input the user’s name? We can input it in three separate pieces—first, middle, and last names—by calling the showInputDialog method three times. Or, we can input the full name at once by calling the showInputDialog method once. We prefer the second style because it is much quicker for the user to enter his/her full name at once. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

45 Intro to OOP with Java, C. Thomas Wu
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, "Enter your full name (first, middle, last):“); JOptionPane.showMessageDialog(null, name); } Notice the use of showMessageDialog to output the input data. This displaying of input data is called echo printing. This is a technique we use to verify the correctness of input data. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

46 Intro to OOP with Java, C. Thomas Wu
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 For the Step 1 test, we run the program and confirm the input routine is working correctly. Even for a simple program like this, incremental testing is important. By confirming the correctness of Step 1 Code, we can focus on the computation task in Step 2. Had we omitted this test and moved to Step 2, we would not be able to tell whether the input routine or the computation is not functioning correctly when there’s an error. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

47 Intro to OOP with Java, C. Thomas Wu
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) Because our programming skills are still limited, we need to make some assumptions on input so we can carry out the required task. To simplify the processing task, we will impose these two restrictions on the input values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

48 Intro to OOP with Java, C. Thomas Wu
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” Given the input string that follows the designated format, we can use the sequence of the substring method to extract first, middle, and last names. Once the the name is separated into three pieces, we can then pull out and concatenate their first characters. We will be using all three string methods and string concatenation operator to achieve the task. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

49 Intro to OOP with Java, C. Thomas Wu
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 = " “; //Input the full name name = JOptionPane.showInputDialog(null, "Enter your full name (first, middle, last):“ ); Notice the use of variable space to make the code more readable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

50 Intro to OOP with Java, C. Thomas Wu
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, "Your monogram is " + monogram); } Make sure you follow the logic of breaking one input string to three substrings (first, middle, last) by applying a sequence of substring method in conjunction with indexOf and length methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

51 Intro to OOP with Java, C. Thomas Wu
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. We run the final test by executing the program numerous times and trying out many different input values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

52 Intro to OOP with Java, C. Thomas Wu
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 Programmers must be always diligent in actively looking for features that may be missing or features that can use improvements. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.


Download ppt "Intro to OOP with Java, C. Thomas Wu Getting Started with Java"

Similar presentations


Ads by Google