02 - Java Fundamentals Handout
02 - Java Fundamentals Handout
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
// strategic (before, overall) vs. tactical (intended for single lines of code can make code unreadable) // include copyright information // add descriptive information before function
Constants:
Block Styles
public class Test {
Indentation Spacing
Indent two spaces (or \t in Eclipse / NetBeans) Use blank line to separate segments of the code
} public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } }
Class names:
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
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.
11
12
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
// Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }
13
14
/** Main method */ public static void main(String[] args) { double radius; double area;
// Assign a radius
radius = 20;
// Compute area
Object Orriented Programming
// 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
20 1256.636
// 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
Elementary programming
10/15/13
a Scanner object
System.out.print("Enter a double value: ");! Scanner input = new Scanner(System.in);! double d = input.nextDouble();
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;
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;
23
24
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,!
10/15/13
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
Type 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.
27
28
char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode)
Escape Sequence \b \t \n
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);
29
30
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;
double: double-precision 64-bit IEEE 754 floating point; usually the default choice for decimal values
10/15/13
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
31
32
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);
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
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';
Equivalent
area = radius*radius*PI; System.out.println("The area for the circle of radius " + radius + " is " + area);
}
Object Orriented Programming
Equivalent
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
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;
! && ||
Object Orriented Programming
Equivalent
^ & |
37
38
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.
optional, can be used to perform actions when none of the specified cases matches the switch-expression.
39
40
41
42
10/15/13
43
44
case 'c': }
45
46
case 'c': }
47
48
10/15/13
Conditional Operator
Formatting Output
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. 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'
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
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
53
54
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
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
100 times
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:
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
used in practice
59
60
// Do something
for ( ; ; ) { // Do something }
// loop body;
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
61
62
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
Equivalent
Equivalent
63
64
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
65
-1
66
11
10/15/13
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)); }
69
70
Invoke a method
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
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; } return result;
parameter list
A method may return a value (otherwise void). The returnValueType = data type of the value the method returns
71
72
Methods
12
10/15/13
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
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.
Stack is empty
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
What is the output? Suppose you invoke the method using nPrintln(Computer Science, 15);
Object Orriented Programming
public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); }
75
76
public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; }
13