1 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

Size: px
Start display at page:

Download "1 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"

Transcription

1 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

2 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 and a function should be assigned with a return type. 1 Recall the multivariate functions. 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 177 / 199

3 Example Zheng-Liang Lu Java Programming 178 / 199

4 1 modifier returntype methodname(list of Parameters) { 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 List of Parameters 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 That is, a function 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 179 / 199

5 Example Write a program which allows the user to enter the math grades in order (-1 to exit), and makes a histogram. How to count? Zheng-Liang Lu Java Programming 180 / 199

6 Scanner in = new Scanner(System.in); 3 int a, b, c, d, e, x; 4 a = b = c = d = e = 0; // a: , and so on 5 do { 6 System.out.printf("Enter ( 1 to exit): "); 7 x = in.nextint(); 8 if (x >= 90) ++a; 9 else if (x >= 80) ++b; 0 else if (x >= 70) ++c; 1 else if (x >= 60) ++d; 2 else if (x >= 0) ++e; 3 else if (x == 1) System.out.println("End of Input..."); 4 else System.out.println("Invalid input."); 5 } while (x!= 1); 6 in.close(); 7 8 System.out.printf("Total: %d\n", a + b + c + d + e); 9 0 System.out.printf("%3d %3d: ", 100, 90); 1 for (int i = 0; i < a ; i++) 2 System.out.printf(" "); 3 System.out.printf("\n"); 4 5 System.out.printf("%3d %3d: ", 89, 80); Zheng-Liang Lu Java Programming 181 / 199

7 6 for (int i = 1; i <= b; i++) 7 System.out.printf(" "); 8 System.out.printf("\n"); 9 0 System.out.printf("%3d %3d: ", 79, 70); 1 for (int i = 1; i <= c; i++) 2 System.out.printf(" "); 3 System.out.printf("\n"); 4 5 System.out.printf("%3d %3d: ", 69, 60); 6 for (int i = 1; i <= d; i++) 7 System.out.printf(" "); 8 System.out.printf("\n"); 9 0 System.out.printf("%3d %3d: ", 59, 0); 1 for (int i = 1; i <= e; i++) 2 System.out.printf(" "); 3 System.out.printf("\n"); 4... Line repeat the same pattern as Line Organize the print() method which displays the stars given the range and the number of stars. Zheng-Liang Lu Java Programming 182 / 199

8 static void print(int lower, int upper, int cnt) { 3 System.out.printf("%3d %3d: ", lower, upper); 4 for (int i = 1; i <= cnt; i++) 5 System.out.printf(" "); 6 System.out.printf("\n"); 7 } 8... In this case, print() does not return a value. Zheng-Liang Lu Java Programming 183 / 199

9 Then one can reorganize main() like this: public static void main(string[] args) { System.out.printf("Total: %d\n", a + b + c + d + e); 5 print(90, 100, a); 6 print(80, 89, b); 7 print(70, 79, c); 8 print(60, 69, d); 9 print(0, 59, e); 0 } 1... Be aware that this is not unique. Can we have a more compact form? Will be affirmative if we have an array, which is a collection of data with the same type, instead of five scalar variables. Zheng-Liang Lu Java Programming 184 / 199

10 Exercise Write a program which prints a certain number of star lines determined by the user repeatedly until the input is negative. Input: n 0 A while loop which makes the program alive until n < 0 Allow the user to choose a symbol in addition to *? Zheng-Liang Lu Java Programming 185 / 199

11 static void printstar(int x, String marker) { 3 for (int i = 1; i <= x; ++i){ 4 for (int j = 1; j <= i; ++j) 5 System.out.printf("%s", marker); 6 System.out.println(); 7 } 8 } Scanner in = new Scanner(System.in); 3 int n; 4 String marker; 5 while (true) { 6 System.out.println("Enter a positive integer? "); 7 n = in.nextint(); 8 if (n < 0) break; 9 System.out.println("Choose a symbol? "); 0 marker = in.next(); 1 printstar(n, marker); 2 } 3 in.close(); 4 System.out.println("Bye."); 5... Zheng-Liang Lu Java Programming 186 / 199

12 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 187 / 199

13 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 188 / 199

14 Zheng-Liang Lu Java Programming 189 / 199

15 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 190 / 199

16 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); 0 p(); 1 System.out.printf("%d\n", i); 2 } 3 4 static void p() { 5 i = i + 1; 6 System.out.printf("%d\n", i); 7 } 8 } Zheng-Liang Lu Java Programming 191 / 199

17 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 192 / 199

18 Exercise (Revisit) Star printing Write a program which prints a certain number of lines with some symbol determined by the user. The program repeats its procedure until the number of lines is negative. If the user enter -1, use * as the default symbol. Zheng-Liang Lu Java Programming 193 / 199

19 static void print(int x, String marker) { 3 for (int i = 1; i <= x; ++i){ 4 for (int j = 1; j <= i; ++j) 5 System.out.printf("%s", marker); 6 System.out.println(); 7 } 8 } 9 0 static void print(int x) { 1 for (int i = 1; i <= x; ++i){ 2 for (int j = 1; j <= i; ++j) 3 System.out.printf(" "); 4 System.out.println(); 5 } 6 } 7... print()s are overloaded. Zheng-Liang Lu Java Programming 194 / 199

20 public static void main (String[] args) { while (true) { 5 System.out.println("Enter a positive integer? "); 6 n = in.nextint(); 7 if (n < 0) break; 8 System.out.println("Choose a symbol? ( 1 to use the default symbol )"); 9 marker = in.next(); 0 if (marker.equals(" 1")) 1 print(n); 2 else 3 print(n, marker); 4 } } 7... in.next() returns a string from keyboard. Be aware that in.next() skips the blanks in the beginning of line. marker.equals() is one method of String object. Zheng-Liang Lu Java Programming 195 / 199

21 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 7 and Math.E 8. 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. 7 π 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 196 / 199

22 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 197 / 199

23 static char getrandomuppercaseletter() { 3 return (char)(math.random() ( Z A ) + A ); 4 } 5 6 static char getrandomlowercaseletter() { 7 return (char)(math.random() ( z a ) + a ); 8 } 9 0 static char getrandomdigitalcharacter() { 1 return (char)(math.random() ( 9 0 ) + 0 ); 2 } 3... Zheng-Liang Lu Java Programming 198 / 199

24 public static void main (String[] args) { 3 System.out.println("Generating a password..."); 4 // def: 0 > upper case, 1 > lower case, 2 > numbers 5 int type; 6 for (int i = 1; i <= 10; ++i){ 7 type = (int)((math.random() 10) % 3); 8 switch (type) { 9 case 0: 0 System.out.printf("%c", getrandomuppercaseletter()) ; 1 break; 2 case 1: 3 System.out.printf("%c", getrandomlowercaseletter()) ; 4 break; 5 case 2: 6 System.out.printf("%c", getrandomdigitalcharacter() ); 7 break; 8 } 9 } 0 } 1... Zheng-Liang Lu Java Programming 199 / 199

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

1 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 / 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 information

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

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

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 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 All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚,

More information

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

1 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 information

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Method 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 information

The return Statement

The 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 information

Cloning 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, 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 information

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Java 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 information

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

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

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

1 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 information

Example: Monte Carlo Simulation 1

Example: 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 information

Example. Password generator

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

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

Nested Loops. A loop can be nested inside another loop.

Nested 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 information

Zheng-Liang Lu Java Programming 45 / 79

Zheng-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 information

Object-Based Programming. Programming with Objects

Object-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 information

1 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 / 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 information

AP CS Unit 3: Control Structures Notes

AP 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

Values in 2 s Complement

Values in 2 s Complement Values in 2 s Complement Java uses an encoding known as 2 s complement 1, which means that negative numbers are represented by inverting 2 all of the bits in a value, then adding 1 to the result. For example,

More information

Exercise (Revisited)

Exercise (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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

Cloning 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, 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 information

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Data 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Activity 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 information

Lecture 5: Methods CS2301

Lecture 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 information

Example: Fibonacci Numbers

Example: 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 information

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

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

How 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 information

www.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some

More information

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Chapter 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 information

Lecture #6-7 Methods

Lecture #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 information

Java Classes: Math, Integer A C S L E C T U R E 8

Java 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 information

Arithmetic Compound Assignment Operators

Arithmetic 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 information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, 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 information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

JAVA 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 information

++x vs. x++ We will use these notations very often.

++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 information

COMP 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 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 information

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Logic is the anatomy of thought. John Locke ( ) This sentence is false. Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than

More information

IEEE Floating-Point Representation 1

IEEE 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 information

CS-201 Introduction to Programming with Java

CS-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 information

Methods (Deitel chapter 6)

Methods (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 information

Methods (Deitel chapter 6)

Methods (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 information

( &% class MyClass { }

( &% 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 information

The Math Class. Using various math class methods. Formatting the values.

The Math Class. Using various math class methods. Formatting the values. The Math Class Using various math class methods. Formatting the values. The Math class is used for mathematical operations; in our case some of its functions will be used. In order to use the Math class,

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH INTRODUCTION TO JAVA PROGRAMMING, LIANG (PEARSON 2014) MATHEMATICAL FUNCTIONS Java

More information

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters

More information

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133 Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object

More information

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes Fall 2018 Margaret Reid-Miller Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

More information

4. Java language basics: Function. Minhaeng Lee

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

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted 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

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Computer Programming, I. Laboratory Manual. Experiment #7. Methods Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #7

More information

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

1 class Lecture3 { 2 3 Selections // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted

More information

Functions. Systems Programming Concepts

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

Introduction to Programming (Java) 4/12

Introduction 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 information

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Lecture 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 information

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods 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 information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods 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 information

Arithmetic Compound Assignment Operators

Arithmetic 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 / 172 Example 1... 2 int x = 1; 3 System.out.println(x);

More information

Chapter 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 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 information

switch-case Statements

switch-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 information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 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 information

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

1 class Lecture3 { 2 3 Selections // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted

More information

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression. Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then

More information

Array. Array Declaration:

Array. Array Declaration: Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and

More information

Pace University. Fundamental Concepts of CS121 1

Pace 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 information

CS115 Principles of Computer Science

CS115 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 information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux CS 231 Data Structures and Algorithms Fall 2018 Event Based Programming Lecture 06 - September 17, 2018 Prof. Zadia Codabux 1 Agenda Event-based Programming Misc. Java Operator Precedence Java Formatting

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and

More information

Loops (while and for)

Loops (while and for) Loops (while and for) CSE 1310 Introduction to Computers and Programming Alexandra Stefan 1 Motivation Was there any program we did (class or hw) where you wanted to repeat an action? 2 Motivation Name

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

LAB 13: ARRAYS (ONE DIMINSION)

LAB 13: ARRAYS (ONE DIMINSION) Statement Purpose: The purpose of this Lab. is to practically familiarize student with the concept of array and related operations performed on array. Activity Outcomes: As a second Lab on Chapter 7, this

More information

Important Java terminology

Important Java terminology 1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as

More information

Review for Test 1 (Chapter 1-5)

Review for Test 1 (Chapter 1-5) Review for Test 1 (Chapter 1-5) 1. Introduction to Computers, Programs, and Java a) What is a computer? b) What is a computer program? c) A bit is a binary digit 0 or 1. A byte is a sequence of 8 bits.

More information

AP Computer Science Java Mr. Clausen Program 6A, 6B

AP Computer Science Java Mr. Clausen Program 6A, 6B AP Computer Science Java Mr. Clausen Program 6A, 6B Program 6A LastNameFirstNameP6A (Quadratic Formula: 50 points) (Including complex or irrational roots) Write a program that begins by explaining the

More information

A Foundation for Programming

A Foundation for Programming 2.1 Functions A Foundation for Programming any program you might want to write objects functions and modules build bigger programs and reuse code graphics, sound, and image I/O arrays conditionals and

More information

Topic 12 more if/else, cumulative algorithms, printf

Topic 12 more if/else, cumulative algorithms, printf Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software,

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information

More information

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information. Chapter 3 Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus Lecture 03 - Introduction To Functions Christopher M. Bourke cbourke@cse.unl.edu 3.1 Building Programs from Existing

More information

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

BASIC INPUT/OUTPUT. Fundamentals of Computer Science BASIC INPUT/OUTPUT Fundamentals of Computer Science Outline: Basic Input/Output Screen Output Keyboard Input Simple Screen Output System.out.println("The count is " + count); Outputs the sting literal

More information

Object Oriented Methods : Deeper Look Lecture Three

Object Oriented Methods : Deeper Look Lecture Three University of Babylon Collage of Computer Assistant Lecturer : Wadhah R. Baiee Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces,

More information

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Fall 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 information

Programming Exercise 7: Static Methods

Programming Exercise 7: Static Methods Programming Exercise 7: Static Methods Due date for section 001: Monday, February 29 by 10 am Due date for section 002: Wednesday, March 2 by 10 am Purpose: Introduction to writing methods and code re-use.

More information

Following is the general form of a typical decision making structure found in most of the programming languages:

Following is the general form of a typical decision making structure found in most of the programming languages: Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name: CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, 2006 Name: Email: This is a closed note, closed book exam. There are II sections worth a total of 200 points. Plan your time accordingly.

More information

M e t h o d s a n d P a r a m e t e r s

M e t h o d s a n d P a r a m e t e r s M e t h o d s a n d P a r a m e t e r s Objective #1: Call methods. Methods are reusable sections of code that perform actions. Many methods come from classes that are built into the Java language. For

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates

More information

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14 int: integers, no fractional part 1, -4, 0 double: floating-point numbers (double precision) 0.5, -3.11111, 4.3E24, 1E-14 A numeric computation overflows if the result falls outside the range for the number

More information

Methods: A Deeper Look

Methods: 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 information

CT 229 Java Syntax Continued

CT 229 Java Syntax Continued CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment

More information