Java program to add two numbers - Example code how to

How to add two numbers in Java
In this Java program tutorial, we will add two numbers provided from the user on the command line. Write a Java program to add two numbers in Java is a common programming exercise for programmers and mostly asked in college exams , school homework, and Java courses as well. There are a different variant as well where you need to ask that write a method to add two numbers e.g. sum(int a, int b) and may ask you to get numbers as input from the user. Taking user input is a little bit tricky for Java programmers but once you know how to do that, it's rather simple.

Java program to add numbers in Java - Code Example

How to add two numbers in Java - program example code tutorial
Here is complete Java program to add two numbers in Java. This Java program accepts numbers as user input from the command line using java.util.Scanner class. We have also written an add() method for adding two numbers in Java,  By the way If you know about the variable argument in Java and varargs method, you can even write a method which can accept a variable number of arguments e.g. two, three or four.

package test;

import java.util.Scanner;

 * Java program to add two numbers in Java. numbers should be entered by user
 * in command prompt.
 * @author

public class CollectionTest {

    public static void main(String args[]) {
        //create Scanner instance to get input from User
        Scanner scanner = new Scanner(;
        System.err.println("Please enter first number to add : ");
        int number = scanner.nextInt();
        System.out.println("Enter second number to add :");
        int num = scanner.nextInt();
        //adding two numbers in Java by calling method
       int result = add(number, num);
       System.out.printf(" Addition of numbers %d and %d is %d %n", number, num, result);
    public static int add(int number, int num){
        return number + num;
   Please enter the first number to add :
Enter the second number to add :
 Addition of numbers 45 and 65 is 110

 Other Java programming exercise :

No comments:

Post a Comment