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.
// for sumnumber1 + number2// for average(float)((number1 + number2)/2)
number1
and number2
: These are the numbers whose sum and average we want to get.
The value returned is a sum and the average of the two values.
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);}}