Java functions and How it work inside the memory?
function means block of code to perform particular task. Java Function are similar to other language function.
A function returnType means int, String, float, etc.. and one more return type is void. it means function return null (no return ).returnType functionName(arg1, arg2,...){//function body}
Java has predefined function or method in JVM, that is Main();. return type of Main() method is void.
write the method to print the name
import java.util.*;public class javaFunctions {public static void myName(String name){System.out.println(name);}public static void main(String arg[]){System.out.print("Enter your Name: ");Scanner sc = new Scanner(System.in);String n = sc.next();myName(n);}}
Enter your Name: sk skWhen function or method is create what happened inside the memory?
When function is created it goes to the bottom of stack, it stored variables and functions in it. stack follow LIFO principle, so When another function is created it goes to the stack like show in fig.
if the upper function ( myname() ) is execute and return value to main() function and it automatically popped to the Stack. then main() function are execute, it popped to the stack and return the output.
Create a function to add two no. and return the sum
public class javaFunctions {public static int myName(int a, int b){int sum = a+b;return sum;}public static void main(String arg[]){int a = 2, b = 3;int myAns = myName(a, b);System.out.println(myAns);}}
5
Post a Comment