Download presentation
1
Methods
2
A Java Program A Java Program
A Java program consists of one or more classes A Java class consists of one or more methods A Java method consists of one or more statements Java classes Java Methods
3
… - What is a method … public class class-name { method1 method 2
method n }
4
Example of a Java Program
Class name Main method Class body Instruction
5
Exercise Write a program that computes: factorial (n!) of 6
factorial of 3, then factorial of 10.
7
using method Method invocation Return type Method parameter
Method definition Method parameter Return instruction
8
Method Structure { statement … } Method name
If method doesn’t return value public or private<static> <void or typeReturned>myMethod(<parameters>) { statement … } Type of the return value Variable list Method body
9
Invoking a Methods The statements inside a method body are executed when the corresponding method is called from another method. Calling a method is also called invoking a method Each time the method is invoked, its corresponding body is executed
10
- return Statements … The body of a method that returns a value must also contain one or more return statements A return statement specifies the value returned and ends the method invocation.
11
return Statements A void method need not contain a return statement, Example : write a method that prints all the numbers between 10 and 30
12
public class TestSum { public static void main)String[] args){ float i =5; float j =2; float k =Sum(i ,j); System.out.println)”The sum =“ + k); } Public static float Sum( float x , float y ) { float z ; z= x + y ; return z; } }
13
- Method Parameters: Array Parameters
A parameter of type array
14
- Method Overloading … In java the same class can have methods with the same name. Such methods are called overloaded methods. Overloaded methods must differ in the number or type of their arguments. The compiler treats overloaded methods as completely different methods..
15
These 3 methods have the same name but different signatures
- Method Overloading … These 3 methods have the same name but different signatures
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.