Add Two Numbers In Java

The topic of discussion is Java Add Two Numbers with the hope that it can serve as a useful educational resource.



Java Add Two Numbers

Here’s how to add two numbers in Java:

Add Two Numbers Example:1 

public class Main { public static void main(String[] args) { float mrx=42.526f; float ample=67.434f; float result=mrx+ample;System.out.println(mrx+" + "+ample+" = "+result); } }

Similarly, we can also add two numbers having data type as double.

Add Two Numbers Example:2 

public class Main { public static void main(String[] args) { double mrx=34.6347345432412d; double ample=74.1242343424362d; double result=mrx+ample;System.out.println(mrx+" + "+ample+" = "+result); } }

Add Two Numbers with User Input

Two numbers can be added by taking the user input as well.

The following programme shows the addition of two numbers of type byte taken from the user.

Reminder: During the input, do not forget that the range of byte is from -128 to +127.

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Number 1 here: "); byte mrx_number1=input.nextByte();System.out.println("Enter Number 2 here: "); byte ample_number2=input.nextByte();int sum= mrx_number1+ample_number2;System.out.println("The Sum of "+mrx_number1+" + "+ample_number2+" is: "+sum); } }

Correspondingly, two float numbers can be added as shown in the example below:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Number 1 here (Can be a decimal value): "); float mrx_num1=input.nextFloat();System.out.println("Enter Number 2 here (Can be a decimal value): "); float ample_num2=input.nextFloat();float sum= mrx_num1+ample_num2;System.out.println("The Sum of "+mrx_num1+" + "+ample_num2+" is: "+sum); } }

 

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

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