Java Programming | Introduction to Functions

Introduction

This is a tutorial for Introduction to functions in java. The program has a static function that is called to add two numbers given in the parameters. The program is extendable. Go enjoy the program. Lets begin……….

Program for sum of two numbers using function in java.

//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class Function {
	//void main
		public static void main (String[] args)
		{
			//declare int
			int x,y,z;
			//print message
			System.out.println("Enter Two numbers:");
			//Take input
			Scanner input = new Scanner(System.in);
			 x = input.nextInt();
		     y = input.nextInt();

		   //call function
		     z=sum(x,y);

			//print the sum
			System.out.println("Sum = "+z);
		}

		//declare a static function
		public static int sum(int a, int b)
		{
			int sum = a+b;
			return sum;
		}
}

Output

Enter Two numbers:
1
2
Sum = 3

How does it work

  1. You enter the number.
  2. The function calculates sum.
  3. The sum is printed.

Extending it

The program is extendable as it is a basic program and can be implement in any java program. Go enjoy the functions beyond the limit.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Declare input as Scanner.
  5. Add system.out.println() function with the message to enter number.
  6. Take the inputs and save it in variables.
  7. Call the function.
  8. Add system.out.print() function to print sum.
  9. Add the function out of void main function.

At the end.

You learnt creating the Java program for Introduction to functions. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s