JAVA Programming Concepts M. G. Abbas Malik Assistant Professor Faculty of Computing and Information Technology University of Jeddah, Jeddah, KSA mgmalik@uj.edu.sa
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
(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
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
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
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
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
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
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
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
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
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
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
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
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
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); 7 8 9 public static void increment(int n) { 10 n++; Method call A method 11 System.out.println("n inside the method is " + n); 12 13 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
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); 7 8 9 public static void increment(int n) { 10 n++; Method call 11 System.out.println("n inside the method is " + n); 12 13 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
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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 x 1 M. G. Abbas Malik, King Abdulaziz University 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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 Before the call, x is 1 x 1 M. G. Abbas Malik, King Abdulaziz University 55
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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 Before the call, x is 1 n M. G. Abbas Malik, King Abdulaziz University 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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 Before the call, x is 1 n 1 M. G. Abbas Malik, King Abdulaziz University 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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 Before the call, x is 1 n 2 M. G. Abbas Malik, King Abdulaziz University 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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 Before the call, x is 1 n inside the method is 2 M. G. Abbas Malik, King Abdulaziz University 59 n 2
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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 Before the call, x is 1 n inside the method is 2 M. G. Abbas Malik, King Abdulaziz University 60 n 2
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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 Before the call, x is 1 n inside the method is 2 M. G. Abbas Malik, King Abdulaziz University 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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 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
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); 7 8 9 public static void increment(int n) { 10 n++; 11 System.out.println("n inside the method is " + n); 12 13 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
Testing Pass by value This program demonstrates passing values to the methods TestPassByValue Run M. G. Abbas Malik, King Abdulaziz University 64
M. G. Abbas Malik, King Abdulaziz University 65
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
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
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
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
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
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
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
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
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
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
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
All object type parameters are passed-byreference M. G. Abbas Malik, King Abdulaziz University 77
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
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
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
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
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
Write a method that converts a decimal integer to a hexadecimal. Decimal2HexConversion Run M. G. Abbas Malik, King Abdulaziz University 83
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
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
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
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
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
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
Constants of the class PI value of (3.14159 ) E base of the natural logarithm (2.718281828 ) M. G. Abbas Malik, King Abdulaziz University 90
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
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
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
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
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
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). http://java.sun.com/javase/6/docs/api/index.html M. G. Abbas Malik, King Abdulaziz University 96
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 65535 using the following expression: (note that since 0 <= Math.random() < 1.0, you have to add 1 to 65535.) (int)(math.random() * (65535 + 1)) M. G. Abbas Malik, King Abdulaziz University 97
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
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
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
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
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
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
Let us use the PrintCalendar example to demonstrate the stepwise refinement approach. PrintCalendar Run M. G. Abbas Malik, King Abdulaziz University 104
printcalendar(main) readinput printmonth M. G. Abbas Malik, King Abdulaziz University 105
printcalendar(main) readinput printmonth printmonthtitle printmonthbody M. G. Abbas Malik, King Abdulaziz University 106
printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname M. G. Abbas Malik, King Abdulaziz University 107
printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday getnumberofday sinmonth M. G. Abbas Malik, King Abdulaziz University 108
printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday getnumberofday sinmonth gettotalnumberofdays M. G. Abbas Malik, King Abdulaziz University 109
printcalendar(main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday getnumberofday sinmonth gettotalnumberofdays isleapyear getnumberofday sinmonth
M. G. Abbas Malik, King Abdulaziz University 111
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
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
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