2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to...

58
2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive Data Types and Operations
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    214
  • download

    0

Transcript of 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to...

Page 1: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

1

Introduction to Computers and Programming in JAVA: V22.0002

Primitive Data Types and Operations

Page 2: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

2

Primitive Data Types and Operations

• Identifiers, Variables, and Constants• Primitive Data Types

– byte, short, int, long, float, double, char, boolean

• Expressions• Mathematical Operators• Syntax Errors, Runtime Errors, and Logic Errors

Page 3: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

3

Reserved words:

Certain words have special meaning in Java and cannot be used as identifiers. These words are called reserved words.

So far we have seen the following reserved words:

public

import

static

void

class

We will see a complete list of reserved words soon.

Use of the words null, true and false is also prohibited.

Page 4: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

4

Lets review Identifiers

• An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).

• An identifier must start with:– a letter– an underscore (_)– or a dollar sign ($).

• It cannot start with a digit. • An identifier cannot be a reserved word.

– (See Appendix A, “Java Keywords,” for a list of reserved words).

• An identifier cannot be true, false, or null.• An identifier can be of any length.

Page 5: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

5

Programming Style and Documentation

• Appropriate Comments

• Naming Conventions

• Proper Indentation and Spacing Lines

• Block Styles

Page 6: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

6

Appropriate Comments

Include a comment at the beginning of each program:– to explain what the program does– its key features– its supporting data structures– and any unique techniques it uses.

• Include your name• class section• instruction• date• and a brief description at the beginning of the

program.

Page 7: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

7

Proper Indentation and Spacing

• Indentation– Indent two spaces.

• Spacing – Use blank line to separate segments of the code.

Page 8: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

8

Block Styles

Use a consistent style for braces.

  public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } }

public class Test { public static void main(String[] args) {

System.out.println("Block Styles"); } }

End-of-line style

Next-line style

Page 9: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

9

Programming Errors

• Syntax Errors– Detected by the compiler

• Runtime Errors– Causes the program to abort

• Logic Errors– Produces incorrect result

Page 10: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

10

Syntax Errors

• Caused when the compiler cannot recognize a statement.

• These are violations of the language

• The compiler normally issues an error message to help the programmer locate and fix it

• Also called compile errors or compile-time errors.

• For example, if you forget a semi-colon, you will get a syntax error.

Page 11: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

11

Run-time Errors

• These occur once a program is running; typically it will “crash” or simply abort.

• The compiler cannot identify these errors at compile time.

• For example, a statement which calls for division by zero causes a run-time error: the compiler would not detect it but the program cannot run in this case.

Page 12: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

12

Naming Conventions

• Choose meaningful and descriptive names.• For Variables, class names and methods:

– Use lowercase.

– If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name.

– For example, the variables radius and area, and the method computeArea.

Page 13: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

13

Naming Conventions, cont.

• Class names: – Capitalize the first letter of each word in the

name. For example, the class name ComputeArea.

• Constants: – Capitalize all letters in constants. For

example, the constant PI.

Page 14: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

14

Variables

Page 15: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

15

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, it replaces (and destroys) the previous value

– Reading variables from memory does not change them

Page 16: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

16

Bucket Analogy

• It is useful to think of a variable as a bucket of data.

• The bucket has a unique name, and can only hold certain kinds of data.

balance

200

balance is a variablecontaining the value200, and can containonly integers.

Page 17: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

17

Memory Concepts

• Visual Representation– sum = 0;

– sum = 3;

– sum = 2;

– Sum = number1 + number2; after execution of statement

sum 0

sum 3

sum 2

Page 18: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

18

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.

Page 19: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

19

Arithmetic

• Arithmetic calculations used in most programs– Usage

• * for multiplication

• / for division

• +, -• No operator for exponentiation

• Integer division truncates remainder

7 / 5 evaluates to 1

– The Remainder operator: % returns the remainder 7 % 5 evaluates to 2

Page 20: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

20

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 (aka “Please excuse my dear Aunt Sally”)

Page 21: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

21

Variable Declaration

• Java is a “strongly typed” language.

• Before you use a variable, you must declare it.

• Examples:

/* Creates an integer variable */

int number;

/* Creates a float variable */

float price;

/* Creates a character variable */

char letter;

Page 22: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

22

Declaring Variables

int x; // Declare x to be an // integer variable;

double radius; // Declare radius to // be a double variable;

char a; // Declare a to be a // character variable;

Page 23: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

23

Data Types:• integers: the simplest data type in Java. They are

used to hold positive and negative whole numbers, e.g. 5, 25, -777, 1.

• doubles: Used to hold fractional or decimal values, e.g. 3.14, 10.25.

• chars: Used to hold individual characters, e.g. ‘c’, ‘e’, ‘1’, ‘\n’

• We will explore each one in detail later this semester as well as some additional primitive data types.

Page 24: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

24

Declaring and Initializingin One Step

• int x = 1;

• double d = 1.4;

• float f = 1.4;

Page 25: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

25

Numerical Data Types

byte 8 bits

short 16 bits

int 32 bits

long 64 bits

float 32 bits

double 64 bits

Page 26: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

26

Assignment Statements

x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;

a = 'A'; // Assign 'A' to a;

Page 27: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

27

Important Point about Declarations

• You must make a declaration immediately following the left brace following the main method.– at the beginning of a function and before any executable

statements or else you get a syntax error.{declaration section…statement section…

}

Page 28: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

28

Example 1: Basic Arithmetic

/* Illustrates Integer Variables */public class addition {

public static void main(String[] args) { int x, y, z;

// Specify values of x and y x = 2; y = 3; // add x and y and place the result in z variablez = x + y;System.out.println("x has a value of " + x); System.out.println("y has a value of " + y); System.out.println("The sum of x + y is " + z); System.exit(0); }

}

Variable Declaration

Assignment Statements

Page 29: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

29

Printing Variables

• To print a variable, use the System.out.print or System.out.println statement as you would for a string.

• System.out.print (x);• System.out.println (x);• System.out.println ("x: " + x);

• Here the “+” symbol is for string concatenation.

Page 30: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

30

Assignment Statements

• Assignments statements enable one to initialize variables or perform basic arithmetic.

x = 2;y = 3;z = x + y;

• Here, we simply initialize x and y and store their sum within the variable z.

Page 31: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

31

Assignment Operator

• =• Read the assignment operator as “GETS” not

“EQUALS!”• This is an assignment of what’s on the right side

of = to a variable on the left• eg sum = integer1 + integer2;

– Read this as, “sum gets integer1 + integer2”

– integer1 and integer2 are added together and stored in sum

Page 32: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

32

Assignment Operators

• Given the following:

x = 2;

x = x + 1;

System.out.println ("x: " + x);• There are actually several ways to rewrite this

more concisely.

Page 33: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

Short Cut Operator

• One option is to use the += operator

x = 2;

x += 1; // same as x = x + 1;

System.out.println ("x: " + x);• There are similar operators for *, -, /.%

– x = x * 5 is equivalent to x *= 5;– x = x – 5; is equivalent to x -= 5;– x = x / 5; is equivalent to x /= 5;– x = x % 5; is equivalent to x %= 5;

• Good Practice: place a space before and after your short cut operators.

Page 34: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

Increment Operator

• A second option is to use an increment operator:

x++ Post-Increment Operator

++x Pre-Increment Operator• Both operators will increment x by 1, but they do

have subtle differences.

Page 35: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

Pre v. Post Increment

• PostIncrement Operator (x++):– use the current value of x in the expression.

Then, increment by 1.• PreIncrement Operator (++x):

– Increment x by 1. Then, use the new value of x in the expression.

Page 36: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

How about a real example?

// Preincrementing v. PostIncrementing public class PrePost{

public static void main (String[] args){

int c = 5;System.out.println (c);System.out.println (c++);System.out.println (c);System.out.println();c = 5;System.out.println (c);System.out.println (++c);System.out.println (c);

}}

Output:

5

5

6

5

6

6

Post Increment

Pre Increment 2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth

Page 37: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

Pre v. Post Decrement

• PostDecrement Operator (x--):– use the current value of x in the expression.

Then, decrease by 1.• PreDecrement Operator (--x):

– Decrease x by 1. Then, use the new value of x in the expression.

• Good practice: Place unary operators directly next to their operands, with no intervening spaces.

Page 38: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

38

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)

Page 39: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

39

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

Page 40: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc.All rights reserved.

40

welcome3.java

1. import declaration

2. Class Welcome4

2.1 main

2.2 showMessageDialog

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, "Welcome\nto\nJava\nProgramming!" );

10

11 System.exit( 0 ); // terminate the program

12 }

1 // welcome3.java2 // Printing multiple lines in a dialog box.3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane6 7 public class welcome3 {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" );14 15 System.exit( 0 ); // terminate application with window16 17 } // end method main18 19 } // end class welcome3

Page 41: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

41

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

Page 42: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

42

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, "Welcome\nto\nJava\nProgramming!" );

Page 43: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

43

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

Page 44: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

44

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 welcome3 and main

15 System.exit( 0 ); // terminate application with window

Page 45: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

45

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

Page 46: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc.All rights reserved.

46

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 // Addition.java2 // Addition program that displays the sum of two numbers.3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane6 7 public class Addition {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user14 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number218 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 int27 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.

Page 47: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc.All rights reserved.

47

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 window38 39 } // end method main40 41 } // end class Addition

Page 48: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

48

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

Page 49: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

49

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

Page 50: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

50

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

Page 51: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

51

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

Page 52: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

52

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

Page 53: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

53

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

Page 54: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

54

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;

Page 55: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

55

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

Page 56: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

56

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

Page 57: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

57

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.

Page 58: 2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved. 1 Introduction to Computers and Programming in JAVA: V22.0002 Primitive.

2003 Prentice Hall, Inc. Modified for use with this class. All rights reserved.

58

Memory Concepts

• Variable names correspond to locations in the computer’s primary memory.

• Every variable has:– a name

– a type

– and a value.

• When a value is placed in a memory location the value replaces the previous value in that location (called destructive read-in)

• A variable’s value can just be used and not destroyed (called non-destructive read-out)