0% found this document useful (0 votes)
12 views

JavaHTP6e 02

The document describes a simple Java program that prints the text "Welcome to Java Programming!" to illustrate basic Java concepts like comments, classes, and methods. It then shows how to modify the program to print the same text using multiple print statements instead of a single println statement.

Uploaded by

M Baba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

JavaHTP6e 02

The document describes a simple Java program that prints the text "Welcome to Java Programming!" to illustrate basic Java concepts like comments, classes, and methods. It then shows how to modify the program to print the same text using multiple print statements instead of a single println statement.

Uploaded by

M Baba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

1

2
Introduction
to Java Applications

© 2005 Pearson Education, Inc. All rights reserved.


2

2.2 First Program in Java: Printing a Line


of Text
• Application
– Executes when you use the java command to launch the
Java Virtual Machine (JVM)
• Sample program
– Displays a line of text
– Illustrates several important Java language features

© 2005 Pearson Education, Inc. All rights reserved.


1 // Fig. 2.1: Welcome1.java 3

2 // Text-printing program.
Outline
3

4 public class Welcome1


Welcome1.java
5 {

6 // main method begins execution of Java application

7 public static void main( String args[] )

8 {

9 System.out.println( "Welcome to Java Programming!" );

10

11 } // end method main

12

13 } // end class Welcome1

Welcome to Java Programming!

© 2005 Pearson Education,


Inc. All rights reserved.
4

2.2 First Program in Java: Printing a Line


of Text (Cont.)
1 // Fig. 2.1: Welcome1.java

– Comments start with: //


• Comments ignored during program execution
• Document and describe code
• Provides code readability
– Traditional comments: /* ... */
/* This is a traditional
comment. It can be
split over many lines */
2 // Text-printing program.

– Another line of comments


– Note: line numbers not part of program, added for reference

© 2005 Pearson Education, Inc. All rights reserved.


5

2.2 First Program in Java: Printing a Line


of Text (Cont.)
3

– Blank line
• Makes program more readable
• Blank lines, spaces, and tabs are white-space characters
– Ignored by compiler

4 public class Welcome1

– Begins class declaration for class Welcome1


• Every Java program has at least one user-defined class
• Keyword: words reserved for use by Java
– class keyword followed by class name
• Naming classes: capitalize every word
– SampleClassName

© 2005 Pearson Education, Inc. All rights reserved.


6

2.2 First Program in Java: Printing a Line


of Text (Cont.)
4 public class Welcome1

– Java identifier
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, $value, _value, button7
– 7button is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different
– In chapters 2 to 7, use public class
• Certain details not important now
• Mimic certain features, discussions later

© 2005 Pearson Education, Inc. All rights reserved.


7

2.2 First Program in Java: Printing a Line


of Text (Cont.)
4 public class Welcome1

– Saving files
• File name must be class name with .java extension
• Welcome1.java

5 {

– Left brace {
• Begins body of every class
• Right brace ends declarations (line 13)

© 2005 Pearson Education, Inc. All rights reserved.


8

2.2 First Program in Java: Printing a Line


of Text (Cont.)
7 public static void main( String args[] )

– Part of every Java application


• Applications begin executing at main
– Parentheses indicate main is a method (Ch. 3 and 6)
– Java applications contain one or more methods
• Exactly one method must be called main
– Methods can perform tasks and return information
• void means main returns no information
• For now, mimic main's first line

8 {

– Left brace begins body of method declaration


• Ended by right brace } (line 11)

© 2005 Pearson Education, Inc. All rights reserved.


9

Good Programming Practice 2.7

Indent the entire body of each method


declaration one “level” of indentation between
the left brace, {, and the right brace, }, that
define the body of the method. This format
makes the structure of the method stand out
and makes the method declaration easier to
read.

© 2005 Pearson Education, Inc. All rights reserved.


10

2.2 First Program in Java: Printing a Line


of Text (Cont.)
9 System.out.println( "Welcome to Java Programming!" );

– Instructs computer to perform an action


• Prints string of characters
– String - series characters inside double quotes
• White-spaces in strings are not ignored by compiler
– System.out
• Standard output object
• Print to command window (i.e., MS-DOS prompt)
– Method System.out.println
• Displays line of text
– This line known as a statement
• Statements must end with semicolon ;

© 2005 Pearson Education, Inc. All rights reserved.


11

2.2 First Program in Java: Printing a Line


of Text (Cont.)
11 } // end method main

– Ends method declaration

13 } // end class Welcome1

– Ends class declaration


– Can add comments to keep track of ending braces

© 2005 Pearson Education, Inc. All rights reserved.


12

2.2 First Program in Java: Printing a Line


of Text (Cont.)
• Compiling a program
– Open a command prompt window, go to directory where
program is stored
– Type javac Welcome1.java
– If no syntax errors, Welcome1.class created
• Has bytecodes that represent application
• Bytecodes passed to JVM

© 2005 Pearson Education, Inc. All rights reserved.


13

2.2 First Program in Java: Printing a Line


of Text (Cont.)
• Executing a program
– Type java Welcome1
• Launches JVM
• JVM loads .class file for class Welcome1
• .class extension omitted from command
• JVM calls method main

© 2005 Pearson Education, Inc. All rights reserved.


14

2.3 Modifying Our First Java Program

• Modify example in Fig. 2.1 to print same contents


using different code

© 2005 Pearson Education, Inc. All rights reserved.


15

2.3 Modifying Our First Java Program


(Cont.)
• Modifying programs
– Welcome2.java (Fig. 2.3) produces same output as
Welcome1.java (Fig. 2.1)
– Using different code
9 System.out.print( "Welcome to " );
10 System.out.println( "Java Programming!" );

– Line 9 displays “Welcome to ” with cursor remaining on


printed line
– Line 10 displays “Java Programming! ” on same line with
cursor on next line

© 2005 Pearson Education, Inc. All rights reserved.


1 // Fig. 2.3: Welcome2.java 16
Outline
2 // Printing a line of text with multiple statements.

4 public class Welcome2 Welcome2.java

5 { 1. Comments

6 // main method begins execution of Java application 2. Blank line

7 public static void main( String args[] ) 3. Begin class


Welcome2
8 {
System.out.print3.1 keeps the cursor
Method mainon
9 System.out.print( "Welcome to " ); the same line, so System.out.println
continues on the same line.
4. Method
10 System.out.println( "Java Programming!" ); System.out.print

11 4.1 Method
System.out.print
12 } // end method main ln

13 5. end main,
Welcome2
14 } // end class Welcome2
Program Output

Welcome to Java Programming!

© 2005 Pearson Education,


Inc. All rights reserved.
17

2.3 Modifying Our First Java Program


(Cont.)
• Escape characters
– Backslash ( \ )
– Indicates special characters be output
• Newline characters (\n)
– Interpreted as “special characters” by methods
System.out.print and System.out.println
– Indicates cursor should be at the beginning of the next line
– Welcome3.java (Fig. 2.4)
9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

– Line breaks at \n

© 2005 Pearson Education, Inc. All rights reserved.


1 // Fig. 2.4: Welcome3.java 18

2 // Printing multiple lines of text with a single statement.


Outline
3

4 public class Welcome3


Welcome3.java
5 {
1. main
6 // main method begins execution of Java application

7 public static void main( String args[] ) 2.


System.out.println
8 { (uses \n for new
line)
9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

10

11 } // end method main

12

13 } // end class Welcome3


Program Output
Welcome
to
Java
Programming!

Notice how a new line is output for each \n


escape sequence.

© 2005 Pearson Education,


Inc. All rights reserved.
19

2.4 Displaying Text with printf

•System.out.printf
– New feature of J2SE 5.0
– Displays formatted data
9 System.out.printf( "%s\n%s\n",
10 "Welcome to", "Java Programming!" );

– Format string
• Fixed text
• Format specifier – placeholder for a value
– Format specifier %s – placeholder for a string

© 2005 Pearson Education, Inc. All rights reserved.


1 // Fig. 2.6: Welcome4.java 20

2 // Printing multiple lines in a dialog box.


Outline
3

4 public class Welcome4


Welcome4.java
5 {

6 // main method begins execution of Java application

7 public static void main( String args[] ) main

8 { printf
9 System.out.printf( "%s\n%s\n",
System.out.printf
displays formatted data.
10 "Welcome to", "Java Programming!" );

11

12 } // end method main

13

14 } // end class Welcome4

Welcome to
Java Programming! Program output

© 2005 Pearson Education,


Inc. All rights reserved.
21

2.5 Another Java Application: Adding


Integers
• Upcoming program
– Use Scanner to read two integers from user
– Use printf to display sum of the two values
– Use packages

© 2005 Pearson Education, Inc. All rights reserved.


1 // Fig. 2.7: Addition.java 22
2 // Addition program that displays the sum of two numbers. Outline
3 import java.util.Scanner; // program uses class Scanner
4 import declaration imports class
5 public class Addition Scanner from package java.util.
6 {
Addition.java
7 // main method begins execution of Java application
8 public static void main( String args[] ) (1 of 2)
9 {
10 // create Scanner to obtain input from command window import
Declare and initialize declaration
variable
11 Scanner input = new Scanner( System.in );
input, which is a Scanner.
12 Scanner
13 int number1; // first number to add
14 int number2; // second number to add
Declare variables number1,
nextInt
15 int sum; // sum of number1 and number2
number2 and sum.
16
17 System.out.print( "Enter first integer: " ); // prompt
18 number1 = input.nextInt(); // read first number from user
19
Read an integer from the user
and assign it to number1.

© 2005 Pearson Education,


Inc. All rights reserved.
20 System.out.print( "Enter second integer: " ); // prompt 23
21 number2 = input.nextInt(); // read second number from user Outline
22 Read an integer from the user
23 sum = number1 + number2; // add numbers and assign it to number2.
24
Calculate the sum of the Addition.java
25 System.out.printf( "Sum is %d\n", sum ); // display sum
variables number1 and
26 number2, assign result to sum.(2 of 2)
27 } // end method main
28 Display the sum using 4. Addition
29 } // end class Addition
formatted output.
5. printf
Enter first integer: 45
Enter second integer: 72 Two integers entered by the user.
Sum is 117

© 2005 Pearson Education,


Inc. All rights reserved.
24

2.5 Another Java Application: Adding


Integers (Cont.)
3 import java.util.Scanner; // program uses class Scanner

– import declarations
• Used by compiler to identify and locate classes used in Java
programs
• Tells compiler to load class Scanner from java.util
package
5 public class Addition
6 {

– Begins public class Addition


• Recall that file name must be Addition.java
– Lines 8-9: begins main

© 2005 Pearson Education, Inc. All rights reserved.


25

Error-Prevention Tip 2.7


Forgetting to include an import declaration for
a class used in your program typically results
in a compilation error containing a message
such as “cannot resolve symbol.” When this
occurs, check that you provided the proper
import declarations and that the names in the
import declarations are spelled correctly,
including proper use of uppercase and
lowercase letters.

© 2005 Pearson Education, Inc. All rights reserved.


26

2.5 Another Java Application: Adding


Integers (Cont.)
10 // create Scanner to obtain input from command window
11 Scanner input = new Scanner( System.in );
– Variable Declaration Statement
– Variables
• Location in memory that stores a value
– Declare with name and type before use
• Input is of type Scanner
– Enables a program to read data for use
• Variable name: any valid identifier
– Declarations end with semicolons ;
– Initialize variable in its declaration
• Equal sign
• Standard input object
– System.in

© 2005 Pearson Education, Inc. All rights reserved.


27

2.5 Another Java Application: Adding


Integers (Cont.)
13 int number1; // first number to add
14 int number2; // second number to add
15 int sum; // second number to add

– Declare variable number1, number2 and sum of type int


• int holds integer values (whole numbers): i.e., 0, -4, 97
• Types float and double can hold decimal numbers
• Type char can hold a single character: i.e., x, $, \n, 7
• int, float, double and char are primitive types
– Can add comments to describe purpose of variables
int number1, // first number to add
number2, // second number to add
sum; // second number to add

– Can declare multiple variables of the same type in one


declaration
– Use comma-separated list

© 2005 Pearson Education, Inc. All rights reserved.


28

Good Programming Practice 2.11

Choosing meaningful variable names helps a


program to be self-documenting (i.e., one can
understand the program simply by reading it
rather than by reading manuals or viewing an
excessive number of comments).

© 2005 Pearson Education, Inc. All rights reserved.


29

Good Programming Practice 2.12

By convention, variable-name identifiers


begin with a lowercase letter, and every word
in the name after the first word begins with a
capital letter. For example, variable-name
identifier firstNumber has a capital N in its
second word, Number.

© 2005 Pearson Education, Inc. All rights reserved.


30

2.5 Another Java Application: Adding


Integers (Cont.)
17 System.out.print( "Enter first integer: " ); // prompt

– Message called a prompt - directs user to perform an


action
– Package java.lang
18 number1 = input.nextInt(); // read first number from user

– Result of call to nextInt given to number1 using


assignment operator =
• Assignment statement
• = binary operator - takes two operands
– Expression on right evaluated and assigned to variable
on left
• Read as: number1 gets the value of input.nextInt()

© 2005 Pearson Education, Inc. All rights reserved.


31

Software Engineering Observation 2.1

By default, package java.lang is imported in


every Java program; thus, java.lang is the
only package in the Java API that does not
require an import declaration.

© 2005 Pearson Education, Inc. All rights reserved.


32

2.5 Another Java Application: Adding


Integers (Cont.)
20 System.out.print( "Enter second integer: " ); // prompt

– Similar to previous statement


• Prompts the user to input the second integer
21 number2 = input.nextInt(); // read second number from user

– Similar to previous statement


• Assign variable number2 to second integer input
23 sum = number1 + number2; // add numbers

– Assignment statement
• Calculates sum of number1 and number2 (right hand side)
• Uses assignment operator = to assign result to variable sum
• Read as: sum gets the value of number1 + number2
• number1 and number2 are operands

© 2005 Pearson Education, Inc. All rights reserved.


33

2.5 Another Java Application: Adding


Integers (Cont.)
25 System.out.printf( "Sum is %d\n: " , sum ); // display sum

– Use System.out.printf to display results


– Format specifier %d
• Placeholder for an int value
System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );

– Calculations can also be performed inside printf


– Parentheses around the expression number1 + number2
are not required

© 2005 Pearson Education, Inc. All rights reserved.


34

2.7 Arithmetic

• Arithmetic calculations used in most programs


– Usage
• * for multiplication
• / for division
• % for remainder
• +, -
– Integer division truncates remainder
7 / 5 evaluates to 1
– Remainder operator % returns the remainder
7 % 5 evaluates to 2

© 2005 Pearson Education, Inc. All rights reserved.


35

Operator(s) Operation(s) Order of evaluation


(precedence)
* Multiplication Evaluated first. If there are
/ several operators of this type,
Division they are evaluated from left to
% Remainder right.

+ Addition Evaluated next. If there are


- several operators of this type,
Subtraction they are evaluated from left to
right.

Fig. 2.12 | Precedence of arithmetic operators.

© 2005 Pearson Education, Inc. All rights reserved.


36

Good Programming Practice 2.14

Using parentheses for complex arithmetic


expressions, even when the parentheses are
not necessary, can make the arithmetic
expressions easier to read.

© 2005 Pearson Education, Inc. All rights reserved.


37

2.8 Decision Making: Equality and


Relational Operators
• Condition
– Expression can be either true or false
•if statement
– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement
executed
– Control always resumes after the if statement
– Conditions in if statements can be formed using equality
or relational operators (next slide)

© 2005 Pearson Education, Inc. All rights reserved.


38

Standard algebraic Java equality Sample


equality or relational or relational Java Meaning of
operator operator condition Java condition
Equality operators
= == x == y x is equal to y
≠ != x != y x is not equal to y
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
≥ >= x >= y x is greater than or equal to y
≤ <= x <= y x is less than or equal to y

Fig. 2.14 | Equality and relational operators.

© 2005 Pearson Education, Inc. All rights reserved.


1 // Fig. 2.15: Comparison.java 39
2 // Compare integers using if statements, relational operators
3 // and equality operators. Outline
4 import java.util.Scanner; // program uses class Scanner
5
6 public class Comparison
7 {
8 // main method begins execution of Java application Comparison.java
9 public static void main( String args[] )
{
10
11 // create Scanner to obtain input from command window
(1 of 2)
12 Scanner input = new Scanner( System.in );
13 1. Class
14 int number1; // first number to compare
Comparison
15 int number2; // second number to compare
16 1.1 main
17 System.out.print( "Enter first integer: " ); // prompt
18 number1 = input.nextInt(); // read first number from user 1.2 Declarations
19
20 System.out.print( "Enter second integer: " ); // prompt 1.3 Input data
21 number2 = input.nextInt(); // read second number from user (nextInt)
22 Test for equality, display
1.4 Compare two
23 if ( number1 == number2 ) result using printf. inputs using if
24 System.out.printf( "%d == %d\n", number1, number2 );
25 statements
26 if ( number1 != number2 )
27 System.out.printf( "%d != %d\n", number1, number2 );
28 Compares two numbers
29 if ( number1 < number2 )
30 using relational
System.out.printf( "%d < %d\n", number1, number2 ); operator <.

© 2005 Pearson Education,


Inc. All rights reserved.
31 40
32 if ( number1 > number2 )
33 System.out.printf( "%d > %d\n", number1, number2 ); Outline
34
35 if ( number1 <= number2 )
Compares two numbers
36 System.out.printf( "%d <= %d\n", number1, using relational
number2 ); operator >,
37 <= and >=. Comparison.java
38 if ( number1 >= number2 )
39 System.out.printf( "%d >= %d\n", number1, number2 ); (2 of 2)
40
41 } // end method main
42
43 } // end class Comparison

Enter first integer: 777


Enter second integer: 777
Program output
777 == 777
777 <= 777
777 >= 777

Enter first integer: 1000


Enter second integer: 2000
1000 != 2000
1000 < 2000
1000 <= 2000

Enter first integer: 2000


Enter second integer: 1000
2000 != 1000
2000 > 1000
2000 >= 1000

© 2005 Pearson Education,


Inc. All rights reserved.
41

2.8 Decision Making: Equality and


Relational Operators (Cont.)
23 if ( number1 == number2 )
24 System.out.printf( "%d == %d\n", number1, number2 );

– if statement to test for equality using (==)


• If variables equal (condition true)
– Line 24 executes
• If variables not equal, statement skipped
• No semicolon at the end of if statement
• Empty statement
– No task is performed
– Lines 26-27, 29-30, 32-33, 35-36 and 38-39
• Compare number1 and number2 with the operators !=, <,
>, <= and >=, respectively

© 2005 Pearson Education, Inc. All rights reserved.


42

Good Programming Practice 2.15

Indent an if statement’s body to make it


stand out and to enhance program
readability.
Use braces {….} for all conditional clauses ---
even if the clause is only one statement.

© 2005 Pearson Education, Inc. All rights reserved.


43

Common Programming Error 2.13

Placing a semicolon immediately after the


right parenthesis of the condition in an if
statement is normally a logic error.

© 2005 Pearson Education, Inc. All rights reserved.


44

2.9 Software Engineering Case Study:


Examining the Requirements Document
• Object-oriented design (OOD) process using
UML
– Chapters 3 to 8, 10
• Object-oriented programming (OOP)
implementation
– Appendix J

© 2005 Pearson Education, Inc. All rights reserved.


45

2.9 Software Engineering Case Study


(Cont.)
• Requirements Document
– New automated teller machine (ATM)
– Allows basic financial transaction
• View balance, withdraw cash, deposit funds
– User interface
• Display screen, keypad, cash dispenser, deposit slot
– ATM session
• Authenticate user, execute financial transaction

© 2005 Pearson Education, Inc. All rights reserved.


46

Fig. 2.17 | Automated teller machine user interface.

© 2005 Pearson Education, Inc. All rights reserved.


47

Fig. 2.18 | ATM main menu.

© 2005 Pearson Education, Inc. All rights reserved.


48

Fig. 2.19 | ATM withdrawal menu.

© 2005 Pearson Education, Inc. All rights reserved.


49

2.9 Software Engineering Case Study


(Cont.)
• Analyzing the ATM System
– Requirements gathering
– Software life cycle
– Use case modeling
• Use case Diagram
– Model the interactions between clients and its use cases
– Actor
• External entity

© 2005 Pearson Education, Inc. All rights reserved.


50

Fig. 2.20 | Use case diagram for the ATM system from the user's perspective.

© 2005 Pearson Education, Inc. All rights reserved.


51

Fig. 2.21 | Use case diagram for a modified version of our ATM system that also allows
users to transfer money between accounts.

© 2005 Pearson Education, Inc. All rights reserved.


52

2.9 Software Engineering Case Study


(Cont.)
• UML diagram types
– Model system structure
• Class diagram
– Models classes, or “building blocks” of a system
– screen, keypad, cash dispenser, deposit slot.

© 2005 Pearson Education, Inc. All rights reserved.


53

2.9 Software Engineering Case Study


(Cont.)
– Model system behavior
• Use case diagrams
– Model interactions between user and a system
• State machine diagrams
– Model the ways in which an object changes state
• Activity diagrams
– Models an object’s activity during program execution
• Communication diagrams (collaboration diagrams)
– Models the interactions among objects
– Emphasize what interactions occur
• Sequence diagrams
– Models the interactions among objects
– Emphasize when interactions occur

© 2005 Pearson Education, Inc. All rights reserved.

You might also like