Saturday, September 29, 2012

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 user on 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 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 user. Taking user input is 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 accept numbers as user input from 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 variable argument in Java and varargs method, you can even write method which can accept 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.in);
     
        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;
    }
}
Output
   Please enter first number to add :
45
Enter second number to add :
65
 Addition of numbers 45 and 65 is 110

 Other Java programming exercise :

No comments:

Post a Comment

Java67 Headline Animator