public class JavaExample {
public static void main(String[] args) {
// two integer variables with values
// and a variable "sum" to store the result
int num1 = 5, num2 = 15,sum;
//calculating the sum of num1 and num2 and
//storing the result in the variable sum
sum = num1+num2;
//printing the result
System.out.println("Sum of "+num1+" and "+num2+" is: "+sum);
}
}
Sum of 5 and 15 is: 20
num1
and num2
. The program then calculates the sum of input numbers and displays it.import java.util.Scanner;
public class AddTwoNumbers2 {
public static void main(String[] args) {
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
In this program, the statement Scanner sc = new Scanner(System.in);
creates an instance of Scanner class. This instance calls nextInt()
method to read the number entered by user. The read values are stored in variables num1
and num2
. Once the values are stored in variables. The addition is performed on these variables and result is displayed.
Enter First Number:
7
Enter Second Number: 14
Sum of these numbers: 21
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
double num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Number: ");
num1 = sc.nextDouble();
System.out.print("Enter Second Number: ");
num2 = sc.nextDouble();
sc.close();
sum = num1 + num2;
System.out.println("Sum of "+num1+" and "+num2+" is: "+sum);
}
}​
Enter First Number: 14
Enter Second Number: 20
Sum of 14.0 and 20.0 is: 34.0