Sunteți pe pagina 1din 13

10/15/13

Mihai Dasclu 2CB, 2013 - 2014

Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles

Appropriate Comments

Naming Conventions

/* 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

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. Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE

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


Object Orriented Programming

// strategic (before, overall) vs. tactical (intended for single lines of code can make code unreadable) // include copyright information // add descriptive information before function

Constants:

Proper Indentation and Spacing


Block Styles
public class Test {

Next-line & End-of-line

Indentation Spacing

Indent two spaces (or \t in Eclipse / NetBeans) Use blank line to separate segments of the code

public static void main(String[] args) { System.out.println("Block Styles"); }


Object Orriented Programming

} public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } }

Object Orriented Programming

Object Orriented Programming

//beginning of the program

Class names:

Object Orriented Programming

Object Oriented Programming

Programming Style and Documentation

10/15/13

Programming Errors

Syntax Errors
public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); } }
Object Orriented Programming Object Orriented Programming

Syntax Errors

Detected by the compiler Causes the program to abort

Runtime Errors Logic Errors


Produces incorrect result

Runtime Errors
public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / 0; } }
Object Orriented Programming

Logic Errors
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);
Object Orriented Programming

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

10

Debugging

Debugger

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.

Object Orriented Programming

http://www.vogella.com/articles/EclipseDebugging/ article.html https://netbeans.org/features/java/debugger.html

11

12

Object Orriented Programming

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

10/15/13

Trace a Program Execution


public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area;

allocate memory for radius radius no value

Object Orriented Programming

// Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

13

14

Trace a Program Execution


public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area;

Trace a Program Execution


public class ComputeArea {

memory radius area no value no value

assign 20 to radius radius area 20 no value

/** Main method */ public static void main(String[] args) { double radius; double area;

// Assign a radius radius = 20;

// Assign a radius

allocate memory for area


Object Orriented Programming

radius = 20;

// Compute area area = radius * radius * 3.14159;

// Compute area
Object Orriented Programming

area = radius * radius * 3.14159;

// Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

// Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

15

16

Trace a Program Execution


public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area;

Trace a Program Execution


public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area;

memory radius area

memory radius area 20 1256.636

20 1256.636

// Assign a radius radius = 20;

// Assign a radius radius = 20;

// Compute area area = radius * radius * 3.14159;

compute area and assign it to variable area


Object Orriented Programming

// Compute area area = radius * radius * 3.14159;

// Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

// Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }

17

18

Object Orriented Programming

print a message to the console

Object Orriented Programming

Elementary programming

// Assign a radius radius = 20;

// Compute area area = radius * radius * 3.14159;

10/15/13

Reading Input from the Console


Create Use

Getting Input from Input Dialog Boxes

a Scanner object

Object Orriented Programming

System.out.print("Enter a double value: ");! Scanner input = new Scanner(System.in);! double d = input.nextDouble();

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

19

20

Identifiers
An

Declaring Variables
int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a;
Object Orriented Programming

identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). 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

// Declare a to be a
Object Orriented Programming

// character variable;

An identifier cannot be true, false, or null.


An

identifier can be of any length.

21

22

Assignment Statements

Constants
final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3;
Object Orriented Programming Object Orriented Programming

x = 1;

// Assign 1 to x;

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

23

24

Object Orriented Programming

the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, oat, double, or boolean value. For example,!

Scanner input = new Scanner(System.in);!

String input = JOptionPane.showInputDialog( "Enter an input");

10/15/13

Primitive Data Types & Operators


Default Values
Data Type byte short int long float double char String (or any object) boolean Default Value (for fields) 0 0 0 0L 0.0f 0.0d '\u0000' null false

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)
Object Orriented Programming

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)

25

26

Numeric Type Conversion

Type Casting

Consider the following statements:


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

Implicit casting Explicit casting

double d = 3; (type widening) int i = (int) 3.0; (type narrowing) int i = (int) 3.9; (Fraction part is truncated)

When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules:
Object Orriented Programming

2. 3. 4.

range increases byte, short, int, long, float, double

27

28

Character Data Type


Escape Sequences for Special Characters



Object Orriented Programming

char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode)

Four hexadecimal digits

Description Backspace Tab Linefeed

Escape Sequence \b \t \n

Unicode \u0008 \u0009 \u000A \u000D \u005C \u0027 \u0022


Object Orriented Programming

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

Carriage return \r Backslash Single Quote Double Quote \\ \' \"

29

30

Object Orriented Programming

1.

If one of the operands is double, the other is converted into double. Otherwise, if one of the operands is float, the other is converted into float. Otherwise, if one of the operands is long, the other is converted into long. Otherwise, both operands are converted into int.

What is wrong?

int x = 5 / 2.0;

Object Orriented Programming

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

10/15/13

The String Type


Converting Strings to Integers or Doubles

Char type represents only one character. To represent a string of characters: String message = "Welcome to Java";

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.

A predefined class in the Java library Not a primitive type, but a reference type
Object Orriented Programming

String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes Chapter2

double doubleValue =Double.parseDouble(doubleString);

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

31

32

The boolean Type and Operators

if Statements
if (boolean-expression) { statement(s); } //else { //
Object Orriented Programming

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 less than or equal to greater than greater than or equal to equal to not equal to

statement(s)-for-the-false-case;
Object Orriented Programming

//}

33

34

Multiple Alternative if Statements

Common Errors

The else clause matches the most recent if clause in the same block.
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'; 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';

Adding a semicolon at the end of an if clause is a common mistake.


if (radius >= 0); {
Wrong

Equivalent

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

}
Object Orriented Programming

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

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

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.

35

36

Object Orriented Programming

Object Orriented Programming

// Three strings are concatenated

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

10/15/13

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

Logical Operator
Operator
boolean even = number % 2 == 0;

Name not and or exclusive or bitwise and bitwise or


Object Orriented Programming

! && ||
Object Orriented Programming

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

Equivalent

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

^ & |

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

37

38

switch Statement Rules (1)


The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. 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 keyword break is

switch Statement Rules (2)


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

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.

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.

Object Orriented Programming

optional, can be used to perform actions when none of the specified cases matches the switch-expression.

39

40

Trace switch statement (1)


Suppose ch is 'a':

Trace switch statement (2)


This is 'a':

Object Orriented Programming

41

42

Object Orriented Programming

switch case case case }

(ch) 'a': 'b': 'c':

{ System.out.println(ch); System.out.println(ch); System.out.println(ch);

switch case case case }

(ch) 'a': 'b': 'c':

{ System.out.println(ch); System.out.println(ch); System.out.println(ch);

Object Orriented Programming

!The default case, which is

10/15/13

Trace switch statement (3)


Execute this line

Trace switch statement (4)


Execute this line

Object Orriented Programming

43

44

Trace switch statement (5)


Execute this line

Trace switch statement (1)


Suppose ch is 'a':

Object Orriented Programming

case 'c': }

45

46

Trace switch statement (2)


This is 'a':

Trace switch statement (3)


Execute this line

switch (ch) { case 'a': case 'b': case 'c': }

Object Orriented Programming

case 'c': }

47

48

Object Orriented Programming

System.out.println(ch); break; System.out.println(ch); break; System.out.println(ch); break;

switch (ch) { case 'a': case 'b':

System.out.println(ch); break; System.out.println(ch); break; System.out.println(ch); break;

Object Orriented Programming

switch case case case }

(ch) 'a': 'b': 'c':

{ System.out.println(ch); System.out.println(ch); System.out.println(ch);

switch (ch) { case 'a': case 'b':

System.out.println(ch); break; System.out.println(ch); break; System.out.println(ch); break;

Object Orriented Programming

switch case case case }

(ch) 'a': 'b': 'c':

{ System.out.println(ch); System.out.println(ch); System.out.println(ch);

switch case case case }

(ch) 'a': 'b': 'c':

{ System.out.println(ch); System.out.println(ch); System.out.println(ch);

10/15/13

Conditional Operator

Formatting Output

(boolean-expression) ? exp1 : exp2

Use the printf statement.

System.out.printf(format, items);

if (num % 2 == 0) System.out.println(num + is even); else


Object Orriented Programming

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. Example true or false 200 45.460000 "Java is cool"
Object Orriented Programming

Specifier Output %b %c %d %f %e %s a boolean value a character a decimal integer a floating-point number a string

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

'a'

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

a number in standard scientific notation 4.556000e+01

49

50

Formatting Example

Operator Precedence
var++, var-+, - (Unary plus and minus), ++var,--var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction)
Object Orriented Programming

int count = 5; double amount = 45.56; System.out.printf(|count is %d \t| amount is %f \t|", count, amount);

==, !=; (Equality) ^ (Exclusive OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)

51

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.
Object Orriented Programming

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

53

54

Object Orriented Programming

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.

Loops

Object Orriented Programming

Display: |count is 5 |amount is 45.560000 |

<, <=, >, >= (Comparison)

10/15/13

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?
Object Orriented Programming

Introducing while Loops


while (loop-continuation-condition) { // loop-body; Statement(s); }

100 times

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

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

Trace it!

55

56

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:

do-while & for Loops


do { // Loop body; Statement(s); } while (loop-continuation-condition); for (initial-action; loop-continuationcondition; action-after-each-iteration) {
Object Orriented Programming

double item = 1; double sum = 0; while (item != 0) { // No guarantee item will be 0 sum += item; item -= 0.1; } System.out.println(sum);

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

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

Trace it!

57

58

Note
The The

Note

initial-action in a for loop a list of zero or more comma-separated expressions 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++) {
Object Orriented Programming

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

Equivalent

Therefore, Rarely

the two for loops are correct

used in practice

59

60

Object Orriented Programming

// Do something

for ( ; ; ) { // Do something }

while (true) { // Do something }

Object Orriented Programming

// loop body;

Object Orriented Programming

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

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)

10

10/15/13

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

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<10);
Correct

Object Orriented Programming

int i=0; while (i < 10); { System.out.println("i is " + i); i++; }

61

62

Which Loop to Use?

Recommendations

The three forms of loop statements, while, dowhile, and for, are expressively equivalent:

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

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

Equivalent

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

Object Orriented Programming

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

Equivalent

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

63

64

Minimizing Numerical Errors


Problem: Monte Carlo Simulation

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.

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 .
1
Object Orriented Programming


Object Orriented Programming

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 <= 1.0f; i = i + 0.01f) sum += i; // Display result System.out.println("The sum is " + sum);

circleArea / squareArea = / 4
-1 1 x

4 * number hits / 1.000.000

65

-1

66

Object Orriented Programming

Object Orriented Programming

for (int i=0; i<10; i++); { System.out.println("i is " + i); }

11

10/15/13

Using break and continue


w1: while (number < 20) { number++; sum += number; if (sum >= 100) break w1; }
Object Orriented Programming

number++; if (number == 10 || number == 11) continue; sum += number; }

67

68

Problem
int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum);

Solution
public static int sum(int i1, int i2) { int sum = 0; for (int i = i1; i <= i2; i++) sum += i; return sum; } public static void main(String[] args) { System.out.println("Sum from 1 to 10 is " + sum(1, 10)); System.out.println("Sum from 20 to 30 is " + sum(20, 30)); System.out.println("Sum from 35 to 45 is " + sum(35, 45)); }

Object Orriented Programming

69

70

Defining Methods (1)

Defining Methods (2)

Invoke a method

A collection of statements grouped together to perform specific operations


Define a method modifier return value type method name formal parameters

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
Object Orriented Programming


Object Orriented Programming

method header method body

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

int z = max(x, y);


actual parameters (arguments)

method signature return value

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

71

72

Object Orriented Programming

Object Orriented Programming

while (number < 20) {

Methods

12

10/15/13

Calling Methods & Call stack


Trace call
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);

CAUTION

pass the value of i & j


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

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
Object Orriented Programming

Space required for the max method num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 (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 result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 (c) The max method is being executed. Space required for the main method k: 5 j: 2 i: 5 (d) The max method is finished and the return value is sent to k.

Object Orriented Programming

Stack is empty

(e) The main method is finished.

73

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

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
Should be

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

74

Passing Parameters

Overloading Methods
Overloading the max Method

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);
Object Orriented Programming

What is the output?

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

75

76

Object Orriented Programming

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

13

S-ar putea să vă placă și