JAVA Programming Concepts

Size: px
Start display at page:

Download "JAVA Programming Concepts"

Transcription

1 JAVA Programming Concepts M. G. Abbas Malik Assistant Professor Faculty of Computing and Information Technology University of Jeddah, Jeddah, KSA

2 Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum); M. G. Abbas Malik, King Abdulaziz University 2

3 Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum); Differences are these numbers M. G. Abbas Malik, King Abdulaziz University 3

4 Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. Computing sum from 1 to 10, from 20 to 30, and from 35 to 45 are very similar except that the starting and ending integers are different. Wouldn t it be nice if we could write the common code once and reuse it without rewriting it? Answer to this question is Method. The method is for creating reusable code. M. G. Abbas Malik, King Abdulaziz University 4

5 public static int sum(int num1, int num2) { int sum = 0; for (int i = num1; i <= num2; i++) sum += i; return sum; It is METHOD. Method is a reusable program/code that may take some input(s) and may give back an output. public static void main(string[] args) { System.out.println("Sum from 1 to 10 is " + sum(1, 10)); System.out.println("Sum from 20 to 30 is " + sum(20, 30)); System.out.println("Sum from 35 to 45 is " + sum(35, 45)); Method calls M. G. Abbas Malik, King Abdulaziz University 5

6 The Syntax for defining a method is: modifier return_value_data_type methodname(list of comma separated parameters) { // Method body; Modifier: Key Words of Java. Set the accessibility of the method like public, private, static Return_Value_Data_Type: what kind of data will be returned by the Method like int, char, boolean, String, double, etc. M. G. Abbas Malik, King Abdulaziz University 6

7 The Syntax for defining a method is: modifier return_value_data_type methodname(list of comma separated parameters) { // Method body; methodname: identifier that will help us to identify the Method List of comma separated parameters: input(s) to the Method. M. G. Abbas Malik, King Abdulaziz University 7

8 Modifiers are keywords that you add to those definitions to change their meanings. Java has two types of Modifiers: 1. Access Control Modifiers 2. Non Access Modifiers M. G. Abbas Malik, King Abdulaziz University 8

9 Access Control Modifiers Java provides a number of access modifiers to set access levels for classes, variables and methods. There are four access levels in Java: Visible to the package. No modifiers is needed. Visible to the class only. private keyword is used for this access level Visible to everyone. public keyword is used for this access level Visible to all the classes in the Package. protected keyword is used for this access level M. G. Abbas Malik, King Abdulaziz University 9

10 Non Access Modifiers Java provides a number of non-access modifiers to achieve many other functionality. The static modifier for creating class methods and variables The final modifier for finalizing the implementations of classes, methods, and variables. The abstract modifier for creating abstract classes and methods. The synchronized and volatile modifiers, which are used for threads. M. G. Abbas Malik, King Abdulaziz University 10

11 A method may return a value. The returnvaluetype is the data type of the value the method returns. return value; return variable;(return sum;) (return 1; return a ;) We can return only one value back to the calling function using return statement. Reurn_Value_Data_Type can be any type of data whose variable can be created in Java code. int, double, char, String, float, long, byte, short, etc. Return value can be an object. Some methods perform desired operations without returning a value. In this case, the returnvaluedatatype is the keyword void. M. G. Abbas Malik, King Abdulaziz University 11

12 Method name is an identifier. An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. An identifier cannot be a reserved or keyword word. It is recommended that the methodname starts with a small letter. Try to use meaningful names for methods. M. G. Abbas Malik, King Abdulaziz University 12

13 A Parameter is a value that is given to the method as an input. In a method, there will be ZERO or MORE Parameters. ZERO means no parameter (or input to the method). MORE means one or more parameters. When we are calling the method, then we must give the method s parameters, if any, in the method call. Examples: public static int numbersum (int startnum, int endnum) public String namestring( String firstname, String lastname) M. G. Abbas Malik, King Abdulaziz University 13

14 Method Header public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; Method Body M. G. Abbas Malik, King Abdulaziz University 14

15 public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; Modifiers Return Value Data Type Method Name Method s Parameters M. G. Abbas Malik, King Abdulaziz University 15

16 Formal Parameters public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; To Invoke or call this method, we use Method s Signature int z = max(x, y); Method s Signature Actual Parameters M. G. Abbas Malik, King Abdulaziz University 16

17 The method header specifies the modifiers, return value type, method name, and parameters of the method. In the method header, you need to declare a separate data type for each parameter. For instance, max(int num1, int num2) is correct, but max(int num1, num2) is wrong. In certain other languages, methods are referred to as procedures and functions. A value-returning method is called a function; a void method is called a procedure. M. G. Abbas Malik, King Abdulaziz University 17

18 We say define a method and declare a variable A definition defines what the defined item is But a declaration usually involves allocating memory to store data for the declared item. M. G. Abbas Malik, King Abdulaziz University 18

19 public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; x 4 M. G. Abbas Malik, King Abdulaziz University 19

20 x 4 y 3 public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; M. G. Abbas Malik, King Abdulaziz University 20

21 x 4 y 3 k public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); Method Call System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; M. G. Abbas Malik, King Abdulaziz University 21

22 x 4 y 3 k public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; num1 num2 M. G. Abbas Malik, King Abdulaziz University 22

23 x 4 y 3 k public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; num1 num2 M. G. Abbas Malik, King Abdulaziz University 23 4

24 x 4 y 3 k public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; num1 4 num2 M. G. Abbas Malik, King Abdulaziz University 24 3

25 x 4 y 3 k public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; 4 > 3 else true return num2; num1 4 num2 M. G. Abbas Malik, King Abdulaziz University 25 3

26 x 4 y 3 k public static void main (String args[]){ int x = 4; int y = 3; int k = 4; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; num1 4 num2 M. G. Abbas Malik, King Abdulaziz University 26 3

27 x 4 y 3 k 4 public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; M. G. Abbas Malik, King Abdulaziz University 27

28 x 4 y 3 k 4 public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; The maximum between 4 and 3 is 4 28

29 A value-returning method can also be invoked as a statement in Java. In this case, the caller simply ignores the return value. For example max(x,y) the returned maximum value will be ignored This is not often done but is permissible if the caller is not interested in the return value. When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached. M. G. Abbas Malik, King Abdulaziz University 29

30 When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when the method ends. A return statement is required for a value-returning method. M. G. Abbas Malik, King Abdulaziz University 30

31 A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compile error because the Java compiler thinks that it is possible that this method returns no value. Methods enable code sharing and reuse. M. G. Abbas Malik, King Abdulaziz University 31

32 Space required for the max method num2: 3 num1: 4 Space required for the max method result: 4 num2: 3 num1: 4 Space required for the main method k: y: 3 x: 4 Space required for the main method k: y: 3 x: 4 Space required for the main method k: y: 3 x: 4 Space required for the main method k: 4 y: 3 x: 4 Stack is empty (a) The main method is invoked. (b) The max method is invoked. (c) The max method is being executed. (d) The max method is finished and the return value is sent to k. (e) The main method is finished. M. G. Abbas Malik, King Abdulaziz University 32

33 i is declared and initialized public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; The main method is invoked. i: 5 33

34 j is declared and initialized public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; The main method is invoked. j: 2 i: 5 34

35 Declare k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; Space required for the main method k: j: 2 i: 5 The main method is invoked. 35

36 Invoke max(i, j) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; Space required for the main method k: j: 2 i: 5 The main method is invoked. 36

37 pass the values of i and j to num1 and num2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 37

38 pass the values of i and j to num1 and num2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 return result; The max method is invoked. 38

39 (num1 > num2) is true public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 return result; The max method is invoked. 39

40 Assign num1 to result public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 return result; The max method is invoked. 40

41 Return result and assign it to k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k:5 j: 2 i: 5 return result; The max method is invoked. 41

42 Execute print statement public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; Space required for the main method k:5 j: 2 i: 5 The main method is invoked. 42

43 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; The main method has finished. return result; 43

44 One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max). M. G. Abbas Malik, King Abdulaziz University 44

45 A return statement is not needed for a void method. A return can be used for terminating the method and returning to the method s caller. return ; This type of method does not return a value. The method performs some actions. TestVoidMethod Run M. G. Abbas Malik, King Abdulaziz University 45

46 public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) System.out.println(message); Suppose you invoke the method using nprintln( Welcome to Java, 5); What is the output? Suppose you invoke the method using nprintln( Computer Science, 15); What is the output? M. G. Abbas Malik, King Abdulaziz University 46

47 The power of a method is its ability to work with parameters. println to print any string max to find the maximum between any two int values When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method signature. This is known as parameter order association. M. G. Abbas Malik, King Abdulaziz University 47

48 The following method prints a message n times: public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) System.out.println(message); What is the output of nprintln("hello", 3)? The statement nprintln(3, "Hello") would be wrong. The arguments must match the parameters in order, number, and compatible type, as defined in the method signature. M. G. Abbas Malik, King Abdulaziz University 48

49 There are two different ways to pass parameter to methods: 1. Pass by Value 2. Pass by Reference M. G. Abbas Malik, King Abdulaziz University 49

50 VALUE When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. All primitive type parameters are passed-by-value to the method. M. G. Abbas Malik, King Abdulaziz University 50

51 x 4 y 3 k public static void main (String args[]){ int x = 4; int y = 3; int k = max(x,y); System.out.println( The maximum between + x + and + y + is + k); public static int max(int num1, int num2){ if (num1 > num2) return num1; else return num2; num1 4 num2 M. G. Abbas Malik, King Abdulaziz University 51 3

52 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; Method call A method 11 System.out.println("n inside the method is " + n); Here we are passing the parameter by-value of variable x to method s local variable n M. G. Abbas Malik, King Abdulaziz University 52 n

53 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; Method call 11 System.out.println("n inside the method is " + n); Here we are passing the parameter by-value of variable x to method s local variable n A method M. G. Abbas Malik, King Abdulaziz University 53 n 1

54 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); x 1 M. G. Abbas Malik, King Abdulaziz University 54

55 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 x 1 M. G. Abbas Malik, King Abdulaziz University 55

56 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n M. G. Abbas Malik, King Abdulaziz University 56

57 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n 1 M. G. Abbas Malik, King Abdulaziz University 57

58 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n 2 M. G. Abbas Malik, King Abdulaziz University 58

59 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n inside the method is 2 M. G. Abbas Malik, King Abdulaziz University 59 n 2

60 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n inside the method is 2 M. G. Abbas Malik, King Abdulaziz University 60 n 2

61 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n inside the method is 2 M. G. Abbas Malik, King Abdulaziz University 61

62 x 1 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n inside the method is 2 after the call, x is 1 M. G. Abbas Malik, King Abdulaziz University 62

63 1 public class Increment { 2 public static void main(string[] args) { 3 int x = 1; 4 System.out.println("Before the call, x is " + x); 5 increment(x); 6 System.out.println("after the call, x is " + x); public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); Before the call, x is 1 n inside the method is 2 after the call, x is 1 M. G. Abbas Malik, King Abdulaziz University 63

64 Testing Pass by value This program demonstrates passing values to the methods TestPassByValue Run M. G. Abbas Malik, King Abdulaziz University 64

65 M. G. Abbas Malik, King Abdulaziz University 65

66 str Pass by Reference public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; M. G. Abbas Malik, King Abdulaziz University 66

67 str x Pass by Reference 5 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; M. G. Abbas Malik, King Abdulaziz University 67

68 str x Pass by Reference 5 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; Pass by Reference M. G. Abbas Malik, King Abdulaziz University 68

69 str x Pass by Reference 5 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; Pass by Reference M. G. Abbas Malik, King Abdulaziz University 69

70 str x Pass by Reference 5 n public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; Pass by Reference M. G. Abbas Malik, King Abdulaziz University 70

71 str x Pass by Reference 5 n 5 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; message Pass by Reference M. G. Abbas Malik, King Abdulaziz University 71

72 str Pass by Reference String is changed in the method x 5 n 5 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; message Pass by Reference M. G. Abbas Malik, King Abdulaziz University 72

73 str Pass by Reference String is changed in the method x 5 n 11 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; message Pass by Reference M. G. Abbas Malik, King Abdulaziz University 73

74 str Pass by Reference String is changed in the method x 5 n 11 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; message Pass by Reference M. G. Abbas Malik, King Abdulaziz University 74

75 str Pass by Reference String is changed in the method x 5 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; Pass by Reference M. G. Abbas Malik, King Abdulaziz University 75

76 str Pass by Reference String is changed in the method x 5 public class PassByReferece{ public static void main (String []args){ String str = Pass by Reference ; int x = 5; System.out.println(str); testpassbyreference(str, x); System.out.println(str); public static void testpassbyreference(string message, int n) { message += String is changed in the method n += 6; Pass by Reference Pass by Reference String is changed in the method M. G. Abbas Malik, King Abdulaziz University 76

77 All object type parameters are passed-byreference M. G. Abbas Malik, King Abdulaziz University 77

78 Methods can be used to reduce redundant code and enable code reuse. Methods can also be used to modularize code and improve the quality of the program. GreatestCommonDivisorMethod Run PrimeNumberMethod Run M. G. Abbas Malik, King Abdulaziz University 78

79 The max method that was used earlier works only with the int data type. What if you need to determine which of two floating-point numbers has the maximum value? public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; TestMethodOverloading Run 79

80 Overloaded methods must have different parameter lists. Method overloading can not be done based on different modifiers or return types. Sometimes there are two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation causes a compile error. M. G. Abbas Malik, King Abdulaziz University 80

81 Ambiguous invocation causes a compile error. public class AmbiguousOverloading { public static void main(string[] args) { System.out.println(max(1, 2) ); public static int max (int num1, int num2){ if (num1 > num2) return num1; else return num2; public static double max(double num1, double num2){ if (num1 > num2) return num1; else return num2; max(int, int) and max(double, double) are possible candidates to match max(1, 2). Since neither is more specific than the other, the invocation is ambiguous, resulting in a compile error. 81

82 Write a method that converts a decimal integer to a hexadecimal. Hexadecimals are often used in computer systems programming To convert a decimal number d to a hexadecimal number is to find the hexadecimal digits h n, h n 1, h n 2,, h 2, h 1 andh 0 such that These numbers can be found by successively dividing d by 16 until the quotient is 0. M. G. Abbas Malik, King Abdulaziz University 82

83 Write a method that converts a decimal integer to a hexadecimal. Decimal2HexConversion Run M. G. Abbas Malik, King Abdulaziz University 83

84 The scope of a variable is the part of the program where the variable can be referenced. A variable defined inside a method is referred to as a local variable. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared and assigned a value before it can be used. A parameter is actually a local variable. The scope of a method parameter covers the entire method. M. G. Abbas Malik, King Abdulaziz University 84

85 Scope of num1 & num2 parameters public static intmax(int num1, int num2) { int result=-1; if (num1 > num2) result = num1; else result = num2; return result; Scope of result Local Variable In the For Block M. G. Abbas Malik, King Abdulaziz University 85

86 A variable declared in the initial-action part of a forloop header has its scope in the entire for loop. a variable declared inside a for-loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable Scope of i for (int i = 0; i <=10; i++){ System.out.println( We are in the loop!!! ); int j; System.out.println( The variable j is declared ); Scope of j M. G. Abbas Malik, King Abdulaziz University 86

87 We can declare a local variable with the same name in different blocks in a method Scope of x Local Variable Scope of y Local Variable M. G. Abbas Malik, King Abdulaziz University 87

88 We cannot declare a local variable twice in the same block or in nested blocks A variable can be declared multiple times in nonnested blocks but only once in nested blocks M. G. Abbas Malik, King Abdulaziz University 88

89 Do not declare a variable inside a block and then attempt to use it outside the block. Scope of i Local Variable In For Body for (int i = 0; i < 10; i++) { System.out.println(i); Trying to access variable i outside of the block or its scope M. G. Abbas Malik, King Abdulaziz University 89

90 Constants of the class PI value of ( ) E base of the natural logarithm ( ) M. G. Abbas Malik, King Abdulaziz University 90

91 Trigonometry Methods /** Return the trigonometric sine of an angle in radians */ public static double sin(double radians) /** Return the trigonometric cosine of an angle in radians */ public static double cos(double radians) /** Return the trigonometric tangent of an angle in radians */ public static double tan(double radians) /** Convert the angle in degrees to an angle in radians */ public static double toradians(double degree) M. G. Abbas Malik, King Abdulaziz University 91

92 Trigonometry Methods /** Convert the angle in radians to an angle in degrees */ public static double todegrees(double radians) /** Return the angle in radians for the inverse of sin */ public static double asin(double a) /** Return the angle in radians for the inverse of cos */ public static double acos(double a) /** Return the angle in radians for the inverse of tan */ public static double atan(double a) M. G. Abbas Malik, King Abdulaziz University 92

93 Exponent Methods /** Return e raised to the power of x (e x ) */ public static double exp(double x) /** Return the natural logarithm of x (ln(x) = log e (x)) */ public static double log(double x) /** Return the base 10 logarithm of x (log 10 (x)) */ public static double log10(double x) /** Return a raised to the power of b (a b ) */ public static double pow(double a, double b) /** Return the square root of x ( x) for x >= 0 */ public static double sqrt(double x) M. G. Abbas Malik, King Abdulaziz University 93

94 Rounding Methods /** x is rounded up to its nearest integer. Returned as a double value. */ public static double ceil(double x) /** x is rounded down to its nearest integer. returned as a double value. */ public static double floor(double x) /** x is rounded to its nearest integer. If x is equally close * to two integers, the even one is returned as a double. */ public static double rint(double x) /** Return (int)math.floor(x + 0.5). */ public static int round(float x) /** Return (long)math.floor(x + 0.5). */ public static long round(double x) M. G. Abbas Malik, King Abdulaziz University 94

95 min max & abs Methods The min and max methods are overloaded to return the minimum and maximum numbers between two numbers (int, long, float, or double). For example, max(3.4, 5.0) returns 5.0, and min(3, 2) returns 2. The abs method is overloaded to return the absolute value of the number (int, long, float, and double). Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 Math.abs(-2.1) returns 2.1 M. G. Abbas Malik, King Abdulaziz University 95

96 random Methods The random() method to generate a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). M. G. Abbas Malik, King Abdulaziz University 96

97 Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. Each character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal). To generate a random character is to generate a random integer between 0 and using the following expression: (note that since 0 <= Math.random() < 1.0, you have to add 1 to ) (int)(math.random() * ( )) M. G. Abbas Malik, King Abdulaziz University 97

98 Now let us consider how to generate a random lowercase letter. The Unicode for lowercase letters are consecutive integers starting from the Unicode for 'a', then that for 'b', 'c', and 'z'. The Unicode for 'a' is (int) a A random integer between (int)'a' and (int)'z' is (int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1) M. G. Abbas Malik, King Abdulaziz University 98

99 All numeric operators can be applied to the char operands. The char operand is cast into a number if the other operand is a number or a character. The expression for generating the random characters can be simplified from (int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1) 'a' + Math.random() * ('z' 'a' + 1) Thus random lowercase letter is (char)('a' + Math.random() * ('z' 'a' + 1)) M. G. Abbas Malik, King Abdulaziz University 99

100 To generalize the foregoing discussion, a random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as follows: (char)(ch1 + Math.random() * (ch2 ch1 + 1)) RandomCharacter TestRandomCharacter Run M. G. Abbas Malik, King Abdulaziz University 100

101 The key to developing software is to apply the concept of abstraction. Method abstraction is achieved by separating the use of a method from its implementation. The client can use a method without knowing how it is implemented. The details of the implementation are encapsulated in the method and hidden from the client who invokes the method. This is known as information hiding or encapsulation. M. G. Abbas Malik, King Abdulaziz University 101

102 If you decide to change the implementation, the client program will not be affected, provided that you do not change the method signature. The implementation of the method is hidden from the client in a black box, M. G. Abbas Malik, King Abdulaziz University 102

103 The concept of method abstraction can be applied to the process of developing programs. When writing a large program, you can use the divide-andconquer strategy, also known as stepwise refinement, to decompose it into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. M. G. Abbas Malik, King Abdulaziz University 103

104 Let us use the PrintCalendar example to demonstrate the stepwise refinement approach. PrintCalendar Run M. G. Abbas Malik, King Abdulaziz University 104

105 printcalendar(main) readinput printmonth M. G. Abbas Malik, King Abdulaziz University 105

106 printcalendar(main) readinput printmonth printmonthtitle printmonthbody M. G. Abbas Malik, King Abdulaziz University 106

107 printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname M. G. Abbas Malik, King Abdulaziz University 107

108 printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday getnumberofday sinmonth M. G. Abbas Malik, King Abdulaziz University 108

109 printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday getnumberofday sinmonth gettotalnumberofdays M. G. Abbas Malik, King Abdulaziz University 109

110 printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday getnumberofday sinmonth gettotalnumberofdays isleapyear getnumberofday sinmonth

111 M. G. Abbas Malik, King Abdulaziz University 111

112 Top-down approach is to implement one method in the structure chart at a time from the top to the bottom. Stubs can be used for the methods waiting to be implemented. A stub is a simple but incomplete version of a method. The use of stubs enables you to test invoking the method from a caller. Implement the main method first and then use a stub for the printmonth method. For example, let printmonth display the year and the month in the stub. Thus, your program may begin like this: A Skeleton for printcalendar M. G. Abbas Malik, King Abdulaziz University 112

113 Bottom-up approach is to implement one method in the structure chart at a time from the bottom to the top. For each method implemented, write a test program to test it. Both top-down and bottom-up methods are fine. Both approaches implement the methods incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together. M. G. Abbas Malik, King Abdulaziz University 113

114 Method abstraction modularizes programs in a neat, hierarchical manner. Programs written as collections of concise methods are easier to write, debug, maintain, and modify. This writing style also promotes method reusability. When implementing a large program, use the top-down or bottom-up approach. M. G. Abbas Malik, King Abdulaziz University 114

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

Chapter 6 Methods. Dr. Hikmat Jaber

Chapter 6 Methods. Dr. Hikmat Jaber Chapter 6 Methods Dr. Hikmat Jaber 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

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

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

COP3502 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

Chapter 5 Methods / Functions

Chapter 5 Methods / Functions Chapter 5 Methods / Functions 1 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a

More information

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

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 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

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

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

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

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 5 Methods rights reserved. 0132130807 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. rights reserved. 0132130807 2 1 Problem int sum =

More information

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk Chapter 5 Methods Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Introducing Methods A method is a collection of statements that

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

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

Benefits of Methods. Chapter 5 Methods

Benefits of Methods. Chapter 5 Methods Chapter 5 Methods Benefits of Methods Write a method once and reuse it anywhere. Information hiding: hide the implementation from the user Reduce complexity 1 4 Motivating Example Often we need to find

More information

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug, 1 To define methods, invoke methods, and pass arguments to a method ( 5.2-5.5). To develop reusable code that is modular, easy-toread, easy-to-debug, and easy-to-maintain. ( 5.6). To use method overloading

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

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

Methods. CSE 114, Computer Science 1 Stony Brook University

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

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Announcements PS 3 is due Thursday, 10/6 Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both sides) Tutoring

More information

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. Chapter 6 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 A Solution int sum = 0; for (int i = 1; i

More information

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. Chapter 6 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 A Solution int sum = 0; for (int i = 1; i

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

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 12. Numbers Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Numeric Type Conversions Math Class References Numeric Type Conversions Numeric Data Types (Review) Numeric Type Conversions Consider

More information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Chapter 5 Methods Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations

More information

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

int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println(Sum from 1 to 10 is  + sum); problem METHODS www.thestudycampus.com 5.1 Introduction Suppose that you need to find the sum of integers from 1 to 10, from 20 to 30, and from 35 to45, respectively. You may write the code as follows:

More information

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University Mathematical Functions, Characters, and Strings CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Static methods Remember the main method header? public static void

More information

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University Mathematical Functions, Characters, and Strings CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Static methods Remember the main method header? public static void

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 X: Methods II Passing Arguments Passing Arguments methods can accept outside information

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical

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

Chapter 4 Mathematical Functions, Characters, and Strings

Chapter 4 Mathematical Functions, Characters, and Strings Chapter 4 Mathematical Functions, Characters, and Strings Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose you need to estimate

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

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

CS171:Introduction to Computer Science II

CS171:Introduction to Computer Science II CS171:Introduction to Computer Science II Department of Mathematics and Computer Science Li Xiong 9/7/2012 1 Announcement Introductory/Eclipse Lab, Friday, Sep 7, 2-3pm (today) Hw1 to be assigned Monday,

More information

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

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

DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY DUBLIN CITY UNIVERSITY REPEAT EXAMINATIONS 2008 MODULE: Object-oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering (Year 2 & 3) B.Eng. in Information Telecomms Engineering (Year 2 &

More information

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries

More information

DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY DUBLIN CITY UNIVERSITY SEMESTER ONE EXAMINATIONS 2007 MODULE: Object Oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering B.Eng. in Information Telecommunications Engineering B.Eng.

More information

Chapter 4. Mathematical Functions, Characters, and Strings

Chapter 4. Mathematical Functions, Characters, and Strings Chapter 4 Mathematical Functions, Characters, and Strings 1 Outline 1. Java Class Library 2. Class Math 3. Character Data Type 4. Class String 5. printf Statement 2 1. Java Class Library A class library

More information

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined

More information

Computer Science is...

Computer Science is... Computer Science is... Bioinformatics Computer scientists develop algorithms and statistical techniques to interpret huge amounts of biological data. Example: mapping the human genome. Right: 3D model

More information

Methods and Data (Savitch, Chapter 5)

Methods and Data (Savitch, Chapter 5) Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private 2 public class Temperature { public static void main(string[] args) {

More information

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a, The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined

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

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

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

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

Lecture 2:- Functions. Introduction

Lecture 2:- Functions. Introduction Lecture 2:- Functions Introduction A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program. The most important reason

More information

Expressions and operators

Expressions and operators Mathematical operators and expressions The five basic binary mathematical operators are Operator Operation Example + Addition a = b + c - Subtraction a = b c * Multiplication a = b * c / Division a = b

More information

Using Free Functions

Using Free Functions Chapter 3 Using Free Functions 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates Goals Evaluate some mathematical and trigonometric functions Use arguments in function

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

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

Methods CSC 121 Fall 2014 Howard Rosenthal

Methods CSC 121 Fall 2014 Howard Rosenthal Methods CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that

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

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

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 V: Mathematical Functions, Characters, and Strings Introduction How would you estimate

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles f Cmputer Science Methds Yanyan Zhuang Department f Cmputer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Clrad Springs Opening Prblem Find the sum f integers frm 1 t 10, frm 20

More information

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

More information

Preview from Notesale.co.uk Page 2 of 79

Preview from Notesale.co.uk Page 2 of 79 COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com Page 2 of 79 tutorialspoint.com i CHAPTER 3 Programming - Environment Though Environment Setup is not an element of any Programming Language, it is the

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading

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

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

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination Tuesday, November 3, 2009 Examiners: Mathieu Petitpas

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

Introduction to Programming Using Java (98-388)

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

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination Thursday, March 11, 2010 Examiners: Milena Scaccia

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Introduction to programming using Python

Introduction to programming using Python Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 5 1 Objectives To come back on the definition of functions To invoke value-returning

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

More information

Module 4: Characters, Strings, and Mathematical Functions

Module 4: Characters, Strings, and Mathematical Functions Module 4: Characters, Strings, and Mathematical Functions Objectives To solve mathematics problems by using the methods in the Math class ( 4.2). To represent characters using the char type ( 4.3). To

More information

Top-down programming design

Top-down programming design 1 Top-down programming design Top-down design is a programming style, the mainstay of traditional procedural languages, in which design begins by specifying complex pieces and then dividing them into successively

More information

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined

More information

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. Engineering Problem Solving With C++ 4th Edition Etter TEST BANK Full clear download (no error formating) at: https://testbankreal.com/download/engineering-problem-solving-with-c-4thedition-etter-test-bank/

More information

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Methods. Eng. Mohammed Abdualal

Methods. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 8 Methods

More information

C Programs: Simple Statements and Expressions

C Programs: Simple Statements and Expressions .. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

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

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters 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 #4

More information

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write

More information

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved. 1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare

More information

C Functions. 5.2 Program Modules in C

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

Methods. Methods. Mysteries Revealed

Methods. Methods. Mysteries Revealed Methods Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private A method (a.k.a. func2on, procedure, rou2ne) is a piece of code

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Chapter 7 User-Defined Methods. Chapter Objectives

Chapter 7 User-Defined Methods. Chapter Objectives Chapter 7 User-Defined Methods Chapter Objectives Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

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

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

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out

More information

DATA TYPES AND EXPRESSIONS

DATA TYPES AND EXPRESSIONS DATA TYPES AND EXPRESSIONS Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical

More information

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Data Types, Variables and Arrays OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Identifiers in Java Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must

More information