1 2 2 introduction to java applications. 2 2.1 introduction java application programming –display...

37
1 2 Introduction to Java Applications

Upload: juniper-wilcox

Post on 28-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

1

22

Introductionto Java Applications

Page 2: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

2

2.1 Introduction

• Java application programming– Display messages

– Obtain information from the user

– Arithmetic calculations

– Decision-making fundamentals

Page 3: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

3

2.2 First Program in Java: Printing a Line of Text

• Application– Executes when you use the java command

to launch the Java Virtual Machine (JVM)

• Sample program– Displays a line of text

– Illustrates several important Java language features

Page 4: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

4

2.2 First Program in Java: Printing a Line of Text (Cont.)

– 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.

Page 5: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

5

2.2 First Program in Java: Printing a Line of Text (Cont.)

– 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

3

4 public class Welcome1

Page 6: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

6

2.2 First Program in Java: Printing a Line of Text (Cont.)

– Java identifier• Series of characters consisting of letters, digits,

underscores ( _ ) and dollar signs ( $ )• Does not begin with a digit, has no spaces• Examples: Welcome1, $value, _value, button7

– 7button is invalid• Java is case sensitive (capitalization matters)

– a1 and A1 are different

– In chapters 2 to 7, use public class• Certain details not important now • Mimic certain features, discussions later

4 public class Welcome1

Page 7: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

7

2.2 First Program in Java: Printing a Line of Text (Cont.)

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

4 public class Welcome1

5 {

Page 8: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

8

2.2 First Program in Java: Printing a Line of Text (Cont.)

– Part of every Java application• Applications begin executing at main

– Parentheses indicate main is a method (Ch. 3 and 6)

– Java applications contain one or more methods

• Exactly one method must be called main

– Methods can perform tasks and return information• void means main returns no information

• For now, mimic main's first line

– Left brace begins body of method declaration• Ended by right brace } (line 11)

7 public static void main( String args[] )

8 {

Page 9: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

9

2.2 First Program in Java: Printing a Line of Text (Cont.)

– Instructs computer to perform an action• Prints string of characters

– String - series characters inside double quotes• White-spaces in strings are not ignored by compiler

– System.out• Standard output object• Print to command window (i.e., MS-DOS prompt)

– Method System.out.println • Displays line of text

– This line known as a statement• Statements must end with semicolon ;

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

Page 10: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

10

2.2 First Program in Java: Printing a Line of Text (Cont.)

– Ends method declaration

– Ends class declaration

– Can add comments to keep track of ending braces

11 } // end method main

13 } // end class Welcome1

Page 11: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

11

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

Page 12: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

12

2.3 Modifying Our First Java Program (Cont.)

• Escape characters– Backslash ( \ )

– Indicates special characters be output

• Newline characters (\n)– Interpreted as “special characters” by methods System.out.print and System.out.println

– Indicates cursor should be at the beginning of the next line

– Welcome3.java (Fig. 2.4)

– Line breaks at \n

9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

Page 13: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

13

Fig. 2.5 | Some common escape sequences.

Page 14: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

14

2.4 Displaying Text with printf

•System.out.printf– New feature of J2SE 5.0

– Displays formatted data

– Format string• Fixed text

• Format specifier – placeholder for a value

– Format specifier %s – placeholder for a string

– Other format specifiers

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

Page 15: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

15

 Formatting Output with printf

•printf– Precise output formatting

• Conversion specifications: flags, field widths, precisions, etc.

– Can perform • rounding• aligning columns• right/left justification• inserting literal characters• exponential format• octal and hexadecimal format• fixed width and precision• date and time format

Page 16: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

16

  Formatting Output with printf (Cont.)

• Format String– Describe the output format

– Consist of fixed text and format specifier

• Format specifier– Placeholder for a value

– Specify the type of data to output

– Begins with a percent sign (%) and is followed by a conversion character

• E.g., %s, %d

– Optional formatting information• Argument index, flags, field width, precision

• Specified between % and conversion character

Page 17: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

17

 Printing Integers

• Integer– Whole number (no decimal point): 25, 0, -9– Positive, negative, or zero– Only minus sign prints by default (later we shall

change this)

• Format– printf( format-string, argument-list );– format-string

• Describe the output format

– argument-list• Contain the value corresponding to each format

specifier

Page 18: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

18

Integer conversion characters.

• View demonstration program Fig. 28.3– Note output of positive, negative numbers

– Note octal (base 8) and hexadecimal (base 16) options

Page 19: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

19

  Printing Floating-Point Numbers

• Floating Point Numbers– Have a decimal point (33.5)

– Computerized scientific notation (exponential notation)• 150.4582 is 1.504582 x 10² in scientific

• 150.4582 is 1.504582e+02 in exponential (e stands for exponent)

• use e or E

– f – print floating point with at least one digit to left of decimal

– g (or G) - prints in f or e (E) • Use exponential if the magnitude is less than 10-3, or

greater than or equal to 107

Page 20: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

20

Floating-point conversion characters.

• View program using printf for floating point numbers, Figure 28.4

Conversion character Description

e or E Display a floating-point value in exponential notation. When conversion character E is used, the output is displayed in uppercase letters.

F Display a floating-point value in decimal format.

g or G Display a floating-point value in either the floating-point format f or the exponential format e based on the magnitude of the value. If the magnitude is less than 10–3, or greater than or equal to 107, the floating-point value is printed with e (or E). Otherwise, the value is printed in format f. When conversion character G is used, the output is displayed in uppercase letters.

a or A Display a floating-point number in hexadecimal format. When conversion character A is used, the output is displayed in uppercase letters.

Conversion character Description

e or E Display a floating-point value in exponential notation. When conversion character E is used, the output is displayed in uppercase letters.

F Display a floating-point value in decimal format.

g or G Display a floating-point value in either the floating-point format f or the exponential format e based on the magnitude of the value. If the magnitude is less than 10–3, or greater than or equal to 107, the floating-point value is printed with e (or E). Otherwise, the value is printed in format f. When conversion character G is used, the output is displayed in uppercase letters.

a or A Display a floating-point number in hexadecimal format. When conversion character A is used, the output is displayed in uppercase letters.

Page 21: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

21

Printing Strings and Characters

• Conversion character c and C– Require char

– C displays the output in uppercase letters

• Conversion character s and S– String

– Object• Implicitly use object’s toString method

– S displays the output in uppercase letters

• View program demonstrating character conversion with printf, Fig. 28.5

Page 22: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

22

Printing with Field Widths and Precisions

• Field width– Size of field in which data is printed

– If width larger than data, default right justified• If field width too small, increases to fit data

• Minus sign uses one character position in field

– Integer width inserted between % and conversion specifier

• E.g., %4d – field width of 4

– Can be used with all format specifiers except the line separator (%n)

• View program demonstrating field width, Fig. 28.12

Page 23: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

23

Printing with Field Widths and Precisions

• Precision– Meaning varies depending on data type– Floating point

• Number of digits to appear after decimal (e or E and f)• Maximum number of significant digits (g or G)

– Strings• Maximum number of characters to be written from

string

– Format• Use a dot (.) then precision number after %

e.g., %.3f

• View program demonstrating precision, Fig. 28.13

Page 24: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

24

Printing with Field Widths and Precisions

• Field width and precision– Can both be specified

• %width.precision

%5.3f

– Negative field width – left justified

– Positive field width – right justified

– Precision must be positive• Example:

printf( "%9.3f", 123.456789 );

Page 25: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

25

2.5 Another Java Application: Adding Integers

• Program Fig. 2.7 to do keyboard input– Use Scanner to read two integers from user

– Use printf to display sum of the two values

– Use packages

Page 26: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

26

2.5 Another Java Application: Adding Integers (Cont.)

– import declarations • Used by compiler to identify and locate classes used in

Java programs

• Tells compiler to load class Scanner from java.util package

– Begins public class Addition• Recall that file name must be Addition.java

– Lines 8-9: begins main

3 import java.util.Scanner; // program uses class Scanner

5 public class Addition 6 {

Page 27: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

27

2.5 Another Java Application: Adding Integers (Cont.)

– Variable Declaration Statement– Variables

• Location in memory that stores a value– Declare with name and type before use

• Input is of type Scanner – Enables a program to read data for use

• Variable name: any valid identifier

– Declarations end with semicolons ;– Initialize variable in its declaration

• Equal sign• Standard input object

– System.in

10 // create Scanner to obtain input from command window11 Scanner input = new Scanner( System.in );

Page 28: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

28

2.5 Another Java Application: Adding Integers (Cont.)

– Declare variable number1, number2 and sum of type int• int holds integer values (whole numbers): i.e., 0, -4, 97

• Types float and double can hold decimal numbers

• Type char can hold a single character: i.e., x, $, \n, 7

• int, float, double and char are primitive types

– Can add comments to describe purpose of variables

– Can declare multiple variables of the same type in one declaration

– Use comma-separated list

13 int number1; // first number to add14 int number2; // second number to add15 int sum; // second number to add

int number1, // first number to add number2, // second number to add sum; // second number to add

Page 29: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

29

2.5 Another Java Application: Adding Integers (Cont.)

– Message called a prompt - directs user to perform an action

– Package java.lang

– Result of call to nextInt given to number1 using assignment operator =

• Assignment statement• = binary operator - takes two operands

– Expression on right evaluated and assigned to variable on left

• Read as: number1 gets the value of input.nextInt()

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

18 number1 = input.nextInt(); // read first number from user

Page 30: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

30

2.5 Another Java Application: Adding Integers (Cont.)

– Similar to previous statement• Prompts the user to input the second integer

– Similar to previous statement• Assign variable number2 to second integer input

– 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

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

21 number2 = input.nextInt(); // read second number from user

23 sum = number1 + number2; // add numbers

Page 31: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

31

2.5 Another Java Application: Adding Integers (Cont.)

– Use System.out.printf to display results

– Format specifier %d• Placeholder for an int value

– Calculations can also be performed inside printf

– Parentheses around the expression number1 + number2 are not required

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

System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );

Page 32: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

32

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

Page 33: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

33

2.7 Arithmetic

• Arithmetic calculations used in most programs

– Usage • * for multiplication

• / for division

• % for remainder

• +, -

– Integer division truncates remainder7 / 5 evaluates to 1

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

Page 34: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

34

Fig. 2.11 | Arithmetic operators.

Page 35: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

35

2.7 Arithmetic (Cont.)

• 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

Page 36: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

36

Fig. 2.12 | Precedence of arithmetic operators.

Operator(s) Operation(s) Order of evaluation (precedence)

*

/

%

Multiplication

Division

Remainder

Evaluated first. If there are several operators of this type, they are evaluated from left to right.

+

-

Addition

Subtraction

Evaluated next. If there are several operators of this type, they are evaluated from left to right.

Page 37: 1 2 2 Introduction to Java Applications. 2 2.1 Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic

37

Operator Precedence Chart

Hierarchy of Java operators with the highest precedence shown first.• Expressions inside parentheses are evaluated first; nested parentheses are evaluated from the innermost parentheses to the outer. • Operators in the same row in the chart have equal precedence.

Operator Type Order of Evaluation

(   )   [   ]    .

ParenthesesArray subscriptMember access

left to right

++   -- Prefix increment, decrement

right to left

++   -- - Postfix increment, decrementUnary minus

right to left

*   /   % Multiplicative left to right

+   - Additive left to right

<   >   <=   >= Relational left to right

==   != Equality left to right

&& And left to right

|| Or left to right

?   : Conditional right to left

=   +=   -=   *=   /=   %=

Assignment right to left