Lesson 5 Methods

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

METHODS

Methods/ Functions()
Today’s Agenda
• Topics:
• Introduction
• Static Methods
• Method Declarations
• Method Calls
• Scope of Declarations
• Method Overloading
• Random numbers
• Reading:
• Java how to program Late objects version (D & D)
• Chapter 5
• The Java Tutorial
• https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Introduction
• A method is a block of code that performs a specific task.
• The method in Java or Methods of Java is a collection of statements that
perform some specific task and return the result to the caller.

Advantage of Method
• Code Reusability
• Easy modification
• Code readability
• Code Optimization
Method Declaration
• The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments.
• It has six components that are known as method header, as we have shown in
the following figure.

• The syntax to declare a method is:


• returnType methodName() {
• // method body
•}
Method Declaration Con’t
• Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
• Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
• Public: The method is accessible by all classes when we use public specifier in our application.
• Private: When we use a private access specifier, the method is accessible only in the classes in which it is
defined.
• Protected: When we use protected access specifier, the method is accessible within the same package or
subclasses in a different package.
• Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
• Return Type: Is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
• Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
• Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
• Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method
• Rules to Name a Method
• While defining a method, remember that the method name must be a verb and start
with a lowercase letter.
• If the method name has more than two words, the first name must be a verb followed by
an adjective or noun.
• In the multi-word method name, the first letter of each word must be in uppercase
except the first word. For example, findSum, computeMax, setX, and getX.
• Single-word method name: sum(), area()
• Multi-word method name: areaOfCircle(), stringComparision()
• It is also possible that a method has the same name as another method name in
the same class, it is known as method overloading.

Types of Method
• There are two types of methods in Java:
• Predefined Method
• User-defined Method
Predefined Method
• The method that is already defined in the Java class libraries is known as
predefined methods/standard library method/built-in method.
• We can directly use these methods just by calling them in the program at any
point.
• Some pre-defined methods are length(), compareTo(), main(), print(), max(),
sqrt(), etc.
• When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already
stored in the library.
• Each and every predefined method is defined inside a class.
• Such as print() method is defined in the java.io.PrintStream class. It prints the
statement that we write inside the method. E.g., print("Java"), it prints Java on
the console.
Predefined Method
• Example 1: Java Standard Library Method
• public class Main {
• public static void main(String[] args) {
• // using the sqrt() method
• System.out.print("Square root of 4 is: " + Math.sqrt(4));
• }
•}
User-defined Method
• The method written by the user or programmer is known as a user-defined method.
• These methods are modified according to the requirement.

2 Ways to Create Method in Java


• 1. Instance Method: Access the instance data using the object name. Declared inside
a class.
• Syntax:
• // Instance Method
• void method_name(){
• body // instance area
• }
• 2. Static Method: Access the static data using class name. Declared inside class
with static keyword.
• Syntax:
• //Static Method
• static void method_name(){
• body // static area
• }
User-defined Method
• How to Call or Invoke a User- • //user defined method
defined Method • public static void findEvenOdd(int
num)
• Example 1: User defined method that checks if a
number is even or odd. •{
• import java.util.Scanner; • //method body
• public class EvenOdd • if(num%2==0)
•{ • System.out.println(num+" is even");
• public static void main (String args[])
• else
•{
• System.out.println(num+" is odd");
• //creating Scanner class object
• }
• Scanner scan=new Scanner(System.in);
• }
• System.out.print("Enter the number: ");
• //reading value from user
• int num=scan.nextInt();

• //method calling
• findEvenOdd(num);
•}
User-defined Method
• How to Call or Invoke a User-defined Method - Explanation
• We have defined the above method named findevenodd().
• It has a parameter num of type int.
• The method does not return any value that's why we have used void.
• The method body contains the steps to check the number is even or odd.
• If the number is even, it prints the number is even, else prints the number is
odd.
• Once we have defined a method, it should be called. When we call or invoke a
user-defined method, the program control transfer to the called method.
• When the compiler reaches at line findEvenOdd(num), the control transfer to
the method and gives the output accordingly.
User-defined Method
• Example 2: A program that adds two numbers and return a value to the calling
method.
• public class Addition
•{
• public static void main(String[] args)
•{
• int a = 19;
• int b = 5;
• //method calling
• int c = add(a, b); //a and b are actual parameters
• System.out.println("The sum of a and b is= " + c);
•}
• //user defined method
• public static int add(int n1, int n2) //n1 and n2 are formal parameters
•{
• int s;
• s=n1+n2;
• return s; //returning the sum
•}
•}
User-defined Method
• Explanation in Example 2 above:

• We have defined a method named add() that sum up the two numbers.

• It has two parameters n1 and n2 of integer type.

• The values of n1 and n2 correspond to the value of a and b, respectively.

• Therefore, the method adds the value of a and b and store it in the variable s
and returns the sum.
Predefined Method
• Example 3: Java Standard Library Method using a for loop for code reusability.
• public class Main {
• // method defined
• private static int getSquare(int x){
• return x * x;
• }

• public static void main(String[] args) {


• for (int i = 1; i <= 5; i++) {

• // method call
• int result = getSquare(i);
• System.out.println("Square of " + i + " is: " + result);
• }
• }
• }
Static Method
• A method that has static keyword is known as static method.
• In other words, a method that belongs to a class rather than an instance of a
class is known as a static method.
• We can also create a static method by using the keyword static before the
method name.
• The main advantage of a static method
• we can call it without creating an object.
• It can access static data members and also change the value of it.
• It is used to create an instance method.
• It is invoked by using the class name.
• The best example of a static method is the main() method.
Static Method Con’t
• Example of static method

• public class Display


• {
• public static void main(String[] args)
• {
• show();
• }
• static void show()
• {
• System.out.println("It is an example of static method.");
• }
• }
Instance Method
• The method of the class is known as an instance method.
• It is a non-static method defined in the class.
• Before calling or invoking the instance method, it is necessary to create an object of its class.
• public class InstanceMethodExample
• {
• public static void main(String [] args)
• {
• //Creating an object of the class
• InstanceMethodExample obj = new InstanceMethodExample();
• //invoking instance method
• System.out.println("The sum is: "+obj.add(12, 13));
• }
• int s;
• //user-defined method because we have not used static keyword
• public int add(int a, int b)
• {
• s = a+b;
• //returning the sum
• return s;
• }
• }
Instance Method
• There are two types of instance method:
• Accessor Method
• Mutator Method
• Read and make short notes on these instances, with program examples on
each.
Method Parameters
• A method parameter is a value accepted by the method.

• As mentioned earlier, a method can also have any number of parameters. For
example;
• // method with two parameters

• int addNumbers(int a, int b) {

• // code

•}

• // method with no parameter

• int addNumbers(){

• // code

•}
Method Parameters Con’t
• If a method is created with parameters, we need to pass the corresponding
values while calling the method.

• For example;
• // calling the method with two parameters

• addNumbers(25, 15);

• // calling the method with no parameters

• addNumbers()
Method Parameters Con’t
• Example 1: Method Parameters • public static void main(String[] args) {
• class Main { • // create an object of Main
• // method with no parameter
• Main obj = new Main();
• public void display1() {
• // calling method with no parameter
• System.out.println("Method without
• obj.display1();
parameter");

• } • // calling method with the single

• // method with single parameter


parameter

• public void display2(int a) { • obj.display2(24);

• System.out.println("Method with a • }
single parameter: " + a); •}
• }
Method Parameters Con’t - Explanation
• The parameter of the method is int. Hence, if we pass any other data type
instead of int, the compiler will throw an error. It is because Java is a strongly
typed language.

• The argument 24 passed to the display2() method during the method call is
called the actual argument.

• The parameter num accepted by the method definition is known as a formal


argument.

• We need to specify the type of formal arguments.

• The type of actual arguments and formal arguments should always match.
Advantages of using methods in Java:
• Reusability: Methods allow you to write code once and use it many times, making your
code more modular and easier to maintain.
• Abstraction: Methods allow you to abstract away complex logic and provide a simple
interface for others to use. This makes your code more readable and easier to
understand.
• Improved readability: By breaking up your code into smaller, well-named methods,
you can make your code more readable and easier to understand.
• Encapsulation: Methods allow you to encapsulate complex logic and data, making it
easier to manage and maintain.
• Separation of concerns: By using methods, you can separate different parts of your
code and assign different responsibilities to different methods, improving the structure
and organization of your code.
• Improved modularity: Methods allow you to break up your code into smaller, more
manageable units, improving the modularity of your code.
• Improved testability: By breaking up your code into smaller, more manageable units,
you can make it easier to test and debug your code.
• Improved performance: By organizing your code into well-structured methods, you
can improve performance by reducing the amount of code that needs to be executed
and by making it easier to cache and optimize your code.
1.Introduction
• Best way to develop and maintain a large program is to
construct it from small, simple pieces.
• It is called divide and conquer
• Normally, methods are called on specific objects
• Example: toUpperCase() method from a string object.
• declare, construct, and initialize a String object
• Note: (We will cover the details on creating objects later)
String s1 = new String("abc");

• call the toUpperCase() method on the object referred to by the variable s1


• construct a new object "ABC"
• returns a reference to this new object, and
• stored it into s2 in its declaration.

String s2 = s1.toUpperCase();
1.Introduction
Instance Methods String s2 = s1.toUpperCase();

• Instance Methods:
• Operations we can apply to objects to examine/change their state
• We use a variable name to specify which object to call a method on
(the object it refers to)
• we write the name of the variable, followed by a period (a separator), followed
by the name of the method, all followed by a pair of open/close parentheses
(separators/delimiters).
• Example: the toUpperCase method is called in the form
object-reference.toUpperCase()

• returns as a result a reference to a new String object whose state is the upper-case
version of the state of the object to which object-reference refers.
1.Introduction String str = new String("abcd");
String Methods
• Some popular methods in the String class:

Python Java Description


str[3] str.charAt(3) Return the char value at the specified index
Return a string that is a substring of this string. The
str.substring(2,
str[2:5] substring begins at the specified beginIndex and
5)
extends to the character at index endIndex - 1
len(str) str.length() Return the length of the string
Return the index of the first occurrence of a specified
str.find('x') str.indexOf('x')
text in a string
str.split() str.split('\s') Split the string on whitespace into a list/array of strings
str.split(',') str.split(',') Split the string at ',' into a list/array of strings
str + str str.concat(str) Concatenate two strings together
str.strip() str.trim() Remove any whitespace at the beginning or end
1.Introduction
Program Modules in Java
• The statements in method bodies are written only once, are hidden from
other methods and can be reused from several locations in a program.
• Software reusability
• using existing methods as building blocks to create new programs
• Often, you can create programs from existing classes and methods rather
than by building customized code
• Dividing a program into meaningful methods makes the program easier
to debug and maintain.
• Every method should be limited to performing a single, well-defined task, and the
name of the method should express that task effectively
1.Introduction
Program Modules in Java
• A method is invoked by a method call
• When the called method completes its task, it returns control
—and possibly a result — to the caller
• Similar to the hierarchical form of management
• A boss (the caller) asks a worker (the called method) to perform a task and
report back (return) the results after completing the task
• The boss method does not know how the worker method performs its
designated tasks
• The worker may also call other worker methods, unbeknown to the boss
• This “hiding” of implementation details promotes good software engineering
1.Introduction
Calling Methods
• Three ways to call a method:
• Using a method name by itself to call another method of the same class

returnVar = methodName(parameters);

• Using an object’s variable name followed by a dot (.) and the method name to call a
non-static method of the object
returnVar = an_object.methodName(parameters);

• Using the class name and a dot (.) to call a static method of a class
String s2 = s1.toUpperCase();

returnVar = className.methodName(parameters);

int value = Math.min(10, 2);


2.Static Methods
• Sometimes a method performs a task that does not depend on the contents
of any object
• Method applies to the class in which it’s declared as a whole and is known as
a static method or a class method
• For any class imported into your program, you can call the class’s static
methods by specifying the name of the class in which the method is declared,
followed by a dot (.) and the method name
• All Math class methods are static
• Method arguments may be constants, variables or expressions
• Example:

System.out.println(Math.min(20, 1));
2.Static Methods
The Math class
2.Static Methods
The Math class
• Class Math declares two constants
• Math.PI (3.141592653589793) is the ratio of a circle’s circumference to its diameter
• Math.E (2.718281828459045) is the base value for natural logarithms (calculated with
static Math method log)
• These constants are declared in class Math with the modifiers public, static
and final.
• public allows you to use these fields in any other classes
• static allows them to be accessed via the class name Math and a dot (.) separator
• final indicates that they are constants—value cannot change after they are initialized.
• A class’s variables are sometimes called fields.
2.Static Methods
The Main method
• Why Is the method main declared static?
• When you execute the Java Virtual Machine (JVM) with the java
command, the JVM attempts to invoke the main method of the class
you specify.
• i.e. This is the line at which the program will start executing.
• All Java applications begin execution by calling main.
• Declaring main as static allows the JVM to invoke main without
creating an object of the class.
• If we omit static keyword before main, Java program will successfully
compile but it won't execute.
3.Method Declarations (static methods)
Method Header
• Method header: Modifiers, return type, method name and parameters
For now, we begin every method declaration
• A public method is “available to the public” with the keywords public and static
• It can be called from methods of other classes
• static methods: can be called without creating an object of class.
• Method name : Style convention :
• Class names, method names and variable names are all use the same camel case naming
scheme (e.g. toUpperCase)
• return type : Specifies the type of data a method returns
• void : perform a task but will not return any information
public static void methodName1(int parameter) { ... }
public static int methodName2(int parameter) { ... }

• Parameters: (additional information to perform its task)


• Defined in a comma-separated parameter-list
• Each parameter must specify a type and an identifier
• They are local variables of that method and can be used only in that method’s body
3.Method Declarations (static methods)
Method body
• Method body
• Delimited by left and right braces
• Contains one or more statements that perform the method’s task
• A return statement returns a value (or just control) to the point in the
program from which the method was called
• There are three ways to return control to the statement that calls a method
• If the method does not return a result, control returns when the program flow reaches
the method-ending right brace or when the statement return; executes
• If the method returns a result, the statement
return expression;
evaluates the expression, then returns the result to the caller

public static void methodName1(int parameter) {


...
}
3.Method Declarations (static methods) L05Code.java

Example
• Example: determines and returns the largest of two double values
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 2 numbers separated by
spaces: ");
double num1 = input.nextDouble();
double num2 = input.nextDouble();
double result = max_of_2(num1, num2);
System.out.println("Maximum is: " + result);
}

public static double max_of_2(double x, double y) {


return Math.max(x, y);
}

Enter 2 numbers separated by spaces: 9.35 2.74


Maximum is: 9.35
98 Fahrenheit is 36 Celsius

26 Celsius is 78 Fahrenheit
Exercise 1
• Consider the following code fragment in Main:
int f = 98, c = 26;
System.out.printf("%d Fahrenheit is %d Celsius%n%n", f, celsius(f));
System.out.printf("%d Celsius is %d Fahrenheit%n%n",c, fahrenheit(c));

• Complete two static methods to convert Celsius temperature to


Fahrenheit and Fahrenheit to Celsius
Return an int!

public static int celsius(int fahrenheitTemperature) {


...

public static int fahrenheit(int celsiusTemperature) {


...
4.Method Calls
Activation Records
• When a program calls a method, the called method must know how to
return to its caller, so the return address of the calling method is pushed
onto the method-call stack
• It also contains the memory for the local variables (including the method
parameters) used in each invocation of a method
• This data, stored as a portion of the method-call stack, is known as the stack frame
(or activation record) of the method call
4.Method Calls
Method-Call Stack
• If a series of method calls occurs, the successive return addresses are pushed
onto the stack in last-in, first-out order
4.Method Calls
Method-Call Stack
• When a method returns to its caller, the stack frame for the method call is
popped off the stack and those local variables are no longer known to the
program.
5.Scope of Declarations
• Declarations introduce names that can be used to refer to classes,
methods, variables and parameters
• The scope of a declaration is the portion of the program that can refer to the
declared entity by its name
• Any block may contain variable declarations.
• Basic scope rules:
• The scope of a local-variable declaration that appears in the initialization section of a
for statement’s header is the body of the for statement and the other expressions in
the header.
• The scope of a local-variable declaration is from the point at which the declaration
appears to the end of that block.

for (int n=1; n<5; n++)


System.out.prinltn(n);
5.Scope of Declarations
Rules
• The scope of a parameter declaration is the body of the method in
which the declaration appears.
• A method or field’s scope is the entire body of the class.

parameter
public static void method(int n) {
int n =0;
int x = 5;
} Local variable

variable n is already defined in method method(int)


int n =0;
L05Code02.java
5.Scope of Declarations
Rules

• If a local variable or parameter in a method has the same name as a field


of the class, the field is hidden until the block terminates execution. It is
called shadowing
• Fields: accessible to all methods from the class itself.
• The static field (whose value is 1) is shadowed in main.

field
public class L05Code02 {
public static int x = 1; //a field
public static void main(String[] args) {
int x = 5; //method's local variable x shadows field x
System.out.printf("local x=%d%n", x);
method();
} Local variable

public static void method() {


System.out.printf("field x=%d%n", x);
}
} local x=5
field field x=1
6.Method Overloading
• Methods of the same name can be declared in the same class, as long as
they have different sets of parameters
• It is called method overloading
• The compiler selects the appropriate method to call by examining the number, types
and order of the arguments in the call
• Used to create several methods that perform the same or similar tasks on
different types or different numbers of arguments
• Math methods abs, min and max are overloaded with four versions each:
• two double parameters, two float parameters, two int parameters, two long
parameters

System.out.println(Math.max(10, 12));
System.out.println(Math.max(10.5, 12.5));

12
12.5
6.Method Overloading L05Code02.java

Rules
• Compiler distinguishes overloaded methods by their signatures
• A combination of the method’s name and the number, types and order of its
parameters, but not its return type.
• The return type of the method is NOT part of the signature
• The compiler must be able to determine which version of the method is being
invoked by analysing the parameters

public static void aMethod() { Zero-parameter


System.out.println("called aMethod()");
}

public static void aMethod(int x, String y, boolean z) {


System.out.println("called aMethod(int x, String y, boolean z)");
}
3-parameters (int, String, boolean)

public static void aMethod(String y, int x, boolean z) {


System.out.println("called aMethod()");
}
3-parameters (String, int, boolean)
6.Method Overloading
Rules
• Method calls cannot be distinguished by return type
• Note: Overloaded methods can have different return types if the
methods have different parameter lists
• Methods have different return types but with the same signature
• :- result in compiler error

public static void aMethod(int x, String y, boolean z) {


System.out.println("called aMethod(int x, String y, boolean z)");
}

public static int aMethod(int x, String y, boolean z) {


...
3-parameters (int, String, boolean)

error: aMethod(int,String,boolean) is already defined in…


6.Method Overloading
L05Code02.java

Argument Promotion
• Argument promotion—converting an argument’s value, if possible, to the
type that the method expects to receive in its corresponding parameter
• promotion rules: int -> double, float -> double etc

sum(20, 20);
public static void sum(int a, double b){
System.out.println(a+b);
System.out.println("Two args");
}
public static void sum(int a,int b,int c){
System.out.println(a+b+c);
System.out.println("Three args"); 40.0
} Two args
• Note:
• Literal integer values are treated as type int
• Literal floating-point values are treated as type double
Exercise 2 - Overloading

• Valid or invalid?
• Case 1: int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)

int mymethod(int a, int b)


• Case 2: int mymethod(float var1, float var2)

int mymethod(int a, int b)


• Case 3: int mymethod(int num)

float mymethod(int a, float b)


• Case 4: float mymethod(float var1, int var2)

7.Random Numbers
• The element of chance can be introduced in a program via an object of
class SecureRandom
• From package java.security
• Such objects can produce random boolean, byte, float, double, int, long and Gaussian
values.
• SecureRandom objects produce nondeterministic random numbers that cannot be
predicted.
• The nextInt() that receives an int argument and returns a value from 0 up
to, but not including, the argument’s value.
• Note: To generate a series of random numbers as a unit, you need to use a
single Random object - do not create a new Random object for each new
random number.
SecureRandom randomNumbers = new SecureRandom();
for (int counter=0; counter<=20; counter++)
System.out.printf("%d ", randomNumbers.nextInt(6)); 0 <= random number <=5

2 4 3 5 1 2 0 0 3 0 3 5 0 2 5 1 2 1 2 0 3
L05Code03.java
7.Random Numbers
Scaling and Shifting
• Generalized scaling and shifting of random numbers:
SecureRandom randomNumbers = new SecureRandom();
number = shiftingValue + randomNumbers.nextInt(scalingFactor);

• where shiftingValue specifies the first number in the desired range of consecutive
integers and scalingFactor specifies how many numbers are in the range
• Example: Simulating dice
• Valid values: 1, 2, 3, 4, 5, 6

randomNumbers.nextInt(6)

0 1 2 3 4 5
1 + randomNumbers.nextInt(6)

1 2 3 4 5 6
Exercise 3
• Complete the code to allow a user to guess a number (from 0 to 10) that will
be randomly generated by computer.

Scanner input = new Scanner(System.in);


int guessNum, randNum;
SecureRandom randomNumbers = new SecureRandom();

__________________

System.out.print("Enter your guess number (0-10):");


Enter your guess number (0-10):5
_____________________ You lost. My number is 9

if (guessNum == randNum) Enter your guess number (0-10):5


System.out.printf("You won."); You lost. My number is
else {
System.out.printf("You lost. My number is %d%n.", randNum);
}

You might also like