1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Lecture 2: Object Oriented Programming I
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
1 Repetition structures Overview while statement for statement do while statement.
1. 2 Introduction to Methods  Type of Variables  Static variables  Static & Instance Methods  The toString  equals methods  Memory Model  Parameter.
1 Classes Overview l Classes as Types l Declaring Instance Variables l Implementing Methods l Constructors l Accessor and Mutator Methods.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
1 More on 1-D Arrays Overview l Array as a return type to methods l Array of Objects.
1 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
1 Parameter Passing Revisited Overview l Parameter passing l Passing parameters by value l Passing parameters by reference l Some Examples l Preview: Data.
SCOPE & I/O CSC 171 FALL 2004 LECTURE 5. CSC171 Room Change Thursday, September 23. CSB 209 THERE WILL BE A (group) QUIZ! - topic: the CS department at.
1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
1 Memory Model of A Program, Methods Overview l Closer Look at Methods l Memory Model of JVM »Method Area »Heap »Stack l Preview: Parameter Passing.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
1 Recursion Overview l Introduction to recursion and recursive methods l Simple popular recursive algorithms l Writing recursive methods l Preview: 1-D.
1 Parameter Passing Revisited Overview l Parameter passing l Passing parameters by value l Passing parameters by reference l Some Examples l Preview: Introduction.
1 Memory Model of A Program, Methods Overview l Memory storage areas for an executing program l Introduction to methods and methods definitions l General.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Supplementary for method, DCO10803, Quarter 3, Page 1 of 7 Object-Oriented Programming and Design DCO10803 Supplementary for method  Prototype.
1 More on 1-D Array Overview l Array as a return type to methods l Array of Objects l Array Cloning l Preview: 2-D Arrays.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Saravanan.G.
Classes, Objects, and Methods
CS1101: Programming Methodology Recitation 3 – Control Structures.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
Methods. Overview Class/Library/static vs. Message/non-static return and void Parameters and arguments.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Building java programs, chapter 3 Parameters, Methods and Objects.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
1 Week 8 l Methods l Parameter passing Methods. 2 Using Methods l Methods are actions that an object can perform. l To use a method you invoke or call.
Scheme -> Java Conversion Course 2001 Lab Session 2/2.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Java – Methods Lecture Notes 5. Methods All objects, including software objects, have state and behavior. example, a student as an object has name, address,
Methods.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
05 Method Calling. 2 What is a Method? Declaring a Method Method Calling Method Call Stack Parameter Passing Pass by Value Outline.
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Objects, Classes, Program Constructs
Methods.
Chapter 8: Collections: Arrays
ATS Application Programming: Java Programming
Classes, Objects, and Methods
Classes & Objects: Examples
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
Group Status Project Status.
CS2011 Introduction to Programming I Methods (II)
Exception Handling Contents
Exceptions.
Handout-16 Recursion Overview
Exceptions.
Presentation transcript:

1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference

2 Closer Look at Methods l Methods are the fundamental building blocks of a Java program. l They can be instant methods, usually written to implement a particular behavior of an object – e.g. withdraw method l They can also be class method, usually written to compute some value or perform some action – e.g main method or sqrt method of the Math class. l The general format of a method is as follows: Modifiers ReturnType methodName(Parameters) [Exceptions] { Statement1; Statement2; * StatementN; }

3 Closer Look at Methods (cont’d) l A method definition could begin with one or more of the following modifiers: [public | private | protected | ] [ static | ] [ final | ] l The first group are called access modifies as they indicate the type of permission or restriction associated with the method. l The following table indicate the meaning of each. l A method can also be static indicating that it is a class method or non-static, indicating that it is an instance method. l A method may also be final, indicating that it can not be overridden by subclasses. classpackagesub-classworld public  protected  default  private 

4 Closer Look at Methods (cont’d) Return Type: l The return type indicates the type of value the method returns – int, double, …,or object reference l If no value or reference is returned by a method, the return type is specified as void. l In Java, a method cannot return more than one value. Parameters: l A method may have zero or more parameters. l Parameters are used to receive input from the method caller. l Each parameter is specified by its type and name. l The parameters in a method definition are called formal parameters. l The values used to call the method are called actual parameters. return statement: l If the return type of a method is not void, then there must be at least one return statement that returns the result of the method.

5 Methods Invocation An Example: import java.io.*; class MethodInvocation { static double doubleParameter(double num) { double d; d = 2*num; return d; } static double squareParameter (double num){ double sq; sq = num*num; return sq; }

6 Methods Invocation public static void main (String[] args) throws IOException { BufferedReader stdin= new BufferedReader( new InputStreamReader(System.in)); double n, d,sq, answer; System.out.println("Enter a number:"); String input = stdin.readLine(); n=Double.parseDouble(input); d = doubleParameter(n); sq = squareParameter(d); System.out.println("Your input is: "+ n); System.out.println("Double of "+n+"is"+d); System.out.println("Square of "+d+"double is "+ sq); }

7 Parameter Passing l In Java variables of primitive types are Passed by value while objects are passed by reference l “Passing by value” means that the argument’s evaluated value is copied, and is passed to the method. »Inside the method this copy can be modified at will, and does not affect the original argument l Passing by reference means that a reference to (i.e., the address of) the argument is passed to the method. »Using the reference, the called method is actually directly accessing the argument, not a copy of it »Any changes the method makes to the parameter are made to the actual object used as the argument »So after you return from the method, that object will retain any new values set in the method

8 Parameter Passing : Passing Values import java.io.*; class SwapPrimitives { static void swap(int first, int second) { int temp=first; first=second; second=temp; } public static void main (String[] args) throws IOException { BufferedReader stdin= new BufferedReader( new InputStreamReader(System.in)); int n1, n2; System.out.print("Enter first integer: ”); n1=Integer.parseInt(stdin.readLine()); System.out.print("Enter Second integer: ”); n2=Integer.parseInt(stdin.readLine()); System.out.println("Values before swapping are: "+n1+" and "+n2); swap(n1, n2); System.out.println("Values before swapping are: "+n1+" and "+n2); }

9 Parameter Passing : Passing Objects class Person { int age; String name; public void print(){ System.out.println(age + " " + name); } public Person(int a, String b) { age = a; name = b; }

10 Parameter Passing : Passing Objects class Test { static int i = 10; public static void main(String[] args) { String str = "First Message."; Person p1 = new Person(21, “Khalid"); Person p2 = new Person(20,“Amr"); mixUp(i, str, p1, p2); System.out.println("i: " + i + " str: " + str); p1.print(); p2.print(); } static void mixUp(int i, String str, Person one, Person two) { i++; str = "Second Message."; one = two; one.age = 34; one.name = “Ali"; }