SlideShare a Scribd company logo
© 2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 2 - Introduction to Java
Applications
Outline
2.1 Introduction
2.2 A First Program in Java: Printing a Line of Text
2.3 Modifying Our First Java Program
2.4 Displaying Text in a Dialog Box
2.5 Another Java Application: Adding Integers
2.6 Memory Concepts
2.7 Arithmetic
2.8 Decision Making: Equality and Relational
Operators
2.9 (Optional Case Study) Thinking About Objects:
Examining the Problem Statement
© 2003 Prentice Hall, Inc. All rights reserved.
2
2.1 Introduction
• In this chapter
– Introduce examples to illustrate features of Java
– Two program styles - applications and applets
© 2003 Prentice Hall, Inc. All rights reserved.
3
2.2 A First Program in Java: Printing a Line
of Text
• Application
– Program that executes using the java interpreter
• Sample program
– Show program, then analyze each line
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
4
Welcome1.java
Program Output
1 // Fig. 2.1: Welcome1.java
2 // Text-printing program.
3
4 public class Welcome1 {
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!
© 2003 Prentice Hall, Inc. All rights reserved.
5
2.2 A First Program in Java: Printing a Line
of Text
– 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 */
– Another line of comments
– Note: line numbers not part of program, added for reference
1 // Fig. 2.1: Welcome1.java
2 // Text-printing program.
© 2003 Prentice Hall, Inc. All rights reserved.
6
– Blank line
• Makes program more readable
• Blank lines, spaces, and tabs are white-space characters
– Ignored by compiler
– 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
2.2 A Simple Program: Printing a Line of
Text
3
4 public class Welcome1 {
© 2003 Prentice Hall, Inc. All rights reserved.
7
2.2 A Simple Program: Printing a Line of
Text
– Name of class called 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
– For chapters 2 to 7, use public keyword
• Certain details not important now
• Mimic certain features, discussions later
4 public class Welcome1 {
© 2003 Prentice Hall, Inc. All rights reserved.
8
2.2 A Simple Program: Printing a Line of
Text
– Saving files
• File name must be class name with .java extension
• Welcome1.java
– Left brace {
• Begins body of every class
• Right brace ends declarations (line 13)
– Part of every Java application
• Applications begin executing at main
– Parenthesis indicate main is a method (ch. 6)
– Java applications contain one or more methods
4 public class Welcome1 {
7 public static void main( String args[] )
© 2003 Prentice Hall, Inc. All rights reserved.
9
2.2 A Simple Program: Printing a Line of
Text
• 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
– Left brace begins body of method declaration
• Ended by right brace } (line 11)
7 public static void main( String args[] )
8 {
© 2003 Prentice Hall, Inc. All rights reserved.
10
2.2 A Simple Program: Printing a Line of
Text
– 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
• Argument inside parenthesis
– This line known as a statement
• Statements must end with semicolon ;
9 System.out.println( "Welcome to Java Programming!" );
© 2003 Prentice Hall, Inc. All rights reserved.
11
2.2 A Simple Program: Printing a Line of
Text
– Ends method declaration
– Ends class declaration
– Can add comments to keep track of ending braces
– Lines 8 and 9 could be rewritten as:
– Remember, compiler ignores comments
– Comments can start on same line after code
11 } // end method main
13 } // end class Welcome1
© 2003 Prentice Hall, Inc. All rights reserved.
12
2.2 A Simple Program: Printing a Line of
Text
• Compiling a program
– Open a command prompt window, go to directory where
program is stored
– Type javac Welcome1.java
– If no errors, Welcome1.class created
• Has bytecodes that represent application
• Bytecodes passed to Java interpreter
© 2003 Prentice Hall, Inc. All rights reserved.
13
2.2 A Simple Program: Printing a Line of
Text
• Executing a program
– Type java Welcome1
• Interpreter loads .class file for class Welcome1
• .class extension omitted from command
– Interpreter calls method main
Fig. 2.2 Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.
© 2003 Prentice Hall, 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
© 2003 Prentice Hall, Inc. All rights reserved.
15
2.3 Modifying Our First Java Program
• Modifying programs
– Welcome2.java (Fig. 2.3) produces same output as
Welcome1.java (Fig. 2.1)
– Using different code
– Line 9 displays “Welcome to ” with cursor remaining on
printed line
– Line 10 displays “Java Programming! ” on same line with
cursor on next line
9 System.out.print( "Welcome to " );
10 System.out.println( "Java Programming!" );
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
16
Welcome2.java
1. Comments
2. Blank line
3. Begin class
Welcome2
3.1 Method main
4. Method
System.out.prin
t
4.1 Method
System.out.prin
tln
5. end main,
Welcome2
Program Output
Welcome to Java Programming!
1 // Fig. 2.3: Welcome2.java
2 // Printing a line of text with multiple statements.
3
4 public class Welcome2 {
5
6 // main method begins execution of Java application
7 public static void main( String args[] )
8 {
9 System.out.print( "Welcome to " );
10 System.out.println( "Java Programming!" );
11
12 } // end method main
13
14 } // end class Welcome2
System.out.print keeps the cursor on
the same line, so System.out.println
continues on the same line.
© 2003 Prentice Hall, Inc. All rights reserved.
17
2.3 Modifying Our First Java Program
• Newline characters (n)
– Interpreted as “special characters” by methods
System.out.print and System.out.println
– Indicates cursor should be on next line
– Welcome3.java (Fig. 2.4)
– Line breaks at n
• Usage
– Can use in System.out.println or
System.out.print to create new lines
• System.out.println( "WelcomentonJavanPr
ogramming!" );
9 System.out.println( "WelcomentonJavanProgramming!" );
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
18
Welcome3.java
1. main
2.
System.out.prin
tln (uses n for new
line)
Program Output
1 // Fig. 2.4: Welcome3.java
2 // Printing multiple lines of text with a single statement.
3
4 public class Welcome3 {
5
6 // main method begins execution of Java application
7 public static void main( String args[] )
8 {
9 System.out.println( "WelcomentonJavanProgramming!" );
10
11 } // end method main
12
13 } // end class Welcome3
Welcome
to
Java
Programming!
Notice how a new line is output for each n
escape sequence.
© 2003 Prentice Hall, Inc. All rights reserved.
19
2.3 Modifying Our First Java Program
Escape characters
– Backslash (  )
– Indicates special characters be output
Escape
sequence
Description
n Newline. Position the screen cursor at the beginning of the
next line.
t Horizontal tab. Move the screen cursor to the next tab stop.
r Carriage return. Position the screen cursor at the beginning of
the current line; do not advance to the next line. Any
characters output after the carriage return overwrite the
characters previously output on that line.
 Backslash. Used to print a backslash character.
" Double quote. Used to print a double-quote character. For
example,
System.out.println( ""in quotes"" );
displays
"in quotes"
Fig. 2.5Some common escape sequences.
© 2003 Prentice Hall, Inc. All rights reserved.
20
2.4 Displaying Text in a Dialog Box
• Display
– Most Java applications use windows or a dialog box
• We have used command window
– Class JOptionPane allows us to use dialog boxes
• Packages
– Set of predefined classes for us to use
– Groups of related classes called packages
• Group of all packages known as Java class library or Java
applications programming interface (Java API)
– JOptionPane is in the javax.swing package
• Package has classes for using Graphical User Interfaces
(GUIs)
© 2003 Prentice Hall, Inc. All rights reserved.
21
2.4 Displaying Text in a Dialog Box
menu menu barbutton text field
© 2003 Prentice Hall, Inc. All rights reserved.
22
2.4 Displaying Text in a Dialog Box
• Upcoming program
– Application that uses dialog boxes
– Explanation will come afterwards
– Demonstrate another way to display output
– Packages, methods and GUI
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
23
Welcome4.java
1. import
declaration
2. Class Welcome4
2.1 main
2.2
showMessageDial
og
2.3 System.exit
Program Output
1 // Fig. 2.6: Welcome4.java
2 // Printing multiple lines in a dialog box
3 import javax.swing.JOptionPane; // import class JOptionPane
4
5 public class Welcome4 {
6 public static void main( String args] )
7 {
8 JOptionPane.showMessageDialog(
9 null, "WelcomentonJavanProgramming!" );
10
11 System.exit( 0 ); // terminate the program
12 }
1 // Fig. 2.6: Welcome4.java
2 // Printing multiple lines in a dialog box.
3
4 // Java packages
5 import javax.swing.JOptionPane; // program uses JOptionPane
6
7 public class Welcome4 {
8
9 // main method begins execution of Java application
10 public static void main( String args[] )
11 {
12 JOptionPane.showMessageDialog(
13 null, "WelcomentonJavanProgramming!" );
14
15 System.exit( 0 ); // terminate application with window
16
17 } // end method main
18
19 } // end class Welcome4
© 2003 Prentice Hall, Inc. All rights reserved.
24
2.4 Displaying Text in a Dialog Box
– Lines 1-2: comments as before
– Two groups of packages in Java API
– Core packages
• Begin with java
• Included with Java 2 Software Development Kit
– Extension packages
• Begin with javax
• New Java packages
– import declarations
• Used by compiler to identify and locate classes used in Java
programs
• Tells compiler to load class JOptionPane from
javax.swing package
4 // Java packages
5 import javax.swing.JOptionPane; // program uses OptionPane
© 2003 Prentice Hall, Inc. All rights reserved.
25
2.4 Displaying Text in a Dialog Box
– Lines 6-11: Blank line, begin class Welcome4 and main
– Call method showMessageDialog of class
JOptionPane
• Requires two arguments
• Multiple arguments separated by commas (,)
• For now, first argument always null
• Second argument is string to display
– showMessageDialog is a static method of class
JOptionPane
• static methods called using class name, dot (.) then
method name
12 JOptionPane.showMessageDialog(
13 null, "WelcomentonJavanProgramming!" );
© 2003 Prentice Hall, Inc. All rights reserved.
26
2.4 Displaying Text in a Dialog Box
– All statements end with ;
• A single statement can span multiple lines
• Cannot split statement in middle of identifier or string
– Executing lines 12 and 13 displays the dialog box
• Automatically includes an OK button
– Hides or dismisses dialog box
• Title bar has string Message
© 2003 Prentice Hall, Inc. All rights reserved.
27
2.4 Displaying Text in a Dialog Box
– Calls static method exit of class System
• Terminates application
– Use with any application displaying a GUI
• Because method is static, needs class name and dot (.)
• Identifiers starting with capital letters usually class names
– Argument of 0 means application ended successfully
• Non-zero usually means an error occurred
– Class System part of package java.lang
• No import declaration needed
• java.lang automatically imported in every Java program
– Lines 17-19: Braces to end Welcome4 and main
15 System.exit( 0 ); // terminate application with window
© 2003 Prentice Hall, Inc. All rights reserved.
28
2.5 Another Java Application: Adding
Integers
• Upcoming program
– Use input dialogs to input two values from user
– Use message dialog to display sum of the two values
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
29
Addition.java
1. import
2. class Addition
2.1 Declare variables
(name and type)
3.
showInputDialog
4. parseInt
5. Add numbers, put
result in sum
1 // Fig. 2.9: Addition.java
2 // Addition program that displays the sum of two numbers.
3
4 // Java packages
5 import javax.swing.JOptionPane; // program uses JOptionPane
6
7 public class Addition {
8
9 // main method begins execution of Java application
10 public static void main( String args[] )
11 {
12 String firstNumber; // first string entered by user
13 String secondNumber; // second string entered by user
14
15 int number1; // first number to add
16 int number2; // second number to add
17 int sum; // sum of number1 and number2
18
19 // read in first number from user as a String
20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
21
22 // read in second number from user as a String
23 secondNumber =
24 JOptionPane.showInputDialog( "Enter second integer" );
25
26 // convert numbers from type String to type int
27 number1 = Integer.parseInt( firstNumber );
28 number2 = Integer.parseInt( secondNumber );
29
30 // add numbers
31 sum = number1 + number2;
32
Declare variables: name and type.
Input first integer as a String, assign
to firstNumber.
Add, place result in sum.
Convert strings to integers.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
30
Program output
33 // display result
34 JOptionPane.showMessageDialog( null, "The sum is " + sum,
35 "Results", JOptionPane.PLAIN_MESSAGE );
36
37 System.exit( 0 ); // terminate application with window
38
39 } // end method main
40
41 } // end class Addition
© 2003 Prentice Hall, Inc. All rights reserved.
31
2.5 Another Java Application: Adding
Integers
– Location of JOptionPane for use in the program
– Begins public class Addition
• Recall that file name must be Addition.java
– Lines 10-11: main
– Declaration
• firstNumber and secondNumber are variables
5 import javax.swing.JOptionPane; // program uses JOptionPane
7 public class Addition {
12 String firstNumber; // first string entered by user
13 String secondNumber; // second string entered by user
© 2003 Prentice Hall, Inc. All rights reserved.
32
2.5 Another Java Application: Adding
Integers
– Variables
• Location in memory that stores a value
– Declare with name and type before use
• firstNumber and secondNumber are of type String
(package java.lang)
– Hold strings
• Variable name: any valid identifier
• Declarations end with semicolons ;
– Can declare multiple variables of the same type at a time
– Use comma separated list
– Can add comments to describe purpose of variables
String firstNumber, secondNumber;
12 String firstNumber; // first string entered by user
13 String secondNumber; // second string entered by user
© 2003 Prentice Hall, Inc. All rights reserved.
33
2.5 Another Java Application: Adding
Integers
– Declares variables 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
• Primitive types - more in Chapter 4
15 int number1; // first number to add
16 int number2; // second number to add
17 int sum; // sum of number1 and number2
© 2003 Prentice Hall, Inc. All rights reserved.
34
2.5 Another Java Application: Adding
Integers
– Reads String from the user, representing the first number
to be added
• Method JOptionPane.showInputDialog displays the
following:
• Message called a prompt - directs user to perform an action
• Argument appears as prompt text
• If wrong type of data entered (non-integer) or click Cancel,
error occurs
20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
© 2003 Prentice Hall, Inc. All rights reserved.
35
2.5 Another Java Application: Adding
Integers
– Result of call to showInputDialog given to
firstNumber using assignment operator =
• Assignment statement
• = binary operator - takes two operands
– Expression on right evaluated and assigned to variable on
left
• Read as: firstNumber gets value of
JOptionPane.showInputDialog( "Enter first
integer" )
20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
© 2003 Prentice Hall, Inc. All rights reserved.
36
2.5 Another Java Application: Adding
Integers
– Similar to previous statement
• Assigns variable secondNumber to second integer input
– Method Integer.parseInt
• Converts String argument into an integer (type int)
– Class Integer in java.lang
• Integer returned by Integer.parseInt is assigned to
variable number1 (line 27)
– Remember that number1 was declared as type int
• Line 28 similar
23 secondNumber =
24 JOptionPane.showInputDialog( "Enter second integer" );
27 number1 = Integer.parseInt( firstNumber );
28 number2 = Integer.parseInt( secondNumber );
© 2003 Prentice Hall, Inc. All rights reserved.
37
2.5 Another Java Application: Adding
Integers
– 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
31 sum = number1 + number2;
© 2003 Prentice Hall, Inc. All rights reserved.
38
2.5 Another Java Application: Adding
Integers
– Use showMessageDialog to display results
– "The sum is " + sum
• Uses the operator + to "add" the string literal "The sum is"
and sum
• Concatenation of a String and another type
– Results in a new string
• If sum contains 117, then "The sum is " + sum results in
the new string "The sum is 117"
• Note the space in "The sum is "
• More on strings in Chapter 11
34 JOptionPane.showMessageDialog( null, "The sum is " + sum,
35 "Results", JOptionPane.PLAIN_MESSAGE );
© 2003 Prentice Hall, Inc. All rights reserved.
39
2.5 Another Java Application: Adding
Integers
– Different version of showMessageDialog
• Requires four arguments (instead of two as before)
• First argument: null for now
• Second: string to display
• Third: string in title bar
• Fourth: type of message dialog with icon
– Line 35 no icon: JOptionPane.PLAIN_MESSAGE
34 JOptionPane.showMessageDialog( null, "The sum is " + sum,
35 "Results", JOptionPane.PLAIN_MESSAGE );
© 2003 Prentice Hall, Inc. All rights reserved.
40
2.5 Another Java Application: Adding
Integers
Message dialog type Icon Description
JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error
to the user.
JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational
message to the user. The user can simply
dismiss the dialog.
JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a
potential problem.
JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to
the user. This dialog normally requires a
response, such as clicking on a Yes or a
No button.
JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a
message, with no icon.
Fig. 2.12 JOptionPane constants for message dialogs.
© 2003 Prentice Hall, Inc. All rights reserved.
41
2.6 Memory Concepts
• Variables
– Every variable has a name, a type, a size and a value
• Name corresponds to location in memory
– When new value is placed into a variable, replaces (and
destroys) previous value
– Reading variables from memory does not change them
© 2003 Prentice Hall, Inc. All rights reserved.
42
2.6 Memory Concepts
• Visual Representation
– Sum = 0; number1 = 1; number2 = 2;
– Sum = number1 + number2; after execution of statement
sum 0
sum 3
© 2003 Prentice Hall, Inc. All rights reserved.
43
2.7 Arithmetic
• Arithmetic calculations used in most programs
– Usage
• * for multiplication
• / for division
• +, -
• No operator for exponentiation (more in Chapter 5)
– Integer division truncates remainder
7 / 5 evaluates to 1
– Remainder operator % returns the remainder
7 % 5 evaluates to 2
© 2003 Prentice Hall, Inc. All rights reserved.
44
2.7 Arithmetic
• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: ( a + b + c ) / 3
– Follows PEMDAS
• Parentheses, Exponents, Multiplication, Division, Addition,
Subtraction
© 2003 Prentice Hall, Inc. All rights reserved.
45
2.7 Arithmetic
Operator(s) Operation(s) Order of evaluation (precedence)
*
/
%
Multiplication
Division
Remainder
Evaluated first. If there are several of this type
of operator, they are evaluated from left to
right.
+
-
Addition
Subtraction
Evaluated next. If there are several of this type
of operator, they are evaluated from left to
right.
Fig. 2.17 Precedence of arithmetic operators.
© 2003 Prentice Hall, Inc. All rights reserved.
46
2.8 Decision Making: Equality and
Relational Operators
• if control statement
– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement
executed
• 0 interpreted as false, non-zero is true
– Control always resumes after the if structure
– Conditions for if statements can be formed using equality
or relational operators (next slide)
if ( condition )
statement executed if condition true
• No semicolon needed after condition
– Else conditional task not performed
© 2003 Prentice Hall, Inc. All rights reserved.
47
2.8 Decision Making: Equality and
Relational Operators
• Upcoming program uses if statements
– Discussion afterwards
Standard algebraic
equality or
relational operator
Java equality
or relational
operator
Example
of Java
condition
Meaning of
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.19 Equality and relational operators.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
48
Comparison.java
1. import
2. Class
Comparison
2.1 main
2.2 Declarations
2.3 Input data
(showInputDialo
g)
2.4 parseInt
2.5 Initialize result
1 // Fig. 2.20: Comparison.java
2 // Compare integers using if statements, relational operators
3 // and equality operators.
4
5 // Java packages
6 import javax.swing.JOptionPane;
7
8 public class Comparison {
9
10 // main method begins execution of Java application
11 public static void main( String args[] )
12 {
13 String firstNumber; // first string entered by user
14 String secondNumber; // second string entered by user
15 String result; // a string containing the output
16
17 int number1; // first number to compare
18 int number2; // second number to compare
19
20 // read first number from user as a string
21 firstNumber = JOptionPane.showInputDialog( "Enter first integer:" );
22
23 // read second number from user as a string
24 secondNumber =
25 JOptionPane.showInputDialog( "Enter second integer:" );
26
27 // convert numbers from type String to type int
28 number1 = Integer.parseInt( firstNumber );
29 number2 = Integer.parseInt( secondNumber );
30
31 // initialize result to empty String
32 result = "";
33
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
49
Comparison.java
3. if statements
4.
showMessageDialo
g
34 if ( number1 == number2 )
35 result = result + number1 + " == " + number2;
36
37 if ( number1 != number2 )
38 result = result + number1 + " != " + number2;
39
40 if ( number1 < number2 )
41 result = result + "n" + number1 + " < " + number2;
42
43 if ( number1 > number2 )
44 result = result + "n" + number1 + " > " + number2;
45
46 if ( number1 <= number2 )
47 result = result + "n" + number1 + " <= " + number2;
48
49 if ( number1 >= number2 )
50 result = result + "n" + number1 + " >= " + number2;
51
52 // Display results
53 JOptionPane.showMessageDialog( null, result, "Comparison Results",
54 JOptionPane.INFORMATION_MESSAGE );
55
56 System.exit( 0 ); // terminate application
57
58 } // end method main
59
60 } // end class Comparison
Test for equality, create new string,
assign to result.
Notice use of JOptionPane.INFORMATION_MESSAGE
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
50
Program Output
© 2003 Prentice Hall, Inc. All rights reserved.
51
2.8 Decision Making: Equality and
Relational Operators
– Lines 1-12: Comments, import JOptionPane, begin
class Comparison and main
– Lines 13-18: declare variables
• Can use comma-separated lists instead:
– Lines 21-30: obtain user-input numbers and parses input
string into integer variables
13 String firstNumber,
14 secondNumber,
15 result;
© 2003 Prentice Hall, Inc. All rights reserved.
52
2.8 Decision Making: Equality and
Relational Operators
– Initialize result with empty string
– if statement to test for equality using (==)
• If variables equal (condition true)
– result concatenated using + operator
– result = result + other strings
– Right side evaluated first, new string assigned to result
• If variables not equal, statement skipped
32 result = "";
34 if ( number1 == number2 )
35 result = result + number1 + " == " + number2;
© 2003 Prentice Hall, Inc. All rights reserved.
53
2.8 Decision Making: Equality and
Relational Operators
– Lines 37-50: other if statements testing for less than, more
than, etc.
• If number1 = 123 and number2 = 123
– Line 34 evaluates true (if number1 = = number 2)
• Because number1 equals number2
– Line 40 evaluates false (if number1 < number 2)
• Because number1 is not less than number2
– Line 49 evaluates true (if number1 >= number2)
• Because number1 is greater than or equal to number2
– Lines 53-54: result displayed in a dialog box using
showMessageDialog
© 2003 Prentice Hall, Inc. All rights reserved.
54
2.8 Decision Making: Equality and
Relational Operators
• Precedence of operators
– All operators except for = (assignment) associates from left
to right
• For example: x = y = z is evaluated x = (y = z)
Operators Associativity Type
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
= right to left assignment
Fig. 2.21 Precedence and associativity of the operators discussed so far.
© 2003 Prentice Hall, Inc. All rights reserved.
55
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
• Emphasize object-oriented programming (OOP)
• Object-oriented design (OOD) implementation
– Chapters 3 to 14, 16, 19
– Appendices D, E, F
© 2003 Prentice Hall, Inc. All rights reserved.
56
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
• Program Goal
– Software simulator application
– 2-floor elevator simulator
• Models actual elevator operation
– Elevator graphics displayed to user
– Graphical user interface (GUI)
• User can control elevator
© 2003 Prentice Hall, Inc. All rights reserved.
57
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
• Elevator Simulation
– Model people using elevator
– Elevator door, floor door, elevator button, floor button,
elevator shaft, bell, floor, backgrounds
• Operate accordingly or by request to avoid “injuring” person
and make useless operations
– Create person objects
– Simulation rules
• Elevator visits floor which person requests for elevator
service
• One person per elevator
• 5 seconds to move from floors
© 2003 Prentice Hall, Inc. All rights reserved.
58
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
• Application GUI
– First Floor/Second Floor buttons create person on
respective floors
• Disable button if floor occupied by a person already
• Unlimited number of passenger creations
– Animation requirements
• Passenger walking and pressing floor button
• Elevator moving, doors opening and closing
• Illumination of elevator lights and buttons during operation
– Incorporating sounds
• Footsteps when person walks
• Button pressing clicks
• Elevator bell rings upon elevator arrival, elevator music
• Doors creak when opening and closing
© 2003 Prentice Hall, Inc. All rights reserved.
59
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
© 2003 Prentice Hall, Inc. All rights reserved.
60
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
© 2003 Prentice Hall, Inc. All rights reserved.
61
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
© 2003 Prentice Hall, Inc. All rights reserved.
62
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
• Designing elevator system
– Specified in requirements document through OOD analysis
• UML
• Design used to implement Java code
– How system should be constructed to complete tasks
• System Structure
– System is a set of interactive components to solve problems
• Simplified by subsystems
– Simulator (through ch. 16), GUI (ch. 13 and 14, display
(ch. 22)
– Describes system’s objects and inter-relationships
– System behavior describes how system changes through object
interaction
© 2003 Prentice Hall, Inc. All rights reserved.
63
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
• UML diagram types
– System structure
• Class diagram (section 3.7)
– Models classes, or “building blocks” of a system
– Person, elevator, floor, etc.
• Object diagrams (section 3.7)
– Snapshot (model) of system’s objects and relationships at
specific point in time
• Component diagrams (section 14.13)
– Model components such as graphics resources and class
packages that make up the system
• Deployment diagrams (not discussed)
– Model hardware, memory and runtime resources
© 2003 Prentice Hall, Inc. All rights reserved.
64
2.9 (Optional Case Study) Thinking About
Objects: Examining the Problem Statement
– System behavior
• Statechart diagrams (section 5.11)
– Model how object changes state
• Condition/behavior of an object at a specific time
• Activity diagrams (section 5.11)
– Flowchart modeling order and actions performed by
object
• Collaboration diagrams (section 7.10)
– Emphasize what interactions occur
• Sequence diagrams (section 16.11)
– Emphasize when interactions occur
• Use-case diagrams (section 13.17)
– Represent interaction between user and system
• Clicking elevator button

More Related Content

PDF
Java swing 1
PDF
Introduction to systems programming
DOC
Assembler
PPTX
Translators(Compiler, Assembler) and interpreter
PPT
Lecture 3 java basics
PPT
How a Compiler Works ?
DOCX
Java 3 rd sem. 2012 aug.ASSIGNMENT
PPTX
COMPILER DESIGN OPTIONS
Java swing 1
Introduction to systems programming
Assembler
Translators(Compiler, Assembler) and interpreter
Lecture 3 java basics
How a Compiler Works ?
Java 3 rd sem. 2012 aug.ASSIGNMENT
COMPILER DESIGN OPTIONS

What's hot (20)

PPTX
PPTX
Compiler Construction Course - Introduction
DOC
Compiler Design(NANTHU NOTES)
PPT
PPT
Compiler Design Basics
PDF
Chapter1pdf__2021_11_23_10_53_20.pdf
PDF
unit1pdf__2021_12_14_12_37_34.pdf
PPT
Phases of compiler
PPT
Introduction to Compiler Construction
PPT
Compiler Construction introduction
PDF
(Ebook pdf) java programming language basics
PPTX
Compiler vs Interpreter-Compiler design ppt.
PPT
Introduction to compiler
PPT
basics of compiler design
PDF
Compiler design Introduction
PPT
Passes of compilers
PDF
COMPILER DESIGN- Introduction & Lexical Analysis:
PDF
JAVA Program Examples
PPSX
PPT
Assembler
Compiler Construction Course - Introduction
Compiler Design(NANTHU NOTES)
Compiler Design Basics
Chapter1pdf__2021_11_23_10_53_20.pdf
unit1pdf__2021_12_14_12_37_34.pdf
Phases of compiler
Introduction to Compiler Construction
Compiler Construction introduction
(Ebook pdf) java programming language basics
Compiler vs Interpreter-Compiler design ppt.
Introduction to compiler
basics of compiler design
Compiler design Introduction
Passes of compilers
COMPILER DESIGN- Introduction & Lexical Analysis:
JAVA Program Examples
Assembler
Ad

Similar to Introduction to Java Applications (20)

PPTX
AndroidHTP3_AppA.pptx
PPT
INTRODUCTION TO JAVA APPLICATION
PPT
jhtp10_ch02_Intro to java Applications: Input/Output and Operators
PPT
Core java-introduction
PPT
Basics of java 1
PPT
Java intro
PDF
02장 Introduction to Java Applications
PPT
01slide
PPT
01slide
PPT
01slide
PPT
01slide (1)ffgfefge
PPTX
lecture 6
PPTX
Introduction to computer science
PPTX
Multi Threading- in Java WPS Office.pptx
PPT
JavaHTP7e_0202_DDP.ppt
PPTX
Intro to programing with java-lecture 1
PPT
Java introduction
PPTX
objectorientedprogrammingCHAPTER 2 (OOP).pptx
PPT
Introduction
PPT
Java PPt.ppt
AndroidHTP3_AppA.pptx
INTRODUCTION TO JAVA APPLICATION
jhtp10_ch02_Intro to java Applications: Input/Output and Operators
Core java-introduction
Basics of java 1
Java intro
02장 Introduction to Java Applications
01slide
01slide
01slide
01slide (1)ffgfefge
lecture 6
Introduction to computer science
Multi Threading- in Java WPS Office.pptx
JavaHTP7e_0202_DDP.ppt
Intro to programing with java-lecture 1
Java introduction
objectorientedprogrammingCHAPTER 2 (OOP).pptx
Introduction
Java PPt.ppt
Ad

More from Andy Juan Sarango Veliz (20)

PDF
Examen final de CCNA Routing y Switching Academia OW
PDF
Criptología de empleo en el Esquema Nacional de Seguridad
PDF
Alfabetización Informática - 3. Navegador Web
PDF
Alfabetización Informática - 2. Test de Conceptos Básicos
PDF
Alfabetización Informática - 1. Conceptos Básicos
PDF
Gestión y Operación de la Ciberseguridad
PPTX
Tecnologías de virtualización y despliegue de servicios
PDF
3. wordpress.org
PDF
2. wordpress.com
PDF
1. Introducción a Wordpress
PDF
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
PDF
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
PDF
Software Defined Radio - Capítulo 5: Modulación Digital I
PDF
Software Defined Radio - Capítulo 4: Modulación FM
PDF
Software Defined Radio - Capítulo 3: Modulación AM
PDF
Software Defined Radio - Capítulo 2: GNU Radio Companion
PDF
Software Defined Radio - Capítulo 1: Introducción
PDF
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
PDF
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
PDF
ITIL Foundation ITIL 4 Edition
Examen final de CCNA Routing y Switching Academia OW
Criptología de empleo en el Esquema Nacional de Seguridad
Alfabetización Informática - 3. Navegador Web
Alfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 1. Conceptos Básicos
Gestión y Operación de la Ciberseguridad
Tecnologías de virtualización y despliegue de servicios
3. wordpress.org
2. wordpress.com
1. Introducción a Wordpress
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Software Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 1: Introducción
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
ITIL Foundation ITIL 4 Edition

Recently uploaded (20)

PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
additive manufacturing of ss316l using mig welding
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPT
Project quality management in manufacturing
DOCX
573137875-Attendance-Management-System-original
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
Sustainable Sites - Green Building Construction
PPTX
web development for engineering and engineering
PDF
PPT on Performance Review to get promotions
PDF
Digital Logic Computer Design lecture notes
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Well-logging-methods_new................
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Construction Project Organization Group 2.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
additive manufacturing of ss316l using mig welding
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Project quality management in manufacturing
573137875-Attendance-Management-System-original
Internet of Things (IOT) - A guide to understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Sustainable Sites - Green Building Construction
web development for engineering and engineering
PPT on Performance Review to get promotions
Digital Logic Computer Design lecture notes
CH1 Production IntroductoryConcepts.pptx
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Well-logging-methods_new................
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Automation-in-Manufacturing-Chapter-Introduction.pdf
Construction Project Organization Group 2.pptx

Introduction to Java Applications

  • 1. © 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1 Introduction 2.2 A First Program in Java: Printing a Line of Text 2.3 Modifying Our First Java Program 2.4 Displaying Text in a Dialog Box 2.5 Another Java Application: Adding Integers 2.6 Memory Concepts 2.7 Arithmetic 2.8 Decision Making: Equality and Relational Operators 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement
  • 2. © 2003 Prentice Hall, Inc. All rights reserved. 2 2.1 Introduction • In this chapter – Introduce examples to illustrate features of Java – Two program styles - applications and applets
  • 3. © 2003 Prentice Hall, Inc. All rights reserved. 3 2.2 A First Program in Java: Printing a Line of Text • Application – Program that executes using the java interpreter • Sample program – Show program, then analyze each line
  • 4. © 2003 Prentice Hall, Inc. All rights reserved. Outline 4 Welcome1.java Program Output 1 // Fig. 2.1: Welcome1.java 2 // Text-printing program. 3 4 public class Welcome1 { 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!
  • 5. © 2003 Prentice Hall, Inc. All rights reserved. 5 2.2 A First Program in Java: Printing a Line of Text – 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 */ – Another line of comments – Note: line numbers not part of program, added for reference 1 // Fig. 2.1: Welcome1.java 2 // Text-printing program.
  • 6. © 2003 Prentice Hall, Inc. All rights reserved. 6 – Blank line • Makes program more readable • Blank lines, spaces, and tabs are white-space characters – Ignored by compiler – 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 2.2 A Simple Program: Printing a Line of Text 3 4 public class Welcome1 {
  • 7. © 2003 Prentice Hall, Inc. All rights reserved. 7 2.2 A Simple Program: Printing a Line of Text – Name of class called 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 – For chapters 2 to 7, use public keyword • Certain details not important now • Mimic certain features, discussions later 4 public class Welcome1 {
  • 8. © 2003 Prentice Hall, Inc. All rights reserved. 8 2.2 A Simple Program: Printing a Line of Text – Saving files • File name must be class name with .java extension • Welcome1.java – Left brace { • Begins body of every class • Right brace ends declarations (line 13) – Part of every Java application • Applications begin executing at main – Parenthesis indicate main is a method (ch. 6) – Java applications contain one or more methods 4 public class Welcome1 { 7 public static void main( String args[] )
  • 9. © 2003 Prentice Hall, Inc. All rights reserved. 9 2.2 A Simple Program: Printing a Line of Text • 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 – Left brace begins body of method declaration • Ended by right brace } (line 11) 7 public static void main( String args[] ) 8 {
  • 10. © 2003 Prentice Hall, Inc. All rights reserved. 10 2.2 A Simple Program: Printing a Line of Text – 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 • Argument inside parenthesis – This line known as a statement • Statements must end with semicolon ; 9 System.out.println( "Welcome to Java Programming!" );
  • 11. © 2003 Prentice Hall, Inc. All rights reserved. 11 2.2 A Simple Program: Printing a Line of Text – Ends method declaration – Ends class declaration – Can add comments to keep track of ending braces – Lines 8 and 9 could be rewritten as: – Remember, compiler ignores comments – Comments can start on same line after code 11 } // end method main 13 } // end class Welcome1
  • 12. © 2003 Prentice Hall, Inc. All rights reserved. 12 2.2 A Simple Program: Printing a Line of Text • Compiling a program – Open a command prompt window, go to directory where program is stored – Type javac Welcome1.java – If no errors, Welcome1.class created • Has bytecodes that represent application • Bytecodes passed to Java interpreter
  • 13. © 2003 Prentice Hall, Inc. All rights reserved. 13 2.2 A Simple Program: Printing a Line of Text • Executing a program – Type java Welcome1 • Interpreter loads .class file for class Welcome1 • .class extension omitted from command – Interpreter calls method main Fig. 2.2 Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.
  • 14. © 2003 Prentice Hall, 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
  • 15. © 2003 Prentice Hall, Inc. All rights reserved. 15 2.3 Modifying Our First Java Program • Modifying programs – Welcome2.java (Fig. 2.3) produces same output as Welcome1.java (Fig. 2.1) – Using different code – Line 9 displays “Welcome to ” with cursor remaining on printed line – Line 10 displays “Java Programming! ” on same line with cursor on next line 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" );
  • 16. © 2003 Prentice Hall, Inc. All rights reserved. Outline 16 Welcome2.java 1. Comments 2. Blank line 3. Begin class Welcome2 3.1 Method main 4. Method System.out.prin t 4.1 Method System.out.prin tln 5. end main, Welcome2 Program Output Welcome to Java Programming! 1 // Fig. 2.3: Welcome2.java 2 // Printing a line of text with multiple statements. 3 4 public class Welcome2 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" ); 11 12 } // end method main 13 14 } // end class Welcome2 System.out.print keeps the cursor on the same line, so System.out.println continues on the same line.
  • 17. © 2003 Prentice Hall, Inc. All rights reserved. 17 2.3 Modifying Our First Java Program • Newline characters (n) – Interpreted as “special characters” by methods System.out.print and System.out.println – Indicates cursor should be on next line – Welcome3.java (Fig. 2.4) – Line breaks at n • Usage – Can use in System.out.println or System.out.print to create new lines • System.out.println( "WelcomentonJavanPr ogramming!" ); 9 System.out.println( "WelcomentonJavanProgramming!" );
  • 18. © 2003 Prentice Hall, Inc. All rights reserved. Outline 18 Welcome3.java 1. main 2. System.out.prin tln (uses n for new line) Program Output 1 // Fig. 2.4: Welcome3.java 2 // Printing multiple lines of text with a single statement. 3 4 public class Welcome3 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "WelcomentonJavanProgramming!" ); 10 11 } // end method main 12 13 } // end class Welcome3 Welcome to Java Programming! Notice how a new line is output for each n escape sequence.
  • 19. © 2003 Prentice Hall, Inc. All rights reserved. 19 2.3 Modifying Our First Java Program Escape characters – Backslash ( ) – Indicates special characters be output Escape sequence Description n Newline. Position the screen cursor at the beginning of the next line. t Horizontal tab. Move the screen cursor to the next tab stop. r Carriage return. Position the screen cursor at the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. Backslash. Used to print a backslash character. " Double quote. Used to print a double-quote character. For example, System.out.println( ""in quotes"" ); displays "in quotes" Fig. 2.5Some common escape sequences.
  • 20. © 2003 Prentice Hall, Inc. All rights reserved. 20 2.4 Displaying Text in a Dialog Box • Display – Most Java applications use windows or a dialog box • We have used command window – Class JOptionPane allows us to use dialog boxes • Packages – Set of predefined classes for us to use – Groups of related classes called packages • Group of all packages known as Java class library or Java applications programming interface (Java API) – JOptionPane is in the javax.swing package • Package has classes for using Graphical User Interfaces (GUIs)
  • 21. © 2003 Prentice Hall, Inc. All rights reserved. 21 2.4 Displaying Text in a Dialog Box menu menu barbutton text field
  • 22. © 2003 Prentice Hall, Inc. All rights reserved. 22 2.4 Displaying Text in a Dialog Box • Upcoming program – Application that uses dialog boxes – Explanation will come afterwards – Demonstrate another way to display output – Packages, methods and GUI
  • 23. © 2003 Prentice Hall, Inc. All rights reserved. Outline 23 Welcome4.java 1. import declaration 2. Class Welcome4 2.1 main 2.2 showMessageDial og 2.3 System.exit Program Output 1 // Fig. 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box 3 import javax.swing.JOptionPane; // import class JOptionPane 4 5 public class Welcome4 { 6 public static void main( String args] ) 7 { 8 JOptionPane.showMessageDialog( 9 null, "WelcomentonJavanProgramming!" ); 10 11 System.exit( 0 ); // terminate the program 12 } 1 // Fig. 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box. 3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane 6 7 public class Welcome4 { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 JOptionPane.showMessageDialog( 13 null, "WelcomentonJavanProgramming!" ); 14 15 System.exit( 0 ); // terminate application with window 16 17 } // end method main 18 19 } // end class Welcome4
  • 24. © 2003 Prentice Hall, Inc. All rights reserved. 24 2.4 Displaying Text in a Dialog Box – Lines 1-2: comments as before – Two groups of packages in Java API – Core packages • Begin with java • Included with Java 2 Software Development Kit – Extension packages • Begin with javax • New Java packages – import declarations • Used by compiler to identify and locate classes used in Java programs • Tells compiler to load class JOptionPane from javax.swing package 4 // Java packages 5 import javax.swing.JOptionPane; // program uses OptionPane
  • 25. © 2003 Prentice Hall, Inc. All rights reserved. 25 2.4 Displaying Text in a Dialog Box – Lines 6-11: Blank line, begin class Welcome4 and main – Call method showMessageDialog of class JOptionPane • Requires two arguments • Multiple arguments separated by commas (,) • For now, first argument always null • Second argument is string to display – showMessageDialog is a static method of class JOptionPane • static methods called using class name, dot (.) then method name 12 JOptionPane.showMessageDialog( 13 null, "WelcomentonJavanProgramming!" );
  • 26. © 2003 Prentice Hall, Inc. All rights reserved. 26 2.4 Displaying Text in a Dialog Box – All statements end with ; • A single statement can span multiple lines • Cannot split statement in middle of identifier or string – Executing lines 12 and 13 displays the dialog box • Automatically includes an OK button – Hides or dismisses dialog box • Title bar has string Message
  • 27. © 2003 Prentice Hall, Inc. All rights reserved. 27 2.4 Displaying Text in a Dialog Box – Calls static method exit of class System • Terminates application – Use with any application displaying a GUI • Because method is static, needs class name and dot (.) • Identifiers starting with capital letters usually class names – Argument of 0 means application ended successfully • Non-zero usually means an error occurred – Class System part of package java.lang • No import declaration needed • java.lang automatically imported in every Java program – Lines 17-19: Braces to end Welcome4 and main 15 System.exit( 0 ); // terminate application with window
  • 28. © 2003 Prentice Hall, Inc. All rights reserved. 28 2.5 Another Java Application: Adding Integers • Upcoming program – Use input dialogs to input two values from user – Use message dialog to display sum of the two values
  • 29. © 2003 Prentice Hall, Inc. All rights reserved. Outline 29 Addition.java 1. import 2. class Addition 2.1 Declare variables (name and type) 3. showInputDialog 4. parseInt 5. Add numbers, put result in sum 1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers. 3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane 6 7 public class Addition { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user 14 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2 18 19 // read in first number from user as a String 20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); 21 22 // read in second number from user as a String 23 secondNumber = 24 JOptionPane.showInputDialog( "Enter second integer" ); 25 26 // convert numbers from type String to type int 27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber ); 29 30 // add numbers 31 sum = number1 + number2; 32 Declare variables: name and type. Input first integer as a String, assign to firstNumber. Add, place result in sum. Convert strings to integers.
  • 30. © 2003 Prentice Hall, Inc. All rights reserved. Outline 30 Program output 33 // display result 34 JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE ); 36 37 System.exit( 0 ); // terminate application with window 38 39 } // end method main 40 41 } // end class Addition
  • 31. © 2003 Prentice Hall, Inc. All rights reserved. 31 2.5 Another Java Application: Adding Integers – Location of JOptionPane for use in the program – Begins public class Addition • Recall that file name must be Addition.java – Lines 10-11: main – Declaration • firstNumber and secondNumber are variables 5 import javax.swing.JOptionPane; // program uses JOptionPane 7 public class Addition { 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user
  • 32. © 2003 Prentice Hall, Inc. All rights reserved. 32 2.5 Another Java Application: Adding Integers – Variables • Location in memory that stores a value – Declare with name and type before use • firstNumber and secondNumber are of type String (package java.lang) – Hold strings • Variable name: any valid identifier • Declarations end with semicolons ; – Can declare multiple variables of the same type at a time – Use comma separated list – Can add comments to describe purpose of variables String firstNumber, secondNumber; 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user
  • 33. © 2003 Prentice Hall, Inc. All rights reserved. 33 2.5 Another Java Application: Adding Integers – Declares variables 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 • Primitive types - more in Chapter 4 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2
  • 34. © 2003 Prentice Hall, Inc. All rights reserved. 34 2.5 Another Java Application: Adding Integers – Reads String from the user, representing the first number to be added • Method JOptionPane.showInputDialog displays the following: • Message called a prompt - directs user to perform an action • Argument appears as prompt text • If wrong type of data entered (non-integer) or click Cancel, error occurs 20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
  • 35. © 2003 Prentice Hall, Inc. All rights reserved. 35 2.5 Another Java Application: Adding Integers – Result of call to showInputDialog given to firstNumber using assignment operator = • Assignment statement • = binary operator - takes two operands – Expression on right evaluated and assigned to variable on left • Read as: firstNumber gets value of JOptionPane.showInputDialog( "Enter first integer" ) 20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
  • 36. © 2003 Prentice Hall, Inc. All rights reserved. 36 2.5 Another Java Application: Adding Integers – Similar to previous statement • Assigns variable secondNumber to second integer input – Method Integer.parseInt • Converts String argument into an integer (type int) – Class Integer in java.lang • Integer returned by Integer.parseInt is assigned to variable number1 (line 27) – Remember that number1 was declared as type int • Line 28 similar 23 secondNumber = 24 JOptionPane.showInputDialog( "Enter second integer" ); 27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber );
  • 37. © 2003 Prentice Hall, Inc. All rights reserved. 37 2.5 Another Java Application: Adding Integers – 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 31 sum = number1 + number2;
  • 38. © 2003 Prentice Hall, Inc. All rights reserved. 38 2.5 Another Java Application: Adding Integers – Use showMessageDialog to display results – "The sum is " + sum • Uses the operator + to "add" the string literal "The sum is" and sum • Concatenation of a String and another type – Results in a new string • If sum contains 117, then "The sum is " + sum results in the new string "The sum is 117" • Note the space in "The sum is " • More on strings in Chapter 11 34 JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE );
  • 39. © 2003 Prentice Hall, Inc. All rights reserved. 39 2.5 Another Java Application: Adding Integers – Different version of showMessageDialog • Requires four arguments (instead of two as before) • First argument: null for now • Second: string to display • Third: string in title bar • Fourth: type of message dialog with icon – Line 35 no icon: JOptionPane.PLAIN_MESSAGE 34 JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE );
  • 40. © 2003 Prentice Hall, Inc. All rights reserved. 40 2.5 Another Java Application: Adding Integers Message dialog type Icon Description JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error to the user. JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational message to the user. The user can simply dismiss the dialog. JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a potential problem. JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button. JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a message, with no icon. Fig. 2.12 JOptionPane constants for message dialogs.
  • 41. © 2003 Prentice Hall, Inc. All rights reserved. 41 2.6 Memory Concepts • Variables – Every variable has a name, a type, a size and a value • Name corresponds to location in memory – When new value is placed into a variable, replaces (and destroys) previous value – Reading variables from memory does not change them
  • 42. © 2003 Prentice Hall, Inc. All rights reserved. 42 2.6 Memory Concepts • Visual Representation – Sum = 0; number1 = 1; number2 = 2; – Sum = number1 + number2; after execution of statement sum 0 sum 3
  • 43. © 2003 Prentice Hall, Inc. All rights reserved. 43 2.7 Arithmetic • Arithmetic calculations used in most programs – Usage • * for multiplication • / for division • +, - • No operator for exponentiation (more in Chapter 5) – Integer division truncates remainder 7 / 5 evaluates to 1 – Remainder operator % returns the remainder 7 % 5 evaluates to 2
  • 44. © 2003 Prentice Hall, Inc. All rights reserved. 44 2.7 Arithmetic • Operator precedence – Some arithmetic operators act before others (i.e., multiplication before addition) • Use parenthesis when needed – Example: Find the average of three variables a, b and c • Do not use: a + b + c / 3 • Use: ( a + b + c ) / 3 – Follows PEMDAS • Parentheses, Exponents, Multiplication, Division, Addition, Subtraction
  • 45. © 2003 Prentice Hall, Inc. All rights reserved. 45 2.7 Arithmetic Operator(s) Operation(s) Order of evaluation (precedence) * / % Multiplication Division Remainder Evaluated first. If there are several of this type of operator, they are evaluated from left to right. + - Addition Subtraction Evaluated next. If there are several of this type of operator, they are evaluated from left to right. Fig. 2.17 Precedence of arithmetic operators.
  • 46. © 2003 Prentice Hall, Inc. All rights reserved. 46 2.8 Decision Making: Equality and Relational Operators • if control statement – Simple version in this section, more detail later – If a condition is true, then the body of the if statement executed • 0 interpreted as false, non-zero is true – Control always resumes after the if structure – Conditions for if statements can be formed using equality or relational operators (next slide) if ( condition ) statement executed if condition true • No semicolon needed after condition – Else conditional task not performed
  • 47. © 2003 Prentice Hall, Inc. All rights reserved. 47 2.8 Decision Making: Equality and Relational Operators • Upcoming program uses if statements – Discussion afterwards Standard algebraic equality or relational operator Java equality or relational operator Example of Java condition Meaning of 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.19 Equality and relational operators.
  • 48. © 2003 Prentice Hall, Inc. All rights reserved. Outline 48 Comparison.java 1. import 2. Class Comparison 2.1 main 2.2 Declarations 2.3 Input data (showInputDialo g) 2.4 parseInt 2.5 Initialize result 1 // Fig. 2.20: Comparison.java 2 // Compare integers using if statements, relational operators 3 // and equality operators. 4 5 // Java packages 6 import javax.swing.JOptionPane; 7 8 public class Comparison { 9 10 // main method begins execution of Java application 11 public static void main( String args[] ) 12 { 13 String firstNumber; // first string entered by user 14 String secondNumber; // second string entered by user 15 String result; // a string containing the output 16 17 int number1; // first number to compare 18 int number2; // second number to compare 19 20 // read first number from user as a string 21 firstNumber = JOptionPane.showInputDialog( "Enter first integer:" ); 22 23 // read second number from user as a string 24 secondNumber = 25 JOptionPane.showInputDialog( "Enter second integer:" ); 26 27 // convert numbers from type String to type int 28 number1 = Integer.parseInt( firstNumber ); 29 number2 = Integer.parseInt( secondNumber ); 30 31 // initialize result to empty String 32 result = ""; 33
  • 49. © 2003 Prentice Hall, Inc. All rights reserved. Outline 49 Comparison.java 3. if statements 4. showMessageDialo g 34 if ( number1 == number2 ) 35 result = result + number1 + " == " + number2; 36 37 if ( number1 != number2 ) 38 result = result + number1 + " != " + number2; 39 40 if ( number1 < number2 ) 41 result = result + "n" + number1 + " < " + number2; 42 43 if ( number1 > number2 ) 44 result = result + "n" + number1 + " > " + number2; 45 46 if ( number1 <= number2 ) 47 result = result + "n" + number1 + " <= " + number2; 48 49 if ( number1 >= number2 ) 50 result = result + "n" + number1 + " >= " + number2; 51 52 // Display results 53 JOptionPane.showMessageDialog( null, result, "Comparison Results", 54 JOptionPane.INFORMATION_MESSAGE ); 55 56 System.exit( 0 ); // terminate application 57 58 } // end method main 59 60 } // end class Comparison Test for equality, create new string, assign to result. Notice use of JOptionPane.INFORMATION_MESSAGE
  • 50. © 2003 Prentice Hall, Inc. All rights reserved. Outline 50 Program Output
  • 51. © 2003 Prentice Hall, Inc. All rights reserved. 51 2.8 Decision Making: Equality and Relational Operators – Lines 1-12: Comments, import JOptionPane, begin class Comparison and main – Lines 13-18: declare variables • Can use comma-separated lists instead: – Lines 21-30: obtain user-input numbers and parses input string into integer variables 13 String firstNumber, 14 secondNumber, 15 result;
  • 52. © 2003 Prentice Hall, Inc. All rights reserved. 52 2.8 Decision Making: Equality and Relational Operators – Initialize result with empty string – if statement to test for equality using (==) • If variables equal (condition true) – result concatenated using + operator – result = result + other strings – Right side evaluated first, new string assigned to result • If variables not equal, statement skipped 32 result = ""; 34 if ( number1 == number2 ) 35 result = result + number1 + " == " + number2;
  • 53. © 2003 Prentice Hall, Inc. All rights reserved. 53 2.8 Decision Making: Equality and Relational Operators – Lines 37-50: other if statements testing for less than, more than, etc. • If number1 = 123 and number2 = 123 – Line 34 evaluates true (if number1 = = number 2) • Because number1 equals number2 – Line 40 evaluates false (if number1 < number 2) • Because number1 is not less than number2 – Line 49 evaluates true (if number1 >= number2) • Because number1 is greater than or equal to number2 – Lines 53-54: result displayed in a dialog box using showMessageDialog
  • 54. © 2003 Prentice Hall, Inc. All rights reserved. 54 2.8 Decision Making: Equality and Relational Operators • Precedence of operators – All operators except for = (assignment) associates from left to right • For example: x = y = z is evaluated x = (y = z) Operators Associativity Type * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 2.21 Precedence and associativity of the operators discussed so far.
  • 55. © 2003 Prentice Hall, Inc. All rights reserved. 55 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement • Emphasize object-oriented programming (OOP) • Object-oriented design (OOD) implementation – Chapters 3 to 14, 16, 19 – Appendices D, E, F
  • 56. © 2003 Prentice Hall, Inc. All rights reserved. 56 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement • Program Goal – Software simulator application – 2-floor elevator simulator • Models actual elevator operation – Elevator graphics displayed to user – Graphical user interface (GUI) • User can control elevator
  • 57. © 2003 Prentice Hall, Inc. All rights reserved. 57 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement • Elevator Simulation – Model people using elevator – Elevator door, floor door, elevator button, floor button, elevator shaft, bell, floor, backgrounds • Operate accordingly or by request to avoid “injuring” person and make useless operations – Create person objects – Simulation rules • Elevator visits floor which person requests for elevator service • One person per elevator • 5 seconds to move from floors
  • 58. © 2003 Prentice Hall, Inc. All rights reserved. 58 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement • Application GUI – First Floor/Second Floor buttons create person on respective floors • Disable button if floor occupied by a person already • Unlimited number of passenger creations – Animation requirements • Passenger walking and pressing floor button • Elevator moving, doors opening and closing • Illumination of elevator lights and buttons during operation – Incorporating sounds • Footsteps when person walks • Button pressing clicks • Elevator bell rings upon elevator arrival, elevator music • Doors creak when opening and closing
  • 59. © 2003 Prentice Hall, Inc. All rights reserved. 59 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement
  • 60. © 2003 Prentice Hall, Inc. All rights reserved. 60 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement
  • 61. © 2003 Prentice Hall, Inc. All rights reserved. 61 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement
  • 62. © 2003 Prentice Hall, Inc. All rights reserved. 62 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement • Designing elevator system – Specified in requirements document through OOD analysis • UML • Design used to implement Java code – How system should be constructed to complete tasks • System Structure – System is a set of interactive components to solve problems • Simplified by subsystems – Simulator (through ch. 16), GUI (ch. 13 and 14, display (ch. 22) – Describes system’s objects and inter-relationships – System behavior describes how system changes through object interaction
  • 63. © 2003 Prentice Hall, Inc. All rights reserved. 63 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement • UML diagram types – System structure • Class diagram (section 3.7) – Models classes, or “building blocks” of a system – Person, elevator, floor, etc. • Object diagrams (section 3.7) – Snapshot (model) of system’s objects and relationships at specific point in time • Component diagrams (section 14.13) – Model components such as graphics resources and class packages that make up the system • Deployment diagrams (not discussed) – Model hardware, memory and runtime resources
  • 64. © 2003 Prentice Hall, Inc. All rights reserved. 64 2.9 (Optional Case Study) Thinking About Objects: Examining the Problem Statement – System behavior • Statechart diagrams (section 5.11) – Model how object changes state • Condition/behavior of an object at a specific time • Activity diagrams (section 5.11) – Flowchart modeling order and actions performed by object • Collaboration diagrams (section 7.10) – Emphasize what interactions occur • Sequence diagrams (section 16.11) – Emphasize when interactions occur • Use-case diagrams (section 13.17) – Represent interaction between user and system • Clicking elevator button