04 PD Intro To Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

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 using Printf
2.5 Another Java Application: Adding Integers
2.6 Memory Concepts
2.7 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 // Fig. 2.1: Welcome1.java Outline
2 // Text-printing program.
3
Welcome1.java
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! Program Output

 2003 Prentice Hall, Inc.


All rights reserved.
4
2.2 A First Program in Java: Printing a
Line of Text
1 // Fig. 2.1: Welcome1.java

– Comments start with: //


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

– Another line of comments


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

 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 A Simple Program: Printing a Line of
Text
4 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 A Simple Program: Printing a Line of
Text
4 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 A Simple Program: Printing a Line of
Text
7 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 A Simple Program: Printing a Line of
Text
9 System.out.println( "Welcome to Java Programming!" );

– Instructs computer to perform an action


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

 2003 Prentice Hall, Inc. All rights reserved.


10
2.2 A Simple Program: Printing a Line of
Text
11 } // 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 System.out.print( "Welcome to " );


10 System.out.println( "Java Programming!" );

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


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

 2003 Prentice Hall, Inc. All rights reserved.


15
1 // Fig. 2.3: Welcome2.java Outline
2 // Printing a line of text with multiple statements.
3
4 public class Welcome2 { Welcome2.java
5
6 // main method begins execution of Java application 1. Comments
7 public static void main( String args[] )
8 {
2. Blank line
9 System.out.print( "Welcome to " );
10 System.out.println( "Java Programming!" );
11 3. Begin class
12 } // end method main Welcome2
13
14 } // end 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

5. end main,
Welcome2
Welcome to Java Programming!

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 // Fig. 2.4: Welcome3.java
2 // Printing multiple lines of text with a single statement.
3 Welcome3.java
4 public class Welcome3 {
5 1. main
6 // main method begins execution of Java application
7 public static void main( String args[] )
2.
8 {
9 System.out.println( "Welcome\nto\nJava\nProgramming!" );
System.out.prin
10 tln (uses \n for new
11 } // end method main line)
12
13 } // end class Welcome3

Welcome Program Output


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 Description
sequence
\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
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 Displaying Text with printf


1 // Fig. 2.6: Welcome4.java
2 // Printing multiple lines in a dialog box.
3
4 public class Welcome4
5 {
6 // main method begins execution of Java application
7 public static void main( String args[] )
8 {
9 System.out.printf( "%s\n%s\n",
10 "Welcome to", "Java Programming!" );
11
12 } // end method main
13
14 } // 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 comma-
separated 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 import java.util.Scanner; // program uses class Scanner
4 24
5 public class Addition
Outline
6 {
7 // main method begins execution of Java application Addition.java
8 public static void main( String args[] )
9 { 1. import
10 // create Scanner to obtain input from command window
11 Scanner input = new Scanner( System.in ); 2. class Addition
12
13 int number1; // first number to add 2.1 Declare variables
14 int number2; // second number to add (name and type)
15 int sum; // sum of number1 and number2
16 3.
showInputDialog
17 System.out.print( "Enter first integer: " ); // prompt
18 number1 = input.nextInt(); // read first number from user
4. parseInt
19
20 System.out.print( "Enter second integer: " ); // prompt
5. Add numbers, put
21 number2 = input.nextInt(); // read second number from user result in sum
22
23 sum = number1 + number2; // add numbers
24
25 System.out.printf( "Sum is %d\n", sum ); // display sum
26
27 } // end method main
28
 2003 Prentice Hall, Inc.
29 } // end class Addition
All rights reserved.
25
Outline

Enter first integer: 45


Enter second integer: 72 Program output
Sum is 117

 2003 Prentice Hall, Inc.


All rights reserved.
26
2.5 Another Java Application: Adding
Integers
5 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 int number1; // first number to add
16 int number2; // second number to add
17 int sum; // 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 Another Java Application: Adding
Integers
17 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 Another Java Application: Adding
Integers
20 sum = number1 + number2;

– 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

25 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 3

 2003 Prentice Hall, Inc. All rights reserved.


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 Arithmetic

Op era tor(s) Op era tion(s) Ord er of eva lua tion (p rec ed enc e)
* Multiplication Evaluated first. If there are several of this type
/ Division of operator, they are evaluated from left to
Remainder right.
+ Addition Evaluated next. If there are several of this type
- Subtraction of operator, they are evaluated from left to
right.
Fig. 2.17 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.

You might also like