150 likes | 249 Views
Methods. 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. A Java Program. Java classes. Java Methods. … - What is a method …. public class class-name { method1 method 2
E N D
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 A Java Program Java classes Java Methods
… - What is a method … public class class-name { method1 method 2 method 3 … … method n }
Example of a Java Program Class name Main method Class body Instruction
Exercise • Write a program that computes: • factorial (n!) of 6 • factorial of 3, then • factorial of 10.
Method definition using method Method invocation Return type Method parameter Return instruction
Method Structure public or private<static> <void or typeReturned>myMethod(<parameters>) { statement statement statement … … statement } Method name If method doesn’t return value Type of the return value Variable list Method body
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
- 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.
return Statements • A void method need not contain a return statement, Example : write a method that prints all the numbers between 10 and 30
public classTestSum{ public staticvoid 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; } }
- Method Parameters: Array Parameters A parameter of type array
- 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..
- Method Overloading … These 3 methods have the same name but different signatures