1 / 105

Advanced Java Programming CSE 7345/5345/ NTU 531

Welcome Back!!!. Advanced Java Programming CSE 7345/5345/ NTU 531. Session 3. Office Hours: by appt 3:30pm-4:30pm SIC 353. Chantale Laurent-Rice. Welcome Back!!!. trice75447@aol.com. claurent@engr.smu.edu. Introduction. Chapter 4 Methods. Chapter 4 Methods. Introducing Methods

cleo
Download Presentation

Advanced Java Programming CSE 7345/5345/ NTU 531

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Welcome Back!!! Advanced Java ProgrammingCSE 7345/5345/ NTU 531 Session 3

  2. Office Hours: by appt 3:30pm-4:30pm SIC 353 Chantale Laurent-Rice Welcome Back!!! trice75447@aol.com claurent@engr.smu.edu

  3. Introduction • Chapter 4 • Methods

  4. Chapter 4 Methods • Introducing Methods • Benefits of methods, Declaring Methods, and Calling Methods • Passing Parameters • Pass by Value • Overloading Methods • Ambiguous Invocation • Scope of Local Variables • Method Abstraction • The Math Class

  5. Introducing Methods Method Structure A method is a collection of statements that are grouped together to perform an operation.

  6. Methods • A method is essentially a set of program statements. It forms the fundamental unit of execution in Java. Each method exists as part of a class. During the execution of a program, methods may invoke other methods in the same or a different class.   No program code can exist outside a method, and no method can exist outside a class.

  7. Using Methods For example: public class TheMethod { public static void main(String[] args) { System.out.println(“First method”); } }

  8. Using Methods You can place additional methods outside the main( ) method. public class TheMethod{ public static void main(String[] args) { System.out.println("First method"); OutsideMainMethod(); AnotherClass.OtherOutsideMethod(); } public static void OutsideMainMethod() { System.out.println("The outside method"); } }//Save as: TheMethod.java

  9. Calling a method from another class Step 1- call it inside main( ) using the dot operator. public class TheMethod{ public static void main(String[] args) { System.out.println("First method"); OutsideMainMethod(); OtherMethod.OtherOutsideMethod(); } public static void OutsideMainMethod() { System.out.println("The outside method"); } }//Save as: TheMethod.java

  10. Calling a method from another class • 2 steps: 1- create another method outside main( )   public class AnotherClass { public static void main(String[] args) { System.out.println("Yes!"); OtherOutsideMethod(); } public static void OtherOutsideMethod() { System.out.println("Hello I am here"); } }

  11. Methods that require a single argument • Arguments are communication from you to a method. • When Java passes an argument into a method call, it is actually a copy of the argument that gets passed. • For example: • 1- double radians = 1.2345; • 2- System.out.println("Sine of " + radians + " = " + Math.sin(radians));

  12. Methods that require a single argument • The variable radians contains a pattern of bits that represents the number 1.2345. • On line 2, a copy of this bit pattern is passed into the Java Virtual Machine's method-calling apparatus.

  13. Methods that require a single argument • When an argument is passed into a method, changes to the argument value by the method do not affect the original data. • For example: • 1- public void bumper(int bumpMe) • 2- bumpMe += 15;

  14. Line 2 modifies a copy of the parameter passed by the caller. • For example: • 1- int xx = 12345; • 2- bumper(xx); • 3- System.out.println("Now xx is " + xx); • On line 2, the caller's xx is copied; the copy is passed into the bumper( ) method and incremented by 15. • Since the original xx is untouched, line 3 will report that xx is still 12345.

  15. All methods are passed by value. • All methods are passed by value. This means that copies of the arguments are provided to a method. • Any changes to those copies are not visible outside the method. • This situation changes when an array or object is passed as an argument.

  16. call-by-value argument passing • In this case the entire array or object is not actually copied. • Instead, only a copy of the reference is provided. • Therefore, any changes to the array or object are visible outside the method. • However, the reference itself is passed by value.

  17. call-by-value argument passing • Method a( ) accepts three arguments: • an int • an int array • an object reference The value of these arguments are displayed before and after the method call.

  18. call-by-value argument passing • The key points to note are: • The change to the first argument is not visible to the main( ) method. • The changes to the array and object are visible to the main( ) method.

  19. Example: public class CallByValue { public static void main(String[] args) { // Initializes variables int i = 5; int j[] = { 1, 2, 3, 4, }; StringBuffer sb = new StringBuffer("abcd"); // Display variables display(i, j, sb); // call method a(i, j, sb); //Display variables again display(i, j, sb); }

  20. Example (con’t) public static void a(int i, int j[], StringBuffer sb) { i = 7; j[0] =11; sb.append("fghi"); } public static void display(int i, int j[], StringBuffer sb) { System.out.println(i); for (int index = 0; index < j.length; index++) System.out.print(j[index] + " "); System.out.println(" "); System.out.println(sb); } }

  21. Example // TestMax.java: demonstrate using the max method public class TestMax { /** Main method */ 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); } /** Return the max between two numbers */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } }

  22. Output • Output • 5 • 1 2 3 4 • abdce • 5 • 11 2 3 4 • abcdefghij

  23. Calling Methods, cont.

  24. Calling Methods, cont.

  25. CAUTION A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } To fix this problem, delete if (n<0) in the code.

  26. Passing Parameters public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); }

  27. Methods that return Values. The return type for a method can be used in the Java • The return type for a method can be any type used in the Java programming language, which includes the primitive (or scalar) types int, double, char, and so on, as well as class type (including class types you create).

  28. Methods that return values public class GettingARaise { public static void main(String[] args) { double mySalary = 200.00; System.out.println("Demonstrating some raises"); predictRaise(mySalary); System.out.println("Demonstrating my salary " + mySalary); predictRaise(400.00); predictRaiseGivenIncrease(600, 800); }

  29. Methods that return values public static void predictRaise(double moneyAmount) { double newAmount; newAmount = moneyAmount * 1.10; System.out.println("With raise salary is " + newAmount); } public static void predictRaiseGivenIncrease(double moneyAmount, double percentRate) { double newAmount; newAmount = moneyAmount * (1 + percentRate); System.out.println("With raise predicted given salary is " + newAmount); } }

  30. Method Overloaded • Java allows you to declare several methods in a class with the same name, as long as each method has a set of parameters that is unique. • This is called method overloading. • The following application contains three forms of the move() method.

  31. Example public class MethodOverloaded { double x; double y; double z; MethodOverloaded(double x) { this(x, 0, 0) } MethodOverloaded(double x, double y) { this(x, y, 0); }

  32. Example….cont MethodOverloaded(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } // This first move form translates the point along the x-axis. void move(double x) { this.x = x; }

  33. Example… cont // This second form updates the x and y coordinates void move(double x, double y) { this.x = x; this.y = y; } // This last form modifies all coordinates void move(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } }

  34. Example public class OverloadMethods1 { public static void main(String[] args) { Point3D p = new Point3D(1.1, 3.4, -2.8); p.move(5); System.out.println("p.x = " + p.x); System.out.println("p.y = " + p.y); System.out.println("p.z = " + p.z); p.move(6, 6); System.out.println("p.x = " + p.x); System.out.println("p.y = " + p.y); System.out.println("p.z = " + p.z); p.move(7, 7, 7); System.out.println("p.x = " + p.x); System.out.println("p.y = " + p.y); System.out.println("p.z = " + p.z); } }

  35. Call by Value/Reference • All methods are passed by value. This means that copies of the arguments are provided to a method. • Any changes to those copies are not visible outside the method. • This is easy to understand for simple types.

  36. Call by Value/Reference • The situation changes when an array or object is passed as an argument. • In this case the entire array or object is not actually copied. • Instead, only a copy of the reference is provided. • Therefore, any changes to the array or object are visible outside the method. • However, the reference itself is passed by value.

  37. Call by Value/Reference • As a point of interest, arguments are passed on the stack. • They are pushed on the stacked when a method is called and popped off the stack when it returns.

  38. Example public class CallByValue { public static void main(String[] args) { // Initialize variables int i =5; int j[ ] ={1, 2, 3, 4 }; StringBuffer sb = new StringBuffer("abdce"); // Display variables display(i, j, sb); // Call method a(i, j, sb); // Display variables again display(i, j, sb); }

  39. Example…cont public static void a(int i, int j[ ], StringBuffer sb) { i = 7; j[0] = 11; sb.append("fghi"); } public static void display(int i, int j[ ], StringBuffer sb) { System.out.println(i); for (int index = 0; index < j.length; index++) System.out.print(j[index] + " " ); System.out.println(""); System.out.println(sb); } }

  40. Chapt 5One-Dimensional Array • A one-Dimensional array is a list of variables of the same type that are accessed through a common name. • An individual variable in the array is called array element. • Arrays form a convenient way to handle groups of related data. • For example, you might use an array to hold the average daily temperature over a 30-day period. • Using an array to represent this data allows you to easily manipulate it.

  41. One-Dimensional Array • To create an array, you need to perform two steps: • 1. declare the array and • type varName[ ]; • ex: int ia[ ]; • This creates a variable named ia that refers to an integer array. But it does not actually create storage for the array. • 2. allocate space for its elements. • varName = new type[size]; • Here, varName is the name of the array, type is a valid Java type, and size specifies the number of elements in the array. You can see that the new operator is used here to allocate memory for the array. • ex: is = new int[10]; • This creates an integer array with 10 elements that may be accessed via ia.

  42. Example…cont public static void display(int x[ ]) { for (int i = 0; i < x.length; i++) System.out.println(x[i] + " "); System.out.println(""); } }

  43. Example • These two steps may be combined into one Java statement as shown here: type varName = new type[size]; for example: int ia = new int[10]; ia[0] ia[1] ia[2] ia[3] ia[4] ia[5] ia[6] ia[7] ia[8] ia[9]

  44. Example public class ArrayArgument { public static void main(String[ ] args) { // Initialize vaviables int x[ ] = { 11, 12, 13, 14, 15}; // Display variables display(x); //Call method change(x); } public static void change(int x[ ]) { int y[ ] = { 21, 22, 23, 24, 25); x = y; }

  45. Structure of one-dimensional array • The figure above represents the structure of a one-dimensional array that has ten elements. • Once an array has been created, an individual element is accessed by indexing the array. This is done by specifying the number of the desired element inside square brackects. • Array indexed begin at zero. • This mean that if you want to access the first element in an array, use the zero for the index. • For example, • ia[2] = 10;

  46. Structure One-Dimensional array • This assigns the value 10 to the third element of ia. • Remember, array indexes begins at zero, so ia[2] refers to the third element. • In Java, the number of elements in an array may be obtained via the following expression: • varName.length.

  47. Pass by value of an array • The following program illustrates that references to arrays are passed by value. • An int array named x is created in the main( ) method and passed as an argument to the change( ) method.

  48. Pass-by value to an array • The change( ) method modifies it copy of the argument. • However, this modification is not visible to the caller. The display( ) method is called immediately before and after the change( ) method is invoked. • As expected, its output is the same in both cases.

  49. Arrays of objects • The steps to accomplish this are the same for arrays of simple types. 1. Declare the array and 2. Allocate space for the array elements. • The elements can then be initialized.

  50. Example:This example shows how to create an array of five strings. public class StringArray { public static void main(String[] args) { String array[] = new String[5]; array[0] = "String 0"; array[1] = "String 1"; array[2] = "String 2"; array[4] = "String 4"; System.out.println(array.length); System.out.println(array[0]; System.out.println(array[1]; System.out.println(array[2]; System.out.println(array[3]; System.out.println(array[4]; } }

More Related