02 - java fundamentals

76
Object Oriented Programming Mihai Dascălu 2CB, 2013 - 2014

Upload: maria-igescu

Post on 27-Sep-2015

280 views

Category:

Documents


2 download

TRANSCRIPT

  • Object Oriented Programming Mihai Dasclu

    2CB, 2013 - 2014

  • Programming Style and Documentation Appropriate Comments

    Naming Conventions

    Proper Indentation and Spacing Lines

    Block Styles

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    2

  • Appropriate Comments /* Include a summary at the beginning of the

    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, teaching

    //assistant, date, and a brief description at the

    //beginning of the program

    // strategic (before, overall) vs. tactical (intended for single lines of code can make code unreadable)

    // include copyright information

    // add descriptive information before function

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    3

  • Naming Conventions Choose meaningful and descriptive names

    Variables and method names: 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.

    Class names: Capitalize the first letter of each word in the name. For

    example, the class name ComputeArea.

    Constants: Capitalize all letters in constants, and use underscores to

    connect words. For example, the constant PI and MAX_VALUE

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    4

  • Proper Indentation and Spacing Indentation

    Indent two spaces (or \t in Eclipse / NetBeans)

    Spacing Use blank line to separate segments of the code

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    5

  • Block Styles Next-line & End-of-line

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    6

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

    }

    }

  • Programming Errors Syntax Errors

    Detected by the compiler

    Runtime Errors Causes the program to abort

    Logic Errors Produces incorrect result

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    7

  • Syntax Errors

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    8

    public class ShowSyntaxErrors {

    public static void main(String[] args) {

    i = 30;

    System.out.println(i + 4);

    }

    }

  • Runtime Errors

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    9

    public class ShowRuntimeErrors {

    public static void main(String[] args) {

    int i = 1 / 0;

    }

    }

  • Logic Errors

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    10

    public class ShowLogicErrors {

    // Determine if a number is between 1 and 100 inclusively

    public static void main(String[] args) {

    // Prompt the user to enter a number

    String input = JOptionPane.showInputDialog(null,

    "Please enter an integer:",

    "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE);

    int number = Integer.parseInt(input);

    // Display the result

    System.out.println("The number is between 1 and 100, " +

    "inclusively? " + ((1 < number) && (number < 100)));

    System.exit(0);

    }

    }

  • Debugging Bugs = logic errors are called

    Debugging = the process of finding and correcting errors

    Common approach -> use a combination of methods to narrow down to the part of the program where the bug is located Hand-trace the program (i.e., catch errors by reading

    the program) Insert print statements in order to show the values of

    the variables or the execution flow of the program This approach might work for a short, simple program.

    But for a large, complex program, the most effective approach for debugging is to use a debugger utility. Ob

    ject

    Orr

    ient

    ed P

    rogr

    amm

    ing

    11

  • Debugger A program that facilitates debugging & used to:

    Execute a single statement at a time Trace into or stepping over a method Set breakpoints Display variables Display call stack Modify variables

    http://www.vogella.com/articles/EclipseDebugging/article.html

    https://netbeans.org/features/java/debugger.html

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    12

  • Elementary programming

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    13

  • Trace a Program Execution public class ComputeArea {

    /** Main method */

    public static void main(String[] args) {

    double radius;

    double area;

    // Assign a radius

    radius = 20;

    // Compute area

    area = radius * radius * 3.14159;

    // Display results

    System.out.println("The area for the circle of radius " +

    radius + " is " + area);

    }

    }

    14

    no value radius

    allocate memory for radius

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Trace a Program Execution public class ComputeArea {

    /** Main method */

    public static void main(String[] args) {

    double radius;

    double area;

    // Assign a radius

    radius = 20;

    // Compute area

    area = radius * radius * 3.14159;

    // Display results

    System.out.println("The area for the circle of radius " +

    radius + " is " + area);

    }

    }

    15

    no value radius

    memory

    no value area

    allocate memory for area

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Trace a Program Execution public class ComputeArea {

    /** Main method */

    public static void main(String[] args) {

    double radius;

    double area;

    // Assign a radius

    radius = 20;

    // Compute area

    area = radius * radius * 3.14159;

    // Display results

    System.out.println("The area for the circle of radius " +

    radius + " is " + area);

    }

    }

    16

    20 radius

    no value area

    assign 20 to radius

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Trace a Program Execution public class ComputeArea {

    /** Main method */

    public static void main(String[] args) {

    double radius;

    double area;

    // Assign a radius

    radius = 20;

    // Compute area

    area = radius * radius * 3.14159;

    // Display results

    System.out.println("The area for the circle of radius " +

    radius + " is " + area);

    }

    }

    17

    20 radius

    memory

    1256.636 area

    compute area and assign it to variable area

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Trace a Program Execution public class ComputeArea {

    /** Main method */

    public static void main(String[] args) {

    double radius;

    double area;

    // Assign a radius

    radius = 20;

    // Compute area

    area = radius * radius * 3.14159;

    // Display results

    System.out.println("The area for the circle of radius " +

    radius + " is " + area);

    }

    }

    18

    20 radius

    memory

    1256.636 area

    print a message to the console

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Reading Input from the Console Create a Scanner object Scanner input = new Scanner(System.in);!

    Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example,!System.out.print("Enter a double value: ");!

    Scanner input = new Scanner(System.in);!double d = input.nextDouble(); Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    19

  • Getting Input from Input Dialog Boxes String input =

    JOptionPane.showInputDialog( "Enter an input");

    String string = JOptionPane.showInputDialog(null, Prompting Message, Dialog Title, JOptionPane.QUESTION_MESSAGE);

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    20

  • 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. An identifier cannot be true, false,

    or null.

    An identifier can be of any length. Obje

    ct O

    rrie

    nted

    Pro

    gram

    min

    g

    21

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

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    22

  • Assignment Statements x = 1; // Assign 1 to x;

    radius = 1.0; // Assign 1.0 to radius;

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

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    23

  • Constants final datatype CONSTANTNAME = VALUE;

    final double PI = 3.14159;

    final int SIZE = 3;

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    24

  • Primitive Data Types & Operators byte: 8-bit signed [-128; 127]

    short: 16-bit signed [-32,768; 32,767]

    int: 32-bit signed [-2,147,483,648; 2,147,483,647] generally the default choice

    long: 64-bit signed [-9,223,372,036,854,775,808; 9,223,372,036,854,775,807] exceed int

    float: single-precision 32-bit IEEE 754 floating point; should never be used for precise values, such as currency (java.math.BigDecimal)

    double: double-precision 64-bit IEEE 754 floating point; usually the default choice for decimal values

    boolean: true and false; its "size" is not precisely defined

    char: 16-bit Unicode character ['\u0000' (or 0); '\uffff' (or 65,535]

    +, -, *, /, %

    Shortcut assignment with =

    ++, -- (pre and post)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    25

  • Default Values

    Data Type Default Value (for fields)

    byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' String (or any object) null boolean false

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    26

  • Numeric Type Conversion Consider the following statements:

    byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;

    When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is

    converted into double. 2. Otherwise, if one of the operands is float, the other

    is converted into float. 3. Otherwise, if one of the operands is long, the other

    is converted into long. 4. Otherwise, both operands are converted into int.

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    27

  • Type Casting Implicit casting

    double d = 3; (type widening)

    Explicit casting int i = (int) 3.0; (type narrowing) int i = (int) 3.9; (Fraction part is truncated)

    What is wrong? int x = 5 / 2.0;

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    28

    range increases

    byte, short, int, long, float, double

  • Character Data Type char letter = 'A'; (ASCII)

    char numChar = '4'; (ASCII)

    char letter = '\u0041'; (Unicode)

    char numChar = '\u0034'; (Unicode)

    NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b. char ch = 'a'; System.out.println(++ch);

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    29

    Four hexadecimal digits

  • Escape Sequences for Special Characters Description Escape Sequence Unicode

    Backspace \b \u0008

    Tab \t \u0009

    Linefeed \n \u000A

    Carriage return \r \u000D

    Backslash \\ \u005C

    Single Quote \' \u0027

    Double Quote \" \u0022

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    30

  • The String Type Char type represents only one character. To represent a

    string of characters:

    String message = "Welcome to Java";

    A predefined class in the Java library

    Not a primitive type, but a reference type

    // Three strings are concatenated String message = "Welcome " + "to " + "Java";

    // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2

    // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    31

  • Converting Strings to Integers or Doubles To convert a string into an int value, you can use

    the static parseInt method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as 123.

    To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue

    =Double.parseDouble(doubleString);

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    32

  • The boolean Type and Operators Often in a program you need to compare two values,

    such as whether i is greater than j => Boolean value: true or false. boolean b = (1 > 2);

    Operator Name

    < less than

    greater than

    >= greater than or equal to

    == equal to

    != not equal to Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    33

  • if Statements if (boolean-expression) {

    statement(s);

    }

    //else {

    // statement(s)-for-the-false-case;

    //}

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    34

  • Multiple Alternative if Statements The else clause matches the most recent if clause

    in the same block.

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    35

    if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

    Equivalent

    if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

    int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");

    int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");

    Equivalent

  • Common Errors Adding a semicolon at the end of an if clause is a

    common mistake. if (radius >= 0); {

    area = radius*radius*PI; System.out.println("The area for the circle of radius " + radius + " is " + area);

    }

    This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error.

    This error often occurs when you use the next-line block style. O

    bjec

    t Orr

    ient

    ed P

    rogr

    amm

    ing

    36

    Wrong

  • Efficiency

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    37

    Equivalent

    Equivalent if (number % 2 == 0) even = true; else even = false;

    boolean even = number % 2 == 0;

    if (even == true) System.out.println( "It is even.");

    if (even) System.out.println( "It is even.");

  • Logical Operator Operator Name

    ! not

    && and

    || or

    ^ exclusive or

    & bitwise and

    | bitwise or

    (1 == x) && ( 2 > x++)? (x=1) Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    38

  • switch Statement Rules (1)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    39

    The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.

    The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.

    switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; case valueN: statement(s)N; break; default: statement(s)-for-default; }

  • switch Statement Rules (2)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    40

    !The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.

    switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; case valueN: statement(s)N; break; default: statement(s)-for-default; }

    !The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The case statements are executed in sequential

    order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.

  • Trace switch statement (1)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    41

    switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); }

    Suppose ch is 'a':

  • Trace switch statement (2)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    42

    switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); }

    This is 'a':

  • Trace switch statement (3)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    43

    switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); }

    Execute this line

  • Trace switch statement (4)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    44

    switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); }

    Execute this line

  • Trace switch statement (5)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    45

    switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); }

    Execute this line

  • Trace switch statement (1)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    46

    switch (ch) { case 'a': System.out.println(ch);

    break; case 'b': System.out.println(ch);

    break; case 'c': System.out.println(ch);

    break; }

    Suppose ch is 'a':

  • Trace switch statement (2)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    47

    switch (ch) { case 'a': System.out.println(ch);

    break; case 'b': System.out.println(ch);

    break; case 'c': System.out.println(ch);

    break; }

    This is 'a':

  • Trace switch statement (3)

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    48

    switch (ch) { case 'a': System.out.println(ch);

    break; case 'b': System.out.println(ch);

    break; case 'c': System.out.println(ch);

    break; }

    Execute this line

  • Conditional Operator (boolean-expression) ? exp1 : exp2

    if (num % 2 == 0)

    System.out.println(num + is even);

    else

    System.out.println(num + is odd);

    System.out.println((num % 2 == 0)? num + is even : num + is odd);

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    49

  • Formatting Output Use the printf statement.

    System.out.printf(format, items);

    Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign.

    Specifier Output Example

    %b a boolean value true or false

    %c a character 'a'

    %d a decimal integer 200

    %f a floating-point number 45.460000

    %e a number in standard scientific notation 4.556000e+01

    %s a string "Java is cool" Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    50

  • Formatting Example int count = 5;

    double amount = 45.56;

    System.out.printf(|count is %d \t| amount is %f\t|", count, amount);

    Display: |count is 5 |amount is 45.560000 |

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    51

  • Operator Precedence var++, var--

    +, - (Unary plus and minus), ++var,--var

    (type) Casting

    ! (Not)

    *, /, % (Multiplication, division, and remainder)

    +, - (Binary addition and subtraction)

    = (Comparison)

    ==, !=; (Equality)

    ^ (Exclusive OR)

    && (Conditional AND) Short-circuit AND

    || (Conditional OR) Short-circuit OR

    =, +=, -=, *=, /=, %= (Assignment operator) Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    52

  • Operator Precedence and Associativity The expression in the parentheses is evaluated first.

    (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule.

    If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative.

    When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative. a b + c d is equivalent to ((a b) + c) d

    Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) O

    bjec

    t Orr

    ient

    ed P

    rogr

    amm

    ing

    53

  • Loops

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    54

  • Loops - Motivations Suppose you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times:

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

    How do you solve this problem?

    55

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

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

    100 times

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Introducing while Loops while (loop-continuation-condition) {

    // loop-body;

    Statement(s);

    }

    Often the number of times a loop is executed is not predetermined => use an input value to signify the end of the loop (a sentinel value)

    56

    int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; }

    Trace it!

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Caution Dont use floating-point values for equality checking in a loop

    control

    Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:

    double item = 1; double sum = 0;

    while (item != 0) { // No guarantee item will be 0

    sum += item;

    item -= 0.1;

    }

    System.out.println(sum);

    This loop seems OK on the surface, but can become an infinite loop (because the floating-point arithmetic is approximated) Ob

    ject

    Orr

    ient

    ed P

    rogr

    amm

    ing

    57

  • do-while & for Loops do {

    // Loop body;

    Statement(s);

    } while (loop-continuation-condition);

    for (initial-action; loop-continuation-condition; action-after-each-iteration) {

    // loop body;

    Statement(s);

    }

    58

    int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java!"); }

    Trace it!

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Note The initial-action in a for loop a list of zero

    or more comma-separated expressions

    The action-after-each-iteration in a for loop a list of zero or more comma-separated statements for (int i = 1; i < 100; System.out.println(i++));

    for (int i = 0, j = 0; (i + j < 10); i++, j++) {

    // Do something

    }

    Therefore, the two for loops are correct

    Rarely used in practice

    59

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Note If the loop-continuation-condition in a for loop is

    omitted, it is implicitly true.

    In case of infinite loops, it is better to use the equivalent while loop to avoid confusion

    60

    Equivalent for ( ; ; ) { // Do something }

    while (true) { // Do something }

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake:

    61

    Logic Errors

    for (int i=0; i

  • Caution, cont. In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; } while (i

  • Which Loop to Use? The three forms of loop statements, while, do-

    while, and for, are expressively equivalent:

    63

    while (loop-continuation-condition) { // Loop body }

    for ( ; loop-continuation-condition; ) { // Loop body } Equivalent

    for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; }

    initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; }

    Equivalent

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Recommendations Use the one that is most intuitive and comfortable

    for you!

    In general: a for loop a fixed number of repetitions (e.g., print a

    message 100 times) a while loop unknown number of repetitions (e.g.

    reading the numbers until the input is 0) a do-while loop replace a while loop if the loop body

    has to be executed before testing the continuation condition

    64

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Minimizing Numerical Errors Numeric errors involving floating-point numbers

    are inevitable.

    Sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    65

    public class TestSum { public static void main(String[] args) { // Initialize sum float sum = 0; // Add 0.01, 0.02, ..., 0.99, 1 to sum for (float i = 0.01f; i

  • Problem: Monte Carlo Simulation The Monte Carlo simulation refers to a technique

    that uses random numbers and probability to solve problems.

    Wide range of applications in computational mathematics, physics, chemistry, and finance

    Use Monto Carlo simulation for estimating .

    66

    circleArea / squareArea = / 4

    4 * number hits / 1.000.000

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    x

    y

    1 -1

    1

    -1

  • Using break and continue w1: while (number < 20) {

    number++;

    sum += number;

    if (sum >= 100) break w1;

    }

    while (number < 20) {

    number++;

    if (number == 10 || number == 11) continue;

    sum += number;

    }

    67

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Methods

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    68

  • Problem

    69

    int sum = 0; for (int i = 1; i

  • Solution

    70

    public static int sum(int i1, int i2) { int sum = 0; for (int i = i1; i

  • Defining Methods (1) A collection of statements grouped together to

    perform specific operations

    71

    public static int max(int num1, int num2) {

    int result; if (num1 > num2) result = num1; else result = num2; return result;

    }

    modifier return value

    type method name

    formal parameters

    return value

    method body

    method header

    parameter list

    Define a method Invoke a method

    int z = max(x, y);

    actual parameters (arguments)

    method signature

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Defining Methods (2) Signature = combination of method name +

    parameter list

    Formal Parameters = variables defined in the method header

    Actual parameter or argument = when invoking a method is, a value is passed to the parameter

    A method may return a value (otherwise void). The returnValueType = data type of the value the method returns

    72

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

  • Calling Methods & Call stack

    73

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

    public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

    pass the value of i & j Trace call

    (a) The main method is invoked.

    Space required for the main method k: j: 2 i: 5

    (b) The max method is invoked.

    Space required for the max method num2: 2 num1: 5

    (d) The max method is finished and the return value is sent to k.

    (e) The main method is finished.

    Stack is empty

    Space required for the main method k: j: 2 i: 5

    Space required for the main method k: 5 j: 2 i: 5

    (c) The max method is being executed.

    Space required for the max method result: 5 num2: 2 num1: 5

    Space required for the main method k: j: 2 i: 5

  • CAUTION A return statement is required for a value-returning

    method

    The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value

    To fix this problem: delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    74

    public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return 1; }

    (a)

    Should be

    (b)

    public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else return 1; }

  • Passing Parameters Suppose you invoke the method using

    nPrintln(Welcome to Java, 5);

    What is the output?

    Suppose you invoke the method using

    nPrintln(Computer Science, 15);

    What is the output?

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g

    75

    public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); }

  • Overloading Methods Overloading the max Method

    public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; }

    76

    Obj

    ect O

    rrie

    nted

    Pro

    gram

    min

    g