Java Functions PDF
Document Details
![StrikingMinotaur2450](https://quizgecko.com/images/avatars/avatar-20.webp)
Uploaded by StrikingMinotaur2450
Tags
Summary
This document provides an introduction to Java functions, explaining predefined, user-defined, parameterized, non-parameterized, and returning functions. It also covers static and instance functions and includes examples of recursive functions, key topics and related concepts.
Full Transcript
Functions in Java In Java, a function (commonly referred to as a method) is a block of code that performs a specific task and can be called multiple times. Types of Functions in Java 1. Predefined (Built-in) Functions o Functions provided by Java libraries, such as Math.pow(), System....
Functions in Java In Java, a function (commonly referred to as a method) is a block of code that performs a specific task and can be called multiple times. Types of Functions in Java 1. Predefined (Built-in) Functions o Functions provided by Java libraries, such as Math.pow(), System.out.println(), etc. 2. User-defined Functions o Functions created by the user to perform specific tasks. 3. Parameterized Functions o Functions that accept parameters and return a result. public int add(int a, int b) { return a + b; } 4. Non-Parameterized Functions o Functions that do not take parameters. public void greet() { System.out.println("Hello, World!"); } 5. Void Functions o Functions that do not return a value. public void displayMessage() { System.out.println("This is a void function."); } 6. Returning Functions o Functions that return a value. public int square(int num) { return num * num; } 7. Static Functions o Functions declared with the static keyword that can be called without creating an instance of the class. public static void show() { System.out.println("Static Method"); } 8. Instance Functions o Functions that require an object of the class to be called. public void instanceMethod() { System.out.println("Instance Method"); } Recursive Function in Java A recursive function is a function that calls itself to solve a problem. Example 1: Factorial Using Recursion public class RecursionExample { public static int factorial(int n) { if (n == 0) { return 1; // Base condition } else { return n * factorial(n - 1); // Recursive call } } public static void main(String[] args) { int num = 5; System.out.println("Factorial of " + num + " is: " + factorial(num)); } } Example 2: Fibonacci Series Using Recursion public class FibonacciRecursion { public static int fibonacci(int n) { if (n