Download presentation
Presentation is loading. Please wait.
Published byNaomi Randall Modified over 9 years ago
1
Review Quick reference Announcement
2
Chapter 1: Basics
3
class Car { String Make; int MaxSpeed; public brake() { System.out.println(“Stop!"); } A class: data fields (properties) + methods (behavior) Class Definition Methods usually go after the data Class Data usually goes first in a class
4
Class is a template for creating instances How to create instances of a class? Class ClassName instanceName = new ClassName(intialInputParam); Car c1= new Car(); c1.make = “Honda”; Car c2= new Car(); c2.make = “Ford”;
5
Groups related classes in the same category How to declare a class is part of a package? Unique name Hierarchal Packages package packagename; package RacingGamePackage; package book.chapter1;
6
Many packages in Java API javax.swing java.lang java.util …… How to use a package? Packages import packagename; import book.chapter1.Welcome; import book.chapter1.*; Only “Welcome” class is imported. All classes in chapter1 imported.
7
3 types of comments in Java Line comment // Example // This is a line comment! Paragraph comment /* */ Example /* This is a paragraph comment. It includes multiple lines. */ JavaDoc comments (automatic documentation) /** */ Comments
8
What is the output? Q public class Test{ public static void main(String[] args) { System.out.println(“3.5 * 2 / 2 – 2.5 is "); System.out.println(3.5 * 2 / 2 – 2.5); } >3.5 * 2 / 2 – 2.5 is >1.0
9
Chapter 2: More Basics
10
1. Create a Scanner object Scanner input = new Scanner(System.in ); 2. Use one of the methods below Input MethodYou will get next()String nextByte()byte nextShort()short nextInt()int nextLong()long nextFloat()float nextDouble()double nextBoolean()boolean
11
A variable stores your data int x = 10; Identifier Name of your variable letters, digits, underscores (_), and dollar signs ($) Cannot start with a digit Cannot be a reserved word Variable X 23 Variable Identifier Literal
12
Value is constant, doesn’t change Use “final” keyword to declare a value as constant Constants final datatype CONSTANTNAME = VALUE; Example: final double PI = 3.14159; final int SIZE = 3;
13
Shortcut operators for assignment Shortcut Operators OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f - 8.0 *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8
14
Increment, decrement operators ++/-- OperatorNameDescription ++varpre-incrementThe expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++post-incrementThe expression (var++) evaluates to the original value in var and increments var by 1. --varpre-decrementThe expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var--post-decrement The expression (var--) evaluates to the original value in var and decrements var by 1.
15
Implicit casting (type widening) A small number fits easily in a large variable Explicit casting (type narrowing) A large number (3.9, double) cannot be fit in a smaller variable (int), so fraction part is truncated. You need to explicitly cast your number. Conversions double d = 3; int i = (int)3.9;
16
Example >b >c Q public class Test{ public static void main(String[] args) { char x = ‘a’; char y = ‘c’; System.out.println(++x); System.out.println(y++); }
17
Chapter 3: Selections
18
Example Two-way if if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area is: “ + area); } else { System.out.println("Negative input"); }
19
else if is used for checking multiple conditions Multiple if-else 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';
20
What if we need more complex conditions composed of “and/or/..”? Logical Operators OperatorName !not &&and ||OR ^Exclusive OR
21
Tax Program Switch Statement switch (status) { case 0: //compute taxes for single filers; break ; case 1: //compute taxes for married file jointly; break ; case 2: //compute taxes for married file separately; break ; case 3: //compute taxes for head of household; break ; default : System.out.println("Errors: invalid status"); }
22
Conditional statement as (boolean-expression) ? expression1 : expression2 Conditional Statement if (x > 0) y = 1 else y = -1; y = (x > 0) ? 1 : -1;
23
%s s stands for a string %f stands for floating point number System.out.printf("%s, %s", "Hello", "World!"); Output: “Hello, World!” System.out.printf(“%.1f pounds”,28.8968); Output: “28.8 pounds” Formatting Output
24
Format specifiers in more detail Formatting Specifier %flagwidth.precisiontype Tells the compiler to expect a specifier … A flag (such as - to left justify) Minimum number of characters to show Maximum number of digits after decimal point Data type (e.g. %f)
25
Formatting Output Specifier OutputExample %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 scientific notation 4.556000e+01 %s a string "Java is cool"
26
What is the output? > amount is 32.3200 >□□ java > Q System.out.printf(“amount is %5.4f”,32.32); System.out.printf(“%6s \n”,”java”);
27
Chapter 4: Loops
28
1. If the condition is true, the statement is executed; then the condition is evaluated again … 2. The statement is executed over and over until the condition becomes false. 3. When the loop finishes, control passes to the next instruction in the program, following the closing curly brace of the loop. while Loop while (condition) { statement; }
29
The body of a while loop must eventually make the condition false If not, it is an infinite loop, which will execute until the user interrupts the program! Caution! int count = 1; while (count > 0) { System.out.println("Welcome to Java!"); count++; }
30
Will be executed at least once do while do { // Loop body; Statement(s); } while (loop-condition);
31
for loop int count = 0; while (count < 10) { System.out.println("Welcome to Java!"); count++; } for ( int count =0; count < 10; count ++) { System.out.println("Welcome to Java!"); }
32
Some recommendations 1. Use the most intuitive loop 2. If number of repetitions known for 3. If number of repetitions unknown while 4. If should be executed at least once (before testing the condition) do-while Which Loop?
33
break causes the loop to be abandoned, and execution continues following the closing curly brace. break while ( i > 0 ) {.... if ( j ==.... ) break ; // abandon the loop …. } // end of the loop body break will bring you here
34
continue causes the rest of the current round of the loop to be skipped. " while " or " do " loop moves directly to the next condition test of the loop. " for " loop moves to the “ action-after-each- iteration” expression, and then to the condition test. continue
35
How many times count++ will be executed? Q int count = 0; while (count < 10) count++; 10 int count= 0; for ( int i=0; i<= 10; i++) count++; 11 int count = 5; while (count < 10) count++; 5 int count = 5; while (count < 10) count += 3; 2
36
Poll results Look up your class section Test credit card # Announcement
37
Chapter 5: Methods
38
A method Method public static int sum( int x, int y) { int sum = 0; for ( int i = x; i <= y; i++) sum += i; return sum; } modifier output name input Method body
39
First, a method should be defined Then we can use the method i.e. calling or invoking a method Invoking a Method public static void main(String[] args) { int total1 = sum(1, 10); int total2= sum(20, 30); int total3 = sum(35, 45); int total4 = sum(35,1000); }
40
When calling a method within the same class, we directly call the method Invoking a Method public class TestClass{ public static void main(String[] args) { int total1 = sum(1, 10); } //---------------------------------------------- public static int sum( int x, int y) { int sum = 0; for ( int i = x; i <= y; i++) sum += i; return sum; } calling directly
41
When calling a method from another class, use class name if a static method Invoking a Method public class TestClass{ public static void main(String[] args) { int total1 = AnotherClass.sum(1, 10); } Class name public class AnotherClass{ public static int sum( int x, int y) { int sum = 0; for ( int i = x; i <= y; i++) sum += i; return sum; }
42
When calling a method from another class, use class name if a static method Invoking a Method public class TestClass{ public static void main(String[] args) { AnotherClass a = new AnotherClass(); int total1 = a.sum(1, 10); } Instance name public class AnotherClass{ public int sum( int x, int y) { int sum = 0; for ( int i = x; i <= y; i++) sum += i; return sum; }
43
How memory is managed? Memory Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: 5 i:5 j:2 Stack is empty Space required for max method: x:5 y:2 Space required for max method: Result: 5 x:5 y:2
44
What about reference types? E.g. Random r = new Random(); Pass by Reference Space required for main method: r (reference) Stack Memory Heap Memory … Actual Object Space required for test method: x
45
Method overload is only based on input arguments Method overload can not be based on different output values Method overload cannot be based on different modifiers Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error. Method Overload
46
Scope: Part of the program where the variable can be referenced. A local variable: A variable defined inside a method. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. Variable Scope
47
Class level Scope: Accessible to all methods of that class Variable Scope public class Test{ int x; //data field: accesible to all methods public int method1() { //do something...} public int method2() { //do something...} }
48
Method level Scope: Variable Scope public int sum( int x, int y) { int sum = 0; for ( int i = x; i <= y; i++) sum += i; return sum; }
49
Block level Scope: Variable Scope public int sum( int x, int y) { int sum = 0; for ( int i = x; i <= y; i++) { int k = -1; sum = k + i; } return sum; }
50
Which statements are incorrect? Q public int sum() { int sum = i; for ( int i = 0; i <= 10; i++) { sum += j; for ( int j = 0; j <= 10; j+=k) { int k = -1; sum = i + j; } } return sum; }
51
Chapter 6: 1D Arrays
52
Array is a data structure that represents a collection of the same type of data. Array is a reference type Array 23 45 53 16 32 8 91 int [] myList = new int [7]; 0x675 myList (memory location of the actual array) Array element at index 6 Value of element at index 6
53
Once an array is created, its size is fixed. i.e. it cannot be changed! You can find the size of an array using For example This returns 7. Length of Array arrayRefVar.length int length = myList.length;
54
Each element of array is an indexed variable: Example (accessing first element) Indexed Variables arrayRefVar[index]; myList[0];
55
Individual initialization Populate Array double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
56
Shorthand initialization This shorthand syntax must be in one statement. Splitting it would cause a syntax error! Populate Array double[] myList = {1.9, 2.9, 3.4, 3.5};
57
JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for-each for (double value: myList) System.out.println(value); for (elementType value:arrayRefVar) …
58
Arrays are reference type, so be careful! After assignment, both lists will point to the same memory location. Array Copy list2 = list1;
59
To copy the contents (and not the reference), you can use a loop: Array Copy int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];
60
To copy the contents (and not the reference), you can also use the arrayCopy utility: Example Array Copy System.arraycopy(source, srcPos, target, tarPos, length); int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; System.arraycopy(sourceArray, 0, targetArray, 0,sourceArray.length);
61
Two ways to pass an array to a method Passing Array public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); } int[] list = {3, 1, 2, 6, 4, 2}; printArray(list); printArray(new int[]{3, 1, 2, 6, 4, 2}); Anonymous Array
62
Two Java uses pass by value to pass arguments to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. Passing Values 23 45 53 16 32 8 int [] y = new int [7]; y int x = 10 ; 10 x
63
Returning an array Return Array public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; } int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1);
64
Does the following statement resize the array? Q int[] myList; myList = new int[10]; myList = new int[20];
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.