How to add two numbers in java

In this tutorial we will learn how to add two numbers in java . Addition of two numbers is very simple in java ,First program we add two number if values are specify ,  In second java program we  add two numbers taking input from user with help of Scanner . In third java program to add two numbers using class and object .

Sum of Two numbers in java

We will write java program to add two numbers  and  numbers are specify in this program

public class AddTwoNumber {
	
	public static void main(String[] args) {
		int firstNumber = 10;
		int secondNumber = 20;
		int sum =0;
		//addition of two numbers
		sum = firstNumber + secondNumber;
		System.out.println("sum of two numbers : "+ sum);
		
	}

}

Output :

sum of two numbers : 30

Add two numbers in Java using Scanner

We will write java program to add two numbers using scanner . In this java program for adding two numbers  , we will take input from using scanner and then sum of these two values .

import java.util.Scanner;

public class AddTwoNumberUsingScanner {
	public static void main(String[] args) {
		int firstNumber;
		int secondNumber;
		int sum ;
		
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Number: ");
        firstNumber = sc.nextInt();
        
        System.out.println("Enter Second Number: ");
        secondNumber = sc.nextInt();
        
        sc.close();
        
        //addition of two numbers
      	sum = firstNumber + secondNumber;
      	System.out.println("sum of two numbers : "+ sum);
        
	}

}

Output :

Enter First Number: 
10
Enter Second Number: 
50
sum of two numbers : 60

Java program to add two numbers using class and object

In this program to addition of two numbers in java we will write a add() method . Add() method take two number as argument return sum of two numbers .

class AddTwoNumbersUsingClassAndObject {
	public static void main(String[] args) {
		int firstNumber = 50;
		int secondNumber = 40;
		AddTwoNumbersUsingClassAndObject addTwoNumbersUsingClassAndObject = 
                                      new AddTwoNumbersUsingClassAndObject();
		int sum = addTwoNumbersUsingClassAndObject.add(firstNumber, secondNumber);
      	System.out.println("sum of two numbers : "+ sum);
	}
	
	
	private int add(int num1 , int num2){
		return num1+ num2;
	}

}

Output :

sum of two numbers : 90

We have learned different method to sum of two numbers in java  in this tutorials .  There are nice simple method for addition of two numbers in java .

 

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 25 = 27