Java Program to Add Two Numbers using different methods(methods in different ways)

Simple Java Program to Add Two Numbers

This simple Java program let the user to enter two integer values and then add those two numbers and assign it to variable sum.
JAVA CODE:
//Addition of two numbers by taking input from user.
import java.io.*;
import java.util.*;

public static void main(String args[]){
int num1,num2,sum;
System.out.println(“Enter two numbers “);
Scanner input= new Scanner(System.in);
num1=input.nextInt();
num2=input.nextInt();
sum=num1+num2;
System.out.println(“The sum of the number is “+sum);

}
}

OUT-

Enter two numbers
78
8
The sum of the number is 86

Java Program to Add Two Numbers using Methods

import java.io.*;

import java.util.*;

{

public static void main(String args[])
{
int num1,num2;
System.out.println(“Enter two numbers”);
Scanner input = new Scanner(System.in);
num1=input.nextInt();
num2=input.nextInt();
}
//here we used static keyword so that we dont need to create an object for addition method
{
int sum;
sum=num1+num2;
return sum;
}
}

Java Program to Add Two Numbers using OOPs

(In OOPs we create two classes in first class we define fields or variables and methods and in main class that is in second class we call methods and fields using object)

import java.io.*;
import java.util.*;

{

{             int num3;
num3=num1+num2;
return num3;

}
}
{
public static void main(String args[])
{
int num1,num2,num3;
Scanner input = new Scanner(System.in);

System.out.println(“Enter two numbers”);
num1=input.nextInt();
num2=input.nextInt();

}
}

OUTPUT-
Enter two numbers
2
5
Sum is 7

Java program for addition of two numbers using constructor

//Addition of two numbers using parameterized constructor

import java.io.*;

import java.util.*;
{
{
int sum;
sum=num1+num2;
}
}