1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248
|
|
- Harriet Howard
- 6 years ago
- Views:
Transcription
1 1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248
2 All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚, 笑傲江湖 第十回 傳劍 Zheng-Liang Lu Java Programming 186 / 248
3 Methods 2 Methods can be used to define reusable code, and organize and simplify code. The idea of functions originates from the definition of mathematical functions, that is, y = f (x), where x is the input parameter 1 and y is the function value. In computer science, each input parameter should be declared with a specific type, and a function should be assigned with a return type. 1 Recall the multivariate functions. The variable x can be a vector, say the position vector (x, y, z). 2 Some programming languages refer to methods as procedures and functions. Zheng-Liang Lu Java Programming 187 / 248
4 Example: max Zheng-Liang Lu Java Programming 188 / 248
5 1 modifier returntype methodname(listofparameters) { 2 // method body 3 } So far, the modifier could be static and public. returntype could be primitive data types, referential data types 3, and void. 4 listofparameters is the inputs of the method, separated by commas. Note that the parameters are optional; that is, a method doesn t have to contain any parameter. 5 The method name and the parameter list together constitute the method signature. 6 3 A method can return an object. 4 Recall that a void method does not return a value. 5 For example, Math.random(). 6 It is the key to the method overloading. We will see it soon. Zheng-Liang Lu Java Programming 189 / 248
6 More Observations There are alternatives to the max() method in the previous page: 1 public static int max(int x, int y) { 2 if (x > y) { 3 return x; 4 } else { 5 return y; 6 } 7 } 1 public static int max(int x, int y) { 2 return x > y? x : y; 3 } Zheng-Liang Lu Java Programming 190 / 248
7 return Statements A method returns to the code that invoked it if one of the following situations occurs: the method completes all the statements, reaches a return statement, or throws an exception (covered later). The return statements are the end of the method. Note that the return statement is not necessarily at the bottom of the method. 7 7 Thanks to a lively discussion on November 22, Zheng-Liang Lu Java Programming 191 / 248
8 However, your method should make sure that the return statement are available for all conditions. For example, 1 static int run1() { 2 while (true); 3 return 0; //unreachable code 4 } 5 6 static int run2(int x) { 7 if (x > 0) { 8 return x; 9 } 10 // what if x < 0? 11 } Once you define the return type, you should return a value or an object depending the return type. Zheng-Liang Lu Java Programming 192 / 248
9 Invoking A Method Invoking a method is to execute the code defined in the method. When a program invokes a method, the program control is transferred to the called method. Each time a method is invoked, the system creates an activation frame that stores parameters and variables for the method and places it in the call stack. A called method transfers the program control to the caller when its return statement is executed or when its end brace is reached. Zheng-Liang Lu Java Programming 193 / 248
10 Note that the parameters are new declared variables within the method. When calling a method, you need to provide arguments, which must match the parameters in order, number, and compatible type, as defined in the method signature. This mechanism is so-called pass-by-value. Zheng-Liang Lu Java Programming 194 / 248
11 Zheng-Liang Lu Java Programming 195 / 248
12 Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets defines a particular scope. Moreover, one can declare variables with the same name in different levels of scopes. Yet, one cannot declare the variables with the same name in the same scope. Zheng-Liang Lu Java Programming 196 / 248
13 Example 1 public class incrementmain { 2 3 static int i = 1; // Aka class member. 4 5 public static void main(string[] args) { 6 System.out.printf("%d\n", i); // Where is i? 7 int i = 2; 8 i++; 9 System.out.printf("%d\n", i); 10 p(); 11 System.out.printf("%d\n", i); 12 } static void p() { 15 i = i + 1; 16 System.out.printf("%d\n", i); 17 } 18 } Zheng-Liang Lu Java Programming 197 / 248
14 Example Write a program which allows the user to enter the math grades in order (-1 to exit), and makes a histogram. Zheng-Liang Lu Java Programming 198 / 248
15 int[] hist = new int[5]; 3 // hist[0]: the number of students who get Scanner in = new Scanner(System.in); 6 int inputvalue; 7 do { 8 do { 9 System.out.println("Enter x? ( 1 to exit)"); 10 inputvalue = in.nextint(); 11 } while (inputvalue!= 1 && (inputvalue < 0 inputvalue > 100)); 12 if (inputvalue >= 90) ++hist[0]; 13 else if (inputvalue >= 80) ++hist[1]; 14 else if (inputvalue >= 70) ++hist[2]; 15 else if (inputvalue >= 60) ++hist[3]; 16 else if (inputvalue >= 0) ++hist[4]; 17 else System.out.println("End of input."); 18 } while (inputvalue!= 1); 19 in.close(); int number = 0; 22 for (int i = 0; i < hist.length; i++) { 23 number += hist[i]; Zheng-Liang Lu Java Programming 199 / 248
16 24 } 25 System.out.printf("Total: %d\n", number); int[] tick = {101, 90, 80, 70, 60, 0}; 28 for (int i = 0; i < 5; i++) { 29 System.out.printf("%3d %3d: ", tick[i], tick[i + 1] 1); 30 for (int j = 0; j < hist[i]; j++) { 31 System.out.printf(" "); 32 } 33 System.out.printf("\n"); 34 } Shall we rearrange the codes in order to reduce the complexity of the main method? Zheng-Liang Lu Java Programming 200 / 248
17 static int[] inputmethod() { 3 int[] cnt = new int[5]; 4 Scanner in = new Scanner(System.in); 5 int inputvalue; 6 do { 7 do { 8 System.out.println("Enter x? ( 1 to exit)"); 9 inputvalue = in.nextint(); 10 } while (inputvalue!= 1 && (inputvalue < 0 inputvalue > 100)); 11 if (inputvalue >= 90) ++cnt[0]; 12 else if (inputvalue >= 80) ++cnt[1]; 13 else if (inputvalue >= 70) ++cnt[2]; 14 else if (inputvalue >= 60) ++cnt[3]; 15 else if (inputvalue >= 0) ++cnt[4]; 16 else System.out.println("End of input."); 17 } while (inputvalue!= 1); 18 in.close(); 19 return cnt; 20 } Zheng-Liang Lu Java Programming 201 / 248
18 24 static void displayhistogram(int[] cnt) { 25 int number = 0; 26 for (int i = 0; i < cnt.length; i++) { 27 number += cnt[i]; 28 } 29 System.out.printf("Total: %d\n", number); int[] tick = {101, 90, 80, 70, 60, 0}; 32 for (int i = 0; i < 5; i++) { 33 System.out.printf("%3d %3d: ", tick[i], tick[i + 1] 1); 34 for (int j = 0; j < cnt[i]; j++) { 35 System.out.printf(" "); 36 } 37 System.out.printf("\n"); 38 } 39 } Zheng-Liang Lu Java Programming 202 / 248
19 public static void main(string[] args) { 3 int[] hist = inputmethod(); 4 displayhistogram(hist); 5 } 6... Zheng-Liang Lu Java Programming 203 / 248
20 Math Class The Math class contains the methods needed to perform basic mathematical functions. The Math class is public. All methods of Math class are public and static with two global constants Math.PI 8 and Math.E 9. The Math class provides common methods like: max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, and random. Full document of Math class can be found here. 8 π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as e is the base of the natural logarithm. It is approximately equal to Zheng-Liang Lu Java Programming 204 / 248
21 Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that a character is encoded using an integer. How to generate these characters randomly? Zheng-Liang Lu Java Programming 205 / 248
22 static char getrandomuppercaseletter() { 3 return (char)(math.random() ( Z A + 1) + A ); 4 } 5 6 static char getrandomlowercaseletter() { 7 return (char)(math.random() ( z a + 1) + a ); 8 } 9 10 static char getrandomdigitalcharacter() { 11 return (char)(math.random() ( ) + 0 ); 12 } Zheng-Liang Lu Java Programming 206 / 248
23 public static void main (String[] args) { 3 // def: 0 > upper case, 1 > lower case, 2 > numbers 4 for (int i = 1; i <= 10; ++i){ 5 int type = (int) (Math.random() 3); 6 switch (type) { 7 case 0: 8 System.out.printf("%c", getrandomuppercaseletter()); 9 break; 10 case 1: 11 System.out.printf("%c", getrandomlowercaseletter()); 12 break; 13 case 2: 14 System.out.printf("%c", getrandomdigitalcharacter()); 15 break; 16 } 17 } 18 } Zheng-Liang Lu Java Programming 207 / 248
24 Overloading Methods Overloading methods enables you to define the methods with the same name as long as their signatures are different. Overloading methods can make programs clearer and more readable. Note that overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types. Zheng-Liang Lu Java Programming 208 / 248
25 Example (Revisit) Printing stars Write a program which prints a certain number of lines with some symbol determined by the user. The program repeats itself until the input number is negative. In addition, use * as the default symbol if the input is left blank. Zheng-Liang Lu Java Programming 209 / 248
26 static void print(int n) { 3 for (int i = 1; i <= n; i++) { 4 for (int j = 1; j <= i; j++) { 5 System.out.printf(" "); 6 } 7 System.out.println(); 8 } 9 } static void print(int n, String m) { 12 for (int i = 1; i <= n; i++) { 13 for (int j = 1; j <= i; j++) { 14 System.out.printf(m); 15 } 16 System.out.println(); 17 } 18 } Zheng-Liang Lu Java Programming 210 / 248
27 while (true) { 3 System.out.println("Enter n =? "); 4 n = Integer.parseInt(input.nextLine()); 5 if (n > 0) { 6 System.out.println("Enter a symbol? "); 7 m = input.nextline(); 8 if (m.equals("")) print(n); 9 else print(n, m); 10 } else { 11 System.out.println("Bye."); 12 break; 13 } 14 } The method Integer.parseInt() converts the input string to an integer. The method nextline() returns a string from the keyboard. The method equals() is a String method used to compare if the two strings are identical. Zheng-Liang Lu Java Programming 211 / 248
28 Divide and Conquer When developing a program, you can use the divide-andconquer strategy, aka stepwise refinement, to decompose the original problem into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. Pros: easier to write, reuse, debug, test, modify, maintain, and better facilitating teamwork For most problems, do not write the entire program at once. 10 Be aware that sitting in front of the computer is the last thing when programming. 10 So you need more skills such that system analysis, project management, and software engineering. Zheng-Liang Lu Java Programming 212 / 248
29 Recursion 11 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is essentially repetition without a loop. 11 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 213 / 248
30 Try Fractal. Zheng-Liang Lu Java Programming 214 / 248
31 Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than and equal to n. Note that 0! = 1. For example, 5! = = 5 4! = 120. Can you find the pattern? Zheng-Liang Lu Java Programming 215 / 248
32 Write a program which determines n! static int factorial(int n) { 3 if (n!= 0) { 4 return n factorial(n 1); 5 } else { 6 return 1; // base condition 7 } 8 } 9... Note that there must be a base case in recursion. Can you implement the same method by using a loop? Zheng-Liang Lu Java Programming 216 / 248
33 Zheng-Liang Lu Java Programming 217 / 248
34 Equivalence: Loop Version int y = 1; 3 for (int i = 1; i < = 10; i++) { 4 y = i; 5 } 6... One intriguing question is, Can we always turn a recursive method into the loop version of that? Yes, theoretically The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 218 / 248
35 In Practice Recursion bears substantial overhead. So the recursive algorithm may execute a bit more slowly than the iterative equivalent. Additionally, a deeply recursive method depletes the call stack, which is limited, and causes stack overflow fast. Zheng-Liang Lu Java Programming 219 / 248
36 Exercise Fibonacci numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The sequence of Fibonacci numbers is defined by the recurrence relation F n = F n 1 + F n 2, where F 0 = 0, F 1 = 1, and n 2. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. Zheng-Liang Lu Java Programming 220 / 248
37 Zheng-Liang Lu Java Programming 221 / 248
38 static int fibrecursive(int n) { 3 if (n == 0) return 0; 4 else if (n == 1) return 1; 5 else return fibrecursive(n 1) + fibrecursive(n 2); 6 } 7... This recursive implementation is straightforward. Yet, this algorithm isn t efficient since it requires more time and memory fibrecursive is an exponential-time algorithm while factorial is a linear-time algorithm. (Why?) Zheng-Liang Lu Java Programming 222 / 248
39 You can try an iterative approach for Fibonacci numbers static double fibiter(int n) { 3 int x = 0, y = 1; 4 if (n < 2) { 5 return (n == 1)? y : x; 6 } else { 7 for (int i = 0; i < n; ++i){ 8 int tmp = x + y; 9 x = y; 10 y = tmp; 11 } 12 return y; 13 } 14 } Can you find a linear recursion for Fibonacci numbers? Zheng-Liang Lu Java Programming 223 / 248
40 Abstraction Abstraction is a technique for managing complexity of computer systems. Higher level of abstraction hides the detail at lower levels, and provides the interfaces only. The programmer works with the well-defined interface and can add additional levels of functionality that would otherwise be too complex to handle. For example, no need to know how System.out.println() works. Zheng-Liang Lu Java Programming 224 / 248
41 Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 225 / 248
42 Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 226 / 248
43 Abstraction (Concluded) Control abstraction is the abstraction of actions while data abstraction is that of data structures. One can view the notion of an object as a way to combine abstractions of data and code. It is encapsulation Recall that object-oriented programming languages fulfill encapsulation, inheritance, and polymorphism. Zheng-Liang Lu Java Programming 227 / 248
44 1 class Lecture7 { 2 3 // Object oriented Programming 4 5 } 6 7 // Reserved words: 8 class, new, this, extends, super, interface, implements, abstract, static, protected, null, default 9 // References: Ch.5 6 in Learning Java Zheng-Liang Lu Java Programming 228 / 248
45 Real Objects Look around. We can easily find many examples for real-world objects. For example, students and an instructor. Real-world objects all have states and behaviors. Identifying these states and behaviors for real-world objects is a great way to begin thinking in object-oriented programming. Zheng-Liang Lu Java Programming 229 / 248
46 Observations For each object, raise two questions: What possible states can the object be in? What possible behaviors can the object perform? Moreover, you may also notice that there are many objects under consideration, which may be the same type or not, These real-world observations all helps translate what you care about into the world of object-oriented programming. Zheng-Liang Lu Java Programming 230 / 248
47 Software Objects From now, we call the objects for short. An object stores its states in fields and exposes its behaviors through methods. Methods operate on an object s internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object s methods is known as encapsulation. Zheng-Liang Lu Java Programming 231 / 248
48 Classes In the real world, you ll often find many individual objects all of the same kind. For example, each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as Bicycle. A class is the blueprint to create class instances which are runtime objects. Classes are the building blocks of Java applications. Zheng-Liang Lu Java Programming 232 / 248
49 Example: Points in 2D Cartesian Coordinate 1 class Point { 2 int x, y; // data member, aka fields 3 } 1 public class PointDemo { 2 public static void main(string[] args) { 3 // create a new instance of Point 4 Point p1 = new Point(); 5 p1.x = 1; 6 p1.y = 2; 7 System.out.println(p1.x + p1.y); 8 9 // create another new instance of Point 10 Point p2 = new Point(); 11 p2.x = 3; 12 p2.y = 4; 13 System.out.println(p2.x + p2.y); 14 } 15 } Zheng-Liang Lu Java Programming 233 / 248
50 Class Declaration Give a class name, with the initial letter capitalized by convention. The class body, surrounded by balanced braces {}, contains all the code that provides for the life cycle of the objects. More explicitly, we declare the fields that provide the state of the class and its objects. Also we implement the methods for the behaviors of the class and its objects. May have a modifier such as public, private, and a number of others that you will encounter later. Access modifiers realize encapsulation! Zheng-Liang Lu Java Programming 234 / 248
51 Declaring Member Variables It is known that there are several kinds of variables: Local variables (method level) Parameters: variables in method declarations Fields (class level): members of a class The first (left-most) modifier lets you control what other classes have access to a member field. public: accessible from all classes. private: accessible only within its own class. In the spirit of encapsulation, it is common to make fields private. We still need access to these values, however. Zheng-Liang Lu Java Programming 235 / 248
52 Defining Methods So we need accessors and mutators. Accessors: to return some property of an object Mutators: to change some property of an object For example, getpoint() and setpoint(int, int) in the class Point. Zheng-Liang Lu Java Programming 236 / 248
53 Example: Point (Revisited) 1 class Point { 2 private int x; 3 private int y; 4 5 String getpoint() { 6 return "(" + x + ", " + y + ")"; 7 } 8 9 void setpoint(int a, int b) { 10 x = a; 11 y = b; 12 } 13 } Zheng-Liang Lu Java Programming 237 / 248
54 Unified Modeling Language The Unified Modeling Language (UML) is a language for specifying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling and other non-software systems. References: IntroToUML.pdf Free software: (available for all platforms) Zheng-Liang Lu Java Programming 238 / 248
55 Class Diagram Class diagrams are the most popular UML diagrams used for construction of software applications. The class diagram describes the fields and methods of a class and also the constraints imposed on the system. Zheng-Liang Lu Java Programming 239 / 248
56 Example: Point (Revisited) Modifiers are placed before the states and the methods: + for public for private Zheng-Liang Lu Java Programming 240 / 248
57 Constructors Constructors are like special methods that are called implicitly as soon as an object is instantiated. Constructor declarations look like method declarations, except that they use the name of the class and have no return type. A constructor is called by the new operator. Note that the constructors are not the part of the instances. As with methods, the constructors can be overloaded. If you don t define an explicit constructor, Java assumes a default constructor for your class. Adding any explicit constructor disables the default constructor. Zheng-Liang Lu Java Programming 241 / 248
58 Parameterized Constructors You can provide any information to the parameterized constructor for a specific object. For example, 1 class Point { Point() {} // default constructor 5 6 Point(int a, int b) { 7 x = a; 8 y = b; 9 } } Zheng-Liang Lu Java Programming 242 / 248
59 Example: Point (Revisited) 1 public class PointDemo { 2 public static void main(string[] args) { 3 Point p1 = new Point(1, 2); 4 System.out.println(p1.getPoint()); // output (1, 2) 5 6 Point p2 = new Point(); 7 System.out.println(p2.getPoint()); // output (0, 0) 8 p2.setpoint(3, 4); 9 System.out.println(p2.getPoint());// output (3, 4) 10 } 11 } Zheng-Liang Lu Java Programming 243 / 248
60 Self-reference Within an instance method or a constructor, the key word this is a reference to the current object. You can refer to any member of the current object from within an instance method or a constructor by using this. The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. From within a constructor, you can also use the this keyword to call another constructor in the same class. Zheng-Liang Lu Java Programming 244 / 248
61 Example: Point (Revisited) 1 class Point { Point(int x, int y) { 5 this.x = x; 6 this.y = y; 7 } } Note that the this operator is referenced to instance members only but not class members. Zheng-Liang Lu Java Programming 245 / 248
62 static Members When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static members. The static keyword can be applied to variables (aka class variables) methods (aka class methods) initial blocks nested classes We will see nested classes later. Zheng-Liang Lu Java Programming 246 / 248
63 The static members do not belong to the instances. These members exist when the class is loaded. So they can be invoked directly by the class name without creating an instance. For example, Math.random(). A static method can access static data member and can change its value. However, static methods cannot access to instance members directly. (Why?) Zheng-Liang Lu Java Programming 247 / 248
64 Example: Count of Points 1 class Point { private static int cnt = 0; 4 5 Point() { 6 cnt++; 7 } 8 9 Point(int x, int y) { 10 Point(); 11 this.x = x; 12 this.y = y; 13 } } Zheng-Liang Lu Java Programming 248 / 248
Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.
Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227 1... 2 int[] hist = new int[5]; 3 //
More information1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244
1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 // keywords: 8 return Zheng-Liang Lu Java Programming 186 / 244 Methods 2 Methods can be used to define reusable code, and organize and simplify code. The idea
More informationThe return Statement
The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return
More information1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199
1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize
More informationMethod Invocation. Zheng-Liang Lu Java Programming 189 / 226
Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationVariable Scope. The variable scope is the range of the program where the variable can be referenced.
Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets
More informationJava Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University
Java Programming U Hou Lok Department of Computer Science and Information Engineering, National Taiwan University Java 272 8 19 Aug., 2016 U Hou Lok Java Programming 1 / 51 A Math Toolbox: Math Class The
More informationRecursion 1. Recursion is the process of defining something in terms of itself.
Recursion 1 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is repetition
More information1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207
1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 Loops A loop can be used to make a program execute statements repeatedly without having
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationExample: Fibonacci Numbers
Example: Fibonacci Numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers
More information1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174
1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 136 / 174 Arrays An array stores a large collection of data which is of the same type. 2 // assume the size variable exists above 3
More informationHow to swap values of two variables without tmp? However, this naive algorithm is biased. 1
Shuffling over array elements 1... 2 for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } 10...
More informationExample. Password generator
Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that
More informationˆ Note that we often make a trade-off between time and space. ˆ Time complexity ˆ Space complexity. ˆ Unlike time, we can reuse memory.
ˆ We use O-notation to describe the asymptotic 1 upper bound of complexity of the algorithm. ˆ So O-notation is widely used to classify algorithms by how they respond to changes in its input size. 2 ˆ
More informationExercise: Sorting 1. ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order).
Exercise: Sorting 1 ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order). ˆ For example, A = [5, 4, 1, 2, 3]. ˆ Then the sorted array is [1, 2, 3, 4, 5]. ˆ You
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationLecture 5: Methods CS2301
Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int
More informationJump Statements. ˆ The break statement exits a for or while loop completely.
Jump Statements ˆ The break statement exits a for or while loop completely. ˆ No longer in the loop. ˆ Aka early termination. ˆ To skip the rest of the instructions in the loop and begin the next iteration,
More informationInstance Members and Static Members
Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationExercise (Revisited)
Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationScope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.
Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate
More informationZheng-Liang Lu Java Programming 45 / 79
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45
More informationChapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited
Chapter 6 Methods Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from
More informationMethods (Deitel chapter 6)
Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods
More informationMethods (Deitel chapter 6)
1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods
More informationActivity 4: Methods. Content Learning Objectives. Process Skill Goals
Activity 4: Methods Java programs are organized into classes, each of which has one or more methods, each of which has one or more statements. Writing methods allows you to break down a complex program
More informationFunctions. Systems Programming Concepts
Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value
More informationCS115 Principles of Computer Science
CS115 Principles of Computer Science Chapter 5 Methods Prof. Joe X. Zhou Department of Computer Science CS115 Methods.1 Re: Objectives in Loops Sequence and selection aside, we need repetition (loops)
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationNested Loops. A loop can be nested inside another loop.
Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationChapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
More informationAP Computer Science Chapter 10 Implementing and Using Classes Study Guide
AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within
More informationIntroduction to Programming (Java) 4/12
Introduction to Programming (Java) 4/12 Michal Krátký Department of Computer Science Technical University of Ostrava Introduction to Programming (Java) 2008/2009 c 2006 2008 Michal Krátký Introduction
More informationObject-Based Programming. Programming with Objects
ITEC1620 Object-Based Programming g Lecture 8 Programming with Objects Review Sequence, Branching, Looping Primitive datatypes Mathematical operations Four-function calculator Scientific calculator Don
More informationDr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly
More information1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 41 / 68 Example Given the radius
More informationLecture #6-7 Methods
Lecture #6-7 s 1. a. group of statements designed to perform a specific function b. may be reused many times i. in a particular program or ii. in multiple programs 2. Examples from the Java Library a.
More informationMethods: A Deeper Look
1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number
More informationData Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87
Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and
More informationCOMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal
COMSC-051 Java Programming Part 1 Part-Time Instructor: Joenil Mistal Chapter 4 4 Moving Toward Object- Oriented Programming This chapter provides a provides an overview of basic concepts of the object-oriented
More informationLecture 7: Classes and Objects CS2301
Lecture 7: Classes and Objects NADA ALZAHRANI CS2301 1 What is OOP? Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly
More informationChapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University
Opening Problem Chapter 6: Methods Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively CS1: Java Programming Colorado State University Original slides by Daniel Liang
More informationObject Oriented Programming with Java
Object Oriented Programming with Java What is Object Oriented Programming? Object Oriented Programming consists of creating outline structures that are easily reused over and over again. There are four
More informationSoftware Design and Analysis for Engineers
Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44
More informationObject Oriented Programming in C#
Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create
More informationMore About Objects. Zheng-Liang Lu Java Programming 255 / 282
More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism
More informationObjects as a programming concept
Objects as a programming concept IB Computer Science Content developed by Dartford Grammar School Computer Science Department HL Topics 1-7, D1-4 1: System design 2: Computer Organisation 3: Networks 4:
More informationMethods and Functions
Programming with Java Module 4 Methods and Functions Theoretical Part Contents 1 Module overview 3 2 Methods 3 2.1 Methods without return value (procedures).............. 3 2.2 Functions with return value
More informationJava Classes: Math, Integer A C S L E C T U R E 8
Java Classes: Math, Integer A C S - 1903 L E C T U R E 8 Math class Math class is a utility class You cannot create an instance of Math All references to constants and methods will use the prefix Math.
More informationAnatomy of a Class Encapsulation Anatomy of a Method
Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and
More informationJAVA: A Primer. By: Amrita Rajagopal
JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently
More information12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.
Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.
More informationLecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.
Lecture 05: Methods AITI Nigeria Summer 2012 University of Lagos. Agenda What a method is Why we use methods How to declare a method The four parts of a method How to use (invoke) a method The purpose
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationComputer Science II (20073) Week 1: Review and Inheritance
Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationAgenda. Objects and classes Encapsulation and information hiding Documentation Packages
Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics
More information34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
34. Recursion Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Example: Factorials Example: Fibonacci Numbers Recursion vs. Iteration References Introduction Introduction Recursion
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationhttps://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.asp...
1 of 8 8/27/2014 2:15 PM Units: Teacher: ProgIIIAPCompSci, CORE Course: ProgIIIAPCompSci Year: 2012-13 Computer Systems This unit provides an introduction to the field of computer science, and covers the
More informationCOP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi Chapter 4 Loops for while do-while Last Week Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of
More information( &% class MyClass { }
Recall! $! "" # ' ' )' %&! ( &% class MyClass { $ Individual things that differentiate one object from another Determine the appearance, state or qualities of objects Represents any variables needed for
More informationEncapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects
Administrative Stuff September 12, 2007 HW3 is due on Friday No new HW will be out this week Next Tuesday we will have Midterm 1: Sep 18 @ 6:30 7:45pm. Location: Curtiss Hall 127 (classroom) On Monday
More information1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 Functions The first thing of the design of algorithms is to divide and conquer. A large and complex problem would be solved by couples
More informationOBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1
OBJECT ORIENTED SIMULATION LANGUAGE OOSimL Reference Manual - Part 1 Technical Report TR-CSIS-OOPsimL-1 José M. Garrido Department of Computer Science Updated November 2014 College of Computing and Software
More informationFall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals
INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer
More informationswitch-case Statements
switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;
More informationChapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }
Chapter 5 Methods 5.1 Introduction A method is a collection of statements that are grouped together to perform an operation. You will learn how to: o create your own mthods with or without return values,
More information4. Java language basics: Function. Minhaeng Lee
4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only
More informationMethods. CSE 114, Computer Science 1 Stony Brook University
Methods CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Opening Problem Find multiple sums of integers: - from 1 to 10, - from 20 to 30, - from 35 to 45,... 2
More informationCH. 2 OBJECT-ORIENTED PROGRAMMING
CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED
More informationC Functions. 5.2 Program Modules in C
1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking
More informationBIL 104E Introduction to Scientific and Engineering Computing. Lecture 4
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA
More informationCOMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette
COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.
More informationIEEE Floating-Point Representation 1
IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either
More informationInterpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled
Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac
More information++x vs. x++ We will use these notations very often.
++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3
More informationMethods CSC 121 Fall 2016 Howard Rosenthal
Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More informationCS1004: Intro to CS in Java, Spring 2005
CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a
More information1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8
Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(
More informationDM550 Introduction to Programming part 2. Jan Baumbach.
DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net COURSE ORGANIZATION 2 Course Elements Lectures: 10 lectures Find schedule and class rooms in online
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS-201 Introduction to Programming with Java
CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture IX: Methods Introduction method: construct for grouping statements together to
More informationMethods CSC 121 Spring 2017 Howard Rosenthal
Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More information