Download presentation
Presentation is loading. Please wait.
1
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 1 Chapter 2 Getting Started with Java Structure of a Java program Declaring and creating objects Program development process Standard Java classes
2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 2 Program Development Process Design the program Use a text editor (vim) to create files containing Java code that define classes vim MyClass.java Compile the java code to create a class file javac MyClass.java Run the program java MyClass Create the documentation javadoc MyClass.java
3
Structure of a Java Program A Java program (application) consists of one or more classes –Each class is defined in a separate file –One class is the main class A class consists of –Data –Methods The main class has a method named main –Other classes (sometimes)
4
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 4 The Simplest Program /** The simplest class */ public class Hello { public static void main(String[ ] args) { System.out.println( "Hello, World"); } The class has a single method, the main method The main method has a single statement
5
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 5 An object-oriented program uses objects. The Hello class uses two kinds of objects –System.out System is a class that provides access to standard input and output facilities out is an object in the System class (class data). It belongs to the PrintStream class –"Hello, World!" Double quotes are used to automatically create a String object.
6
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 6 Template for Simple Java Programs import java.package.ClassName; /** Describe the class here */ public class MyClass { // Declare attributes here /** Describe the method here */ public static void main(String[ ] args) { /* main method is used to start the program declare and create objects then call the methods of those objects */ } Import Statements Class Name javadoc Comment javadoc Comment main Method
7
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 7 Program Components A Java program is composed of one or more classes –Each class corresponds to a file Each class contains –import statements –comments - ignored by the compiler –class declaration
8
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 8 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 comme nt /** * 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
9
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 9 Import Statement Syntax and Semantics We often use classes that already exist in our programs We use an import statement to tell the compiler how to find a class we want to use in our program. ; e.g. dorm. Resident; Class Name The name of the class we want to import. Use asterisks to import all classes. 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. Package Name Name of the package that contains the classes we want to use.
10
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 10 Program that creates and uses an object import javax.swing.JFrame; /** Chapter 2 Sample Program: Displaying a Window */ public class Ch2Sample1 { public static void main(String[ ] args) { JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); }
11
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 11 Objects Used The fundamental OOP concept illustrated by the program: An object-oriented program uses objects. This program displays a window on the screen. –the window is an object The size of the window is set to 300 pixels wide and 200 pixels high. Its title is set to My First Java Program. –the title is a String, another object
12
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 12 Program Diagram for Ch2Sample1 myWindow : JFrame Ch2Sample1 setSize(300, 200) setTitle(“My First Java Program”) setVisible(true) Ch2Sample1 is not an object In the main method –declare and create object myWindow –send messages to myWindow
13
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 13 Object Declaration Every object we use in a program needs a name Use a declaration statement to tell the compiler –what names we are going to use for the object –what type of object the name will refer to JFrame myWindow; Object Name One object is declared here. Object Name One object is declared here. Class Name This class must be defined before this declaration can be stated. Class Name This class must be defined before this declaration can be stated.
14
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 14 Names in Java We need names for classes, objects and methods in a Java program Rules for names –Start with a letter or underscore (_) –remaining characters can be letters, digits, underscore –case sensitive Naming conventions –class names start with a capital letter –method and object names start with a lower case letter –constants are all capitals
15
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 15 Object Creation Instantiation is the process of creating an object –use the new operator in front of a constructor to create an object If we want to use the object more than once, we have to give it a name –use the assignment operator (=) to assign a name myWindow = new JFrame ( ) ; Object Name Name of the object we are creating here. Object Name Name of the object we are creating here. Class Name An instance of this class is created. Class Name An instance of this class is created. Argument No arguments are used here. Argument No arguments are used here.
16
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 16 Declaration and 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
17
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 17 Name vs. Objects Customer customer; customer = new Customer( ); customer2 = customer; customer : Customer Created with the first new. Created with the second new. Reference to the first Customer object is lost. customer2
18
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 18 Sending a Message myWindow. setVisible ( true ) ; Object Name Name of the object to which we are 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. Method Name The name of the message we are sending. Argument The argument we are passing with the message. Argument The argument we are passing with the message. We send a message to an object by calling one of its methods When we send a message, we need to specify the object it should be sent to
19
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 19 Method Definition 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 Return Type Method Name Parameter
20
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 20 Standard Classes Java comes with a large collection of existing classes –Don’t reinvent the wheel. When there are existing classes that satisfy our needs, use them. –Before we can learn how to define our own classes, we need to learn how to use existing classes We will introduce three standard classes here: –String –Date –SimpleDateFormat.
21
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 21 String The String class is used to represent text There are close to 50 methods defined in the String class. For example. –length - tells how many characters a String has –indexOf - gives the position of a particular sequence of characters in a String –substring - get another String containing some part of the original string Java provides a special operation called concatenation to combine Strings –We can concatenate two strings using +
22
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 22 Literal Strings A sequence of characters separated by double quotes is a String constant, also called a String literal. Putting double-quoted text into your program tells the compiler to create a String object for you. –The literal string does not have a name unless you give it one. String myString = "this is my string"; –If you want to use the same constant string in several places in your program, you can either give it a name or just use the double- quoted form wherever you need it.
23
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 23 name Naming a Literal String 1. The identifier name is declared and space is allocated in memory. 2. The identifier name is set to refer to the literal String. 1 2 1 String name; name = “Jon Java”; : String Jon Java name 2
24
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 24 name A 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 String name; name = new String(“Jon Java”); : String Jon Java name 2 : String Jon Java
25
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 25 String method: length Assume str is a properly initialized String object. str.length( ) will return the number of characters in str. If str is “programming”, then str.length( ) will return 11. –all characters, including spaces, are counted in the length
26
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 26 String Indexing The position, or index, of the first character is 0.
27
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 27 String Method: indexOf Assume str and substr are properly initialized String objects. 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.
28
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 28 String Method: substring Assume str is a properly initialized String object. str.substring( i, j ) will return a new string by extracting characters of str from position i through position j-1 where 0 i str.length, 0 j str.length, 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.
29
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 29 String Method: concatenation Assume str1 and str2 are properly initialized String objects. 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 + is an operator and not a method of the String class. The strings str1 and str2 remain the same.
30
Example Read a name consisting of –first middle last Print it back out as –last, middle first What happens if there are too few names? What happens if there are too many names
31
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 31 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 the current date (based on the computers settings) 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”
32
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 2 - 32 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”
33
SimpleDateFormat Formatting Symbols yyearyyyy -> 2008 MmonthMM->10, MMM-> Sep, MMMM->September ddaydd->10 hhour(1-12) hh->09 aam/pma-> AM mminutesmm->35 ssecondsss->54 Eday of week E->Thur, EEEE->Thursday
34
Example Given a date, determine the day of the week. How could we read a date and get month, day and year from it?
35
Standard Input The technique of using System.in to input data is called standard input. –We can only input a single byte using System.in directly. To input data in a more useful format, we use the Scanner class (from Java 5.0). import java.util.Scanner; … Scanner scanner; scanner = new Scanner( System.in); String word = scanner.next (); String line = scanner.nextLine ();
36
The GregorianCalendar Class Use a GregorianCalendar object to manipulate calendar information GregorianCalendar today, independenceDay; today = new GregorianCalendar(); independenceDay = new GregorianCalendar(1776, 6, 4); //month 6 means July; 0 means January
37
Retrieving Calendar Information This table shows the class constants for retrieving different pieces of calendar information from Date.
38
Sample Calendar Retrieval GregorianCalendar cal = new GregorianCalendar(); //Assume today is Nov 9, 2003 System.out.print(“Today is ” + (cal.get(Calendar.MONTH)+1) + “/” + cal.get(Calendar.DATE) + “/” + cal.get(Calendar.YEAR)); Today is 11/9/2003 Output
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.