Chapter 2 - Introduction to Java Applications

1 Chapter 2 - Introduction to Java Applications Outline 2.1 2.2 2.3 2.4 2.5 2.6 2.7 Introduction A First Program in Java: Printing a Line of Text Mo...
Author: Gabriel Barber
5 downloads 0 Views 475KB Size
1

Chapter 2 - Introduction to Java Applications Outline 2.1 2.2 2.3 2.4 2.5 2.6 2.7

Introduction A First Program in Java: Printing a Line of Text Modifying Our First Java Program Displaying Text using Printf Another Java Application: Adding Integers Memory Concepts Arithmetic

 2003 Prentice Hall, Inc. All rights reserved.

2

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.

3 1 2 3 4 5 6 7 8 9 ); 10 11 12 13

// Fig. 2.1: Welcome1.java // Text-printing program. public class Welcome1 {

Outline Welcome1.java

// main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome to Java Programming!"

} // end method main } // end class Welcome1

Welcome to Java Programming!

Program Output

 2003 Prentice Hall, Inc. All rights reserved.

4

2.2 1

A First Program in Java: Printing a Line of Text

// Fig. 2.1: Welcome1.java

– Comments start with: // • Comments ignored during program execution • Document and describe code • Provides code readability

– Traditional comments: /* ... */ /* This is a traditional comment. It can be split over many lines */ 2

// Text-printing program.

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

 2003 Prentice Hall, Inc. All rights reserved.

5

2.2

A Simple Program: Printing a Line of Text

3

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

public class Welcome1 {

– Begins class declaration for class Welcome1 • Every Java program has at least one user-defined class • Keyword: words reserved for use by Java – class keyword followed by class name • Naming classes: capitalize every word – SampleClassName  2003 Prentice Hall, Inc. All rights reserved.

6

2.2 4

A Simple Program: Printing a Line of Text public class Welcome1 {

– 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

 2003 Prentice Hall, Inc. All rights reserved.

7

2.2 4

A Simple Program: Printing a Line of Text public class Welcome1 {

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

public static void main( String args[] )

– Part of every Java application • Applications begin executing at main – Parenthesis indicate main is a method – Java applications contain one or more methods  2003 Prentice Hall, Inc. All rights reserved.

8

2.2 7

A Simple Program: Printing a Line of Text public static void main( String args[] )

• Exactly one method must be called main

– Methods can perform tasks and return information • void means main returns no information • For now, mimic main's first line 8

{

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

 2003 Prentice Hall, Inc. All rights reserved.

9

2.2 9

A Simple Program: Printing a Line of Text System.out.println( "Welcome to Java Programming!" );

– Instructs computer to perform an action • Prints string of characters – String - series characters inside double quotes • White-spaces in strings are not ignored by compiler

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

– Method System.out.println • Displays line of text • Argument inside parenthesis

– This line known as a statement • Statements must end with semicolon ;  2003 Prentice Hall, Inc. All rights reserved.

10

2.2 11

A Simple Program: Printing a Line of Text } // end method main

– Ends method declaration 13

– – – –

} // end class Welcome1

Ends class declaration Can add comments to keep track of ending braces Remember, compiler ignores comments Comments can start on same line after code

 2003 Prentice Hall, Inc. All rights reserved.

11

2.2

A Simple Program: Printing a Line of Text

• Compiling a program – If no errors, Welcome1.class created • Has bytecodes that represent application • Bytecodes passed to Java interpreter

 2003 Prentice Hall, Inc. All rights reserved.

12

2.2

A Simple Program: Printing a Line of Text

• Executing a program • 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.

13

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.

14

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 9 10

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

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

 2003 Prentice Hall, Inc. All rights reserved.

15 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Outline

// Fig. 2.3: Welcome2.java // Printing a line of text with multiple statements.

Welcome2.java

public class Welcome2 { // main method begins execution of Java application public static void main( String args[] ) { System.out.print( "Welcome to " ); System.out.println( "Java Programming!" ); } // end method main } // end class Welcome2

1. Comments 2. Blank line 3. Begin class Welcome2

3.1 Method main System.out.print keeps the cursor on the same line, so System.out.println 4. Method continues on the same line. System.out.prin t 4.1 Method System.out.prin tln

Welcome to Java Programming!

5. end main, Welcome2 Program Output  2003 Prentice Hall, Inc. All rights reserved.

16

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

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

– Line breaks at \n

• Usage – Can use in System.out.println or System.out.print to create new lines • System.out.println( "Welcome\nto\nJava\nProgramming!" );  2003 Prentice Hall, Inc. All rights reserved.

17

Outline 1 2 3 4 5 6 7 8 9 10 11 12 13

// Fig. 2.4: Welcome3.java // Printing multiple lines of text with a single statement.

Welcome3.java public class Welcome3 {

1. main // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome\nto\nJava\nProgramming!" ); } // end method main

2. System.out.prin tln (uses \n for new line)

} // end class Welcome3

Program Output

Welcome to Java Programming!

Notice how a new line is output for each \n escape sequence.  2003 Prentice Hall, Inc. All rights reserved.

18

2.3

Modifying Our First Java Program

Escape characters – Backslash ( \ ) – Indicates special characters be output Escape sequence \n

Description

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 exampl e, System.out.println( " \ "in quotes \ "" ); displays "in quotes" Fig. 2.5 Some common escape sequences.  2003 Prentice Hall, Inc. All rights reserved.

19

2.4

Displaying Text with printf

• System.out.printf – Method for displaying formatted data – the f in the name printf stands for "formatted"

 2003 Prentice Hall, Inc. All rights reserved.

20

2.4 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Displaying Text with printf

// Fig. 2.6: Welcome4.java // Printing multiple lines in a dialog box. public class Welcome4 { // main method begins execution of Java application public static void main( String args[] ) { System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!" ); } // end method main } // end class Welcome4

Welcome to Java Programming!

 2003 Prentice Hall, Inc. All rights reserved.

21

2.4

Displaying Text with printf

9

System.out.printf( "%s\n%s\n",

10

"Welcome to", "Java Programming!" );

– The method call specifies three arguments. – When a method requires multiple arguments, the arguments are separated with commas (,) this is known as a commaseparated list. – Remember that all statements in Java end with a semicolon (;)  Therefore, lines 9/10 represent only one statement. – Java allows large statements to be split over many lines.

 2003 Prentice Hall, Inc. All rights reserved.

22

2.4

Displaying Text with printf

9

System.out.printf( "%s\n%s\n",

10

"Welcome to", "Java Programming!" );

• Method printf's first argument is a format string that may consist of fixed text and format specifiers. • Fixed text is output by printf just as it would be output by print or println. Each format specifier is a placeholder for a value and specifies the type of data to output. • Format specifiers begin with a percent sign (%) and are followed by a character that represents the data type. – For example, the format specifier %s is a placeholder for a string. The format string in line 9 specifies that printf should output two strings and that each string should be followed by a newline character.

 2003 Prentice Hall, Inc. All rights reserved.

23

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.

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

import java.util.Scanner; // program uses class Scanner 24 public class Addition { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user

Outline 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

sum = number1 + number2; // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum } // end method main } // end class Addition

 2003 Prentice Hall, Inc. All rights reserved.

25

Outline

Enter first integer: 45 Enter second integer: 72 Sum is 117

Program output

 2003 Prentice Hall, Inc. All rights reserved.

26

2.5 5

Another Java Application: Adding Integers

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

– Location of JOptionPane for use in the program 7

public class Addition {

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

– Lines 10-11: main 15 16 17

int number1; int number2; int sum;

// first number to add // second number to add // sum of number1 and number2

– 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  2003 Prentice Hall, Inc. All rights reserved.

27

2.5 17

Another Java Application: Adding Integers

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

– Uses System.out.print to display the message "Enter first integer:" 18

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

– Uses Scanner object input's nextInt method to obtain an integer from the user. At this point the program waits for the user to type the number and press the Enter key to submit the number.

 2003 Prentice Hall, Inc. All rights reserved.

28

2.5 20

Another Java Application: Adding Integers

sum = number1 + number2;

– Assignment statement • • • • 25

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

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

• Displays "Sum is", followed by the value of sum

 2003 Prentice Hall, Inc. All rights reserved.

29

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.

30

2.6 Memory Concepts • Visual Representation – Sum = 0; number1 = 1; number2 = 2; sum

0

– Sum = number1 + number2; after execution of statement

sum

 2003 Prentice Hall, Inc. All rights reserved.

3

31

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.

32

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.

33

2.7 Op era tor(s) * / + Fig. 2.17

Op era tion(s) Multiplication Division Remainder Addition Subtraction

Arithmetic

Ord er of eva lua tion (p rec ed enc e) Evaluated first. If there are several of this type of operator, they are evaluated from left to right. Evaluated next. If there are several of this type of operator, they are evaluated from left to right. Prec ed enc e o f a rithm etic o p era tors.

 2003 Prentice Hall, Inc. All rights reserved.

34

Latihan • Buatlah aplikasi menggunakan Java NetBeans untuk menghitung luas persegi panjang • Buatlah aplikasi menggunakan Java NetBeans untuk mengubah jam dan menit yang diinput ke dalam satuan detik. • Buatlah aplikasi menggunakan Java NetBeans untuk menghitung luas lingkaran.

 2003 Prentice Hall, Inc. All rights reserved.