How to get the sum and average of two numbers in Java
Overview
We can get the average and sum of two numbers in Java by performing a mathematical operation and printing out the result. For the sum, we just need to add the two numbers. For the average, we need to add the two numbers and divide them by 2. Then, we typecast the value returned to a float. Typecasting here means converting the value returned to another value.
Syntax
// for sumnumber1 + number2// for average(float)((number1 + number2)/2)
The syntax to get the sum and average of two numbers in Java
Parameters
number1 and number2: These are the numbers whose sum and average we want to get.
Return value
The value returned is a sum and the average of the two values.
Example
class HelloWorld {public static void main( String args[] ) {// create some numbersint no1 = 23;int no2 = 1;int no3 = 6;int no4 = 100;// get sumint sum1 = no1 + no2;int sum2 = no3 + no4;// get the averagefloat avg1 = (float)((no1 + no2) / 2);float avg2 = (float)((no1 + no2) / 2);// print results to the console.System.out.println(sum1);System.out.println(sum2);System.out.println(avg1);System.out.println(avg2);}}
Explanation
- Lines 4-7: We create some integer values. These represent our numbers.
- Lines 10 and 11: We calculate their sum.
- Lines 14 and 15: We calculate their average as well.
- Lines 18-21: We print the results to the console.