04 PD Intro To Java
04 PD Intro To Java
– Blank line
• Makes program more readable
• Blank lines, spaces, and tabs are white-space characters
– Ignored by compiler
– 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)
• Modifying programs
– Welcome2.java (Fig. 2.3) produces same output as
Welcome1.java (Fig. 2.1)
– Using different code
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
– 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!" );
• System.out.printf
– Method for displaying formatted data
– the f in the name printf stands for "formatted"
Welcome to
Java Programming!
– 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
• 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
• Visual Representation
– Sum = 0; number1 = 1; number2 = 2;
sum 0
sum 3
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
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
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.
Latihan