Simple java program to add two numbers

java program to add two numbers is a very simple program.

It is required by learners How can we add two numbers.

We will start with simple addition and try to cover additional things here.

Flowchart To Add Two Numbers
Flowchart To Add Two Numbers

Simple java program to add two numbers

Steps to add two numbers

  1. Store two numbers in two variables
  2. Add both variables and store in another variable
  3. Print the result

Here we take a=5 and a=6 two variables

added a and b and stored in variable sum

printed the sum in consol.

Fig: Addition of two numbers in Notepad++
Fig: Compilation and run of Addition program

Addition of two numbers in java

Above we add two integer numbers.

Here lets take two decimal numbers in java we represent decimal number in float and double

Addition of two decimal numbers in java

The process is same only we changed data types.

Addition of two numbers in java

Here we are considering two numbers one is integer and another is double.

Here a is integer data type and b is double data type.

For addition a is automatically promoted to double data type by the compiler the addition is performed.

Whenever two or more variable of different data types take part in any operation then a lower data type is always converted to higher data type.

This automatic conversion is done by compiler and the process in known as widening.

Addition of short numbers in java

Here variable a and b both are short type.

While adding two short numbers it is converted to integer and the result is stored in integer data type.

Both byte and short data types are converted to an integer.

Sum of two numbers in java using method

In the above program sum() is a static method so we called it with Class name.

add1(), add2(), add3() and add4() are non static so we called by object of class.

Methods are with and without argument and with and without return type.

Write the definition of a method add, which receives two integer parameters and returns their sum.

Adding Two Numbers using Integer class sum()

Java program to add two numbers From User Input

1 add two numbers in java using Scanner class input

2 add two numbers in java using BufferedReader Class input

3. add two numbers in java using Console class input

write a program to add two numbers using class and constructor

Addition if Numbers class in java

The abstract class Number is the superclass of platform classes representing numeric values that are convertible to the primitive types bytedoublefloatintlong, and short.

java.lang.Number

To convert Number class to int long float double the methods intValue(), longValue(), floatValue() and doubleValue() are used respectively.

How to add Two BigInteger in Java

To add two BigInteger numbers we use add() method.