SE_21_Lesson_5: Methods

 1. Structure of a method




2. Method signature:

Method signature consists of method name and its parameters.

There can not be two methods with same signature.

-----------------------------------------------------------------------------------------------------------------------------

package org.example;

public class Main {
public static void main(String[] args) {
byte b = 3;
foo(3);
}

public static void foo(short i) {
System.out.println("in short");
}

public static void foo(int i) {
System.out.println("in int");
}

public static void foo(long i) {
System.out.println("in long");
}
}



*** Advantage of using Variable arguments

public static double average(double a, double b) {
return (a + b) / 2;
}

public static double average(double a, double b, double c) {
return (a + b + c) / 3;
}

public static double averageArray(double[] arr) {
double sum = 0;
for(int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}

public static double average(double... arr) {
double sum = 0;
for(int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}


Problem with variable arguments

package org.example;

public class Main {
public static void main(String[] args) {
foo(1, 2, 3);
}

public static void foo(int... args) {
System.out.println(args);
}

public static void foo(int i, int... args) {
System.out.println(i);
System.out.println(args);
}

public static void foo(int i, int j, int... args) {
System.out.println(i);
System.out.println(j);
System.out.println(args);
}
}


***Recursion

1) Simple recursion

public static void foo(int n) {
System.out.println(n);
foo(n);
}

2) Print numbers in descending order

public static void foo(int n) {
if(n == 0) {
System.out.println(n);
return;
}
System.out.println(n);
foo(n - 1);
}

3) Print numbers in ascending order

public static void foo(int n) {
if(n == 0) {
System.out.println(n);
return;
}
foo(n - 1);
System.out.println(n);
}

4) Print digits of number

public static void foo(int n) {
if(n == 0) return;
System.out.println(n % 10);
foo(n / 10);
}
public static void foo(int n) {
if(n == 0) return;
foo(n / 10);
System.out.println(n % 10);
}

5) Finding factorial

public static int foo(int n) {
if (n == 0) return 1;
else {
return n * foo(n - 1);
}
}
public static int foo(int n) {
if (n == 0) return 1;
else {
int prev = foo(n - 1);
int result = n;
result *= prev;
return result;
}
}

6) Fibonacci number

public static int foo(int n) {
if (n == 0 || n == 1) return n;
else {
return foo(n - 1) + foo(n - 2);
}
}












Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class