Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science A 7: 27/2. Methods - subroutines Chapter 4 static return-type name ( parameters ) { statements } Call a method name ();

Similar presentations


Presentation on theme: "Computer Science A 7: 27/2. Methods - subroutines Chapter 4 static return-type name ( parameters ) { statements } Call a method name ();"— Presentation transcript:

1 Computer Science A 7: 27/2

2 Methods - subroutines Chapter 4 static return-type name ( parameters ) { statements } Call a method name ();

3 Methods Return type: void or some type If void call method as a statement If not void call it in expressions If not void the method should return a value Methods can declare local variables – can have same name as variales in other methods – they disappear when you leave Methods can have parameters

4 Examples static void printBlanks(int n){ for(int i=0;i<n;i++) System.out.print(” ”); } … for(int i=n/2;i>=0;i++){ printBlanks(i); System.out.print(”x”); printBlanks(n-2*i); System.out.println(”x”); }

5 Examples static String spaces(int n){ String s=””; for(int i=0;i<n;i++)s+=” ”; return s; } … for(int i=n/2;i>=0;i++){ System.out.println(spaces(i)+ ”x”+spaces(n-2*i)+”x”); }

6 Parameters Methods can have zero one or more parameters They work as local variables that are initialized when the method is called static void zero(int x){x=0;} int n=1; zero(n); // but n is still 1

7 Overloading You can have several methods with the same name if they have different parameter types static void check(int n){ System.out.println(”an integer”);} static void check(double d){ System.out.println(”a real number”);} static void check(String s){ System.out.println(”a string”);}

8 Static variables A class can have variables that can be used in all methods public class A{ static int count=0; static void main(..){..} static void method(){ count++;} } Do not such variables to return values from methods

9 Method calls Methods can call other methods – they can even call themselves static int fib(int n){ if(n<=2) return 1; else return fib(n-1)+fib(n-2); }

10 Exercises Write a capitalize function – that change the first letter in each word into uppercase Write a random function random(int n,int m) that generates a random integer between n and m (inclusive).


Download ppt "Computer Science A 7: 27/2. Methods - subroutines Chapter 4 static return-type name ( parameters ) { statements } Call a method name ();"

Similar presentations


Ads by Google