0% found this document useful (0 votes)
4 views2 pages

Objects Recr

The document discusses methods in Java that can return objects, specifically demonstrating a method that returns an array containing the sum and difference of two integers. It also explains recursion through examples, including calculating the factorial of a number and summing integers using recursive calls. The provided code snippets illustrate these concepts in action.

Uploaded by

nagabhushansv2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Objects Recr

The document discusses methods in Java that can return objects, specifically demonstrating a method that returns an array containing the sum and difference of two integers. It also explains recursion through examples, including calculating the factorial of a number and summing integers using recursive calls. The provided code snippets illustrate these concepts in action.

Uploaded by

nagabhushansv2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Returing objects

Methods in Java can return objects, allowing for flexible and reusable code
public class Test {
// Returns an array such that first element
// of array is a+b, and second element is a-b
static int[] getSumAndSub(int a, int b)
{
int[] ans = new int[2];
ans[0] = a + b;
ans[1] = a - b;

// returning array of elements


return ans;
}

// Driver method
public static void main(String[] args)
{
int[] ans = getSumAndSub(100, 50);
System.out.println("Sum = " + ans[0]);
System.out.println("Sub = " + ans[1]);
}
}
--------------------
Recursion.
It is the process of defining something in terms of itself.

public class FactorialExample{


public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}

using recursion

public class Main{


int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1)*n;
return result;
}

public static void main(String p[])


{
Main f = new Main();
System.out.println("factorial of number is:"+f.fact(5));
}
}
------------------
To add numbers example

public class Main {


public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}

o/p
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

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

You might also like