• No results found

Chapter 2

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 2"

Copied!
52
0
0

Loading.... (view fulltext now)

Full text

(1)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 2

Getting Started with Java

(2)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 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 object creation.

(3)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 2 Objectives, cont.

After you have read and studied this chapter, you should be able to

• Describe the process of creating and running Java programs.

• Use the Date, SimpleDateFormat, String, and JOptionPane classes from the standard Java packages.

• Develop Java programs using the incremental development

approach.

(4)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.1 The First Java Program

This first program displays a window on the screen.

The size of the window is 300 x 200 pixels, and the default title is My First Java Program.

The fundamental OOP concept illustrated by the program:

•An object-oriented program uses objects.

(5)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.1 The First Java Program

/*

Chapter 2 Sample Program: Displaying a Window File: Ch2Sample1.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);

} }

(6)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.1

Result of running the Ch2Sample1 program.

(7)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.2

The program diagram for the Ch2Sample1 program.

(8)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.3

The program diagram for the

Ch2Sample1 program that shows the dependency relationship.

(9)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.1 The First Java Program

To use an object in a program, first we declare and create and object.

Then we send messages to it.

(10)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.1 The First Java Program

When we declare an object, we must give it a name. A Java

identifier is a sequence of letters, digits, underscores, and dollar

signs used to name a class, object, method, etc.

The first character in a Java identifier must be a letter.

(11)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.1 The First Java Program

Uppercase and lowercase letters are distinguished.

myWindow, mywindow, MYWINDOW

No spaces are allowed in an identifier.

Java naming conventions dictate the use of an uppercase letter for the first letter of class names, and a lowercase letter for the first letter of object names.

•class Account

•object account

(12)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.1 The First Java Program

No objects are created by the

declaration. The declaration only assigns an identifier to the object.

We create an object by invoking the new operation:

<object name> = new <class name> (<arguments>);

myWindow = new JFrame ( );

(13)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.4

Distinction between object

declaration and object creation.

(14)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.5

Relationship between the state-of- memory diagram and the

program diagram notation.

(15)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.6

The state after two new commands are executed.

(16)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.1 The First Java Program

The object that receives a message must possess a corresponding

method.

The expressions “sending a

message” and “calling a method”

are synonymous.

(17)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.7

Correspondence between message sending as represented in the

program diagram and in the actual Java statement.

(18)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.8

How the beginning and ending comment markers are matched.

(19)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

Below are the program

components for the program Ch2Sample1:

•Comments

•Import Statement

•Class Declaration

•Method Declaration

(20)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

Programs contain comments in

which we state the purpose of the program, explain the meaning of code, and provide other

descriptions to help programmers use and understand the code.

A comment is any sequence of text that begins with the marker /*

and ends with the marker */.

(21)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

In Java, classes are grouped into packages, and the Java system comes with numerous packages.

To use a class from a package, we refer to the class in the program by using the following syntax:

<package name>.<class name>

This notation is called dot notation.

(22)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

Using the fully qualified name of a class can be cumbersome. Using the import statement solves this problem.

import javax.swing.*;

(23)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

A Java program is composed of one or more classes. The syntax for

declaring a class is

class <class name> {

<class member declarations>

}

A class member is either a data value or a method.

(24)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

One of the classes in the program must be designated as the main class.

If we designate a class as a main class, we must define a method

called main, because when a Java program is executed, the main

method of a main class is executed first.

(25)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

A sample method declaration and its components.

(26)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.9

A program template for simple Java applications.

(27)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.2 Program Components

/*

Chapter 2 Sample Program: Freehand Drawing File: Ch2FunTime.java

The program will allow you to draw a picture by

dragging a mouse (move the mouse while holding the left mouse button down; hold the button on Mac). To erase the picture and start over, click the right mouse button (command-click on Mac).

*/

import javabook.*;

class Ch2FunTime {

public static void main (String[ ] args) { SketchPad doodleBoard;

doodleBoard = new SketchPad( );

doodleBoard.setVisible( true );

} }

(28)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.10

The window that appears on the screen when the program starts running.

(29)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.11

The same window after a picture is drawn.

(30)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.12

The program diagram for the FunTime program.

(31)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.13

A MiniBrowser object displaying a sample web page.

(32)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.3 Edit-Compile-Run Cycle

Step One: Edit the program.

•Type in the program, using a text editor, and save the

program to a file.

•Use the name of the main class and the suffix .java for the

filename.

•This file is called a source file.

(33)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.3 Edit-Compile-Run Cycle

Step 2: Compile the source file.

•The process of compiling the

source file creates the bytecode file.

•The name of the compiler- generated bytecode file will

have the suffix .class while its prefix is the same as the source file’s.

(34)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.3 Edit-Compile-Run Cycle

A sample source file and its bytecode file.

(35)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.3 Edit-Compile-Run Cycle

Step 3: Execute the bytecode file.

•A java interpreter will go

through the bytecode file and execute the instructions in it.

•If your program is error-free, a window will appear on the

screen.

•If an error occurs while running the program, the interpreter will catch it and stop its execution.

(36)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.3 Edit-Compile-Run Cycle

The result after the interpreter executes the instructions in the bytecode file.

(37)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.4 Sample Java Standard Classes

Using existing Java classes is an important step in becoming a successful and proficient

programmer.

We will introduce four standard classes here:

•JOptionPane

•String

•Date

•SimpleDateFormat.

(38)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.4 Sample Java Standard Classes

Using the JOptionPane class is a simple way to display a result of a computation to the user.

JOptionPane.showMessageDialog(null,

“I Love Java”);

(39)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.14

A simple “message” dialog created by the showMessageDialog

method of the JOptionPane class.

(40)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.15

A dialog with multiple lines of text.

(41)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.4 Sample Java Standard Classes

The textual values passed to the showMessageDialog method are instances of the String class.

A sequence of characters separated by double quotes is String

constants.

String text;

text = “Espresso”;

JOptionPane.showMessageDialog(text.substring(2, 7));

(42)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.16

A dialog showing the substring of

“espresso” from index position 2 to 6.

(43)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.17

Individual characters in a string are numbered from 0.

(44)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.18

The effect of the substring method is shown. The original string

remains intact.

(45)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.4 Sample Java Standard Classes

Date and SimpleDateFormat

The Date class is used to represent a time instance to a millisecond.

This class is in the java.util package.

SimpleDateFormat can be used to provide an alternative format to the Date class. This class is in the java.text package.

(46)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.19

JOptionPane can also be used for input: Below is the result of

calling the showInputDialog

method of the JOptionPane class with “What is your name?” as the method’s second argument.

(47)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.5 Sample Development:

Printing the Initials

Problem statement:

Write an application that asks for the user’s first, middle, and last names and replies with their initials.

Overall plan:

•Get the user’s first, middle, and last names.

•Extract the initials to form the monogram.

•Output the monogram.

(48)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.20

The program diagram for Ch2Monogram.

(49)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.5 Sample Development:

Printing the Initials

/*

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);

} }

(50)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.5 Sample Development:

Printing the Initials

/*

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):");

(51)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

2.5 Sample Development:

Printing the Initials

//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);

} }

(52)

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 2.21

Apply the two sequences of

indexOf and substring methods to extract three substrings from a given string.

References

Related documents

Java class in this output statement example below displays all such a string with java programs output string examples pdf or a string objects in java.. JAVA for Beginners Search

Since a servlet is a regular Java class, you can use the full power of the Java language to implement the request processing, using standard Java development and

septempunctata adults collected from the field were not significantly different from either adults from historical collec- tions or adults reared in the laboratory without prey

Containing Schema CommonTypesxsd Documentation Date Time for type enforcing the format ddmmyyyy HHMM.. Java SimpleDateFormat pattern for W3C XML dates with

J2SE: Java 2 standard edition J2EE: Java 2 enterprise edition J2ME: Java 2 micro edition... Definition of J2SE, J2EE

Polymorphism. Introduction to Java: History of Java, Java features and advantages, creating classes with Java, Concept of Constructors, Using JDK, Java application and

Some notable core packages include: java.lang, which contains fundamental classes needed by the Java language itself; java.awt, which contains classes of the Java Abstract

We are getting -1 back because the indexOf method invokes the equals method for the BaseType object to determine which item in the arraylist matches the target. However, we