Adding two numbers in java

How to Add Two Numbers in Java

In This Tutorial, We will be going to Learn about How To Add Two Numbers in Java.

Initially, in Java with The Different ways available to us. Also, we will learn Taking Inputs in java or to initialize values in an array.

Читайте также:  Products Demo Page

Adding two Numbers In java Can be done in different ways. The Addition is one of the Very Basic Arithmetic operations in various fields of our day to day life.

If you don’t know how to add two Nos. in java, then you are in the right place.

Because, in this tutorial, we will be going to deal with The Various Process through which addition can be done.

Different Situations That May Come During Addition of two numbers

There are Three Basic situations that may arise during the addition. These are:

  1. Adding of two Numbers Which are Given to User Before Only.
  2. Addition of two Numbers with the Inputs Provided by User with Use of ‘Scanner’ class.
  3. Addition of two Numbers With Inputs Provided by User with the Help of ‘BufferedReader’ method.

1: Addition of two Numbers Which are Given to User Before Only :

In this situation, we are Already Been Provided With Initial Numbers, we just have to gonna Add Both and display the Result. Here, We simply take Inputs As initial Values In Different Variables.

In this Situation, we maybe Provided with Any Integer Values, So we add Them and display it.

2: Add two numbers in java with the Use of ‘Scanner’ class :

In this method, we Will Be taking input of two numbers from the User With The Help of ‘Scanner’ class.

Then We will be Adding Them and Display The Corresponding Result that is the addition of two variables.

Initially, we need to Learn what ‘Scanner’ class Actually is.

The Scanner is a class Present in ‘java.util’ , a package which is used for obtaining the input, or taking Input of the primitive types like integer, float, double, etc. and strings also many other datatypes.

In our example, we will use the ‘nextInt’ method, which is used to read The Integer Numbers.

Similarly, different methods can be used to Take Different type of Values that is for Strings or Double. For Example, ‘nextFloat’, which is used for taking input of Float values.

Syntax For creating an object for above is:

Below Is An example of this Type method :

import java.util.*; class Add2 < public static void main(String Args[]) < int n1,n2,sum=0; Scanner sc = new Scanner (System.in); System.out.println("Enter First Number: "); n1 = sc.nextInt(); System.out.println("Enter Second Number: "); n2 = sc.nextInt(); sum=(n1+n2); System.out.println("Sum of Provided Numbers is :"+sum); >>

When The Above Code gets to execute, the User will be asked to get the input of Two Numbers. Then, the user will provide inputs and the corresponding output would come.

3: Add two Numbers in Java With the Help of ‘BufferedReader’ method:

Initially, we need to know What Basically is ‘BufferedReader’ class.

In Java, ‘BufferedReader’ class is used to read the text, buffering characters so as to provide a systematic reading of arrays and lines.

BufferedReader is much more Synchronized than The ‘Scanner’. Also, it has a larger Default Value of Buffer. In this, it can be used to read the data line by line by the ‘readLine()’ method.

Basically, It inherits Reader Class.

Syntax for Above is : BufferedReader object = new BufferedReader (new InputStreamReader(System.in));

When the above code Executed, It will ask for two nos. from the user and correspondingly adds two numbers and displays it.

Источник

Add Two Numbers in Java

Java Course - Mastering the Fundamentals

Adding or finding the sum of two numbers in Java is one of the fundamental aspect in Java. The given two numbers will be added and the sum will be displayed. The size of the data type must be kept in mind while adding the two numbers. If the size of the answer exceeds the size of the data type, overflow occurs.

Introduction

In our kindergarten, after learning alphabets, we learnt about the various mathematical operations like addition, substraction, multiplication and division. As novice programmers, when we enter the programming world, it is expected that we begin with the basic concepts to get a hang of that language.

Addition uses the «+» operator for adding two numbers.

operator for adding two numbers

Let us look at the ways in which we can add two numbers.

Method 1: Sum of two numbers

This is the most easiest way to find the sum of two numbers in Java. We will initialise and declare the value in the program itself. Here the input is not taken from the user.

Explanation In the above program we have declared two variables and initialised their values in the program. The sum of the numbers is stored and displayed on the console.

Method 2: Add Two Numbers in Java With User Input

In Java, the Scanner class is one of the classes which fetches the user input.

Explanation We have initialised the scanner class so that we can take in the user’s input. The line scn.nextInt() reads the user input in the form of integer and it gets saved in that variable. The sum gets stored and is displayed on the screen.

Method 3: Sum of Two Numbers Using Command Line Arguments in Java

Command line arguments are basically the arguments that are passed on the console during the program execution. It is the information that we pass after typing the name of the program during the execution and it is stored as strings in a string array. It is stored in String[] args. The arguments are in string and then we have to convert it into integer.

Steps to be executed

  • While compiling the above program in your IDE, type «javac Main.java» as the class here is Main. To execute the program, type «java Main 99 83». Here 99 and 83 get stored in the String[] args array .
  • The first number at 0th index is stored in a variable and the same is done for the second number.

Method 4: Sum of Two Numbers in Java Using Method

a) By using User-defined method

In this method we are creating a function where the addition of two numbers will be calculated and the value will be returned.

Explanation We have created a function sumFunction which is a user-defined function which takes in two numbers as parameters. The sum of these numbers is returned and displayed.

b) By Using the Sum() Method

The sum() method is used to add numbers given in the arguments of the method. The sum() method is in the Integer class of Java which is in the util package.

Return type

We will use the Integer.sum() function.

Explanation In the above program we have declared two variables and initialised their values in the program. The sum of the numbers is calculated by the sum() method in Java which takes in numbers as arguments.

Method 5: Sum of 3 Numbers in Java

The sum of 3 numbers is similar to the sum of 2 numbers, the only difference is that here we have got three variables.

Explanation We have calculated the sum of 3 numbers.

Method 6: Sum of N Numbers in Java

This is a more generalised way of calculating the sum of a given numbers. When the number of iterations is unknown, we use loops to perform the operations in our program.

  • Read or initialize the value of N which is the number of integers to be added.
  • The loop will run N times and ask the user to enter the numbers or else it depends on how the loop is initialised.
  • Calculate the sum for each input and store it into a variable.
  • When all the iterations are done, print the value of sum.

Sum of N Numbers in Java

The flowchart below demonstrates the logic for the program of finding the sum of N numbers.

Explanation In the example, we have calculated the sum of N numbers with N taken as an input from the user. The loop runs N times and each time user enters a number to be added. The value of that entered number gets added in the sum variable and after the iterations are completed, it is displayed.

Integer Overflow

If our sum exceeds the maximum value for an integer in Java which is Integer.MAX_VALUE = 2147483647 , it will cause integer overflow. If the sum is greater than Integer.MAX_VALUE which is the maximum value an integer can hold, then at the point when it exceeds that value, it gets converted to Integer.MIN_VALUE and the rest of the number is added. It goes to -2147483648 and then continues from there.

To avoid the integer overflow, use data type like long which can hold longer values.

Consider the example where we have stored the value 2147483647 which is the maximum value an integer can hold and then performed addition.

Explanation

  • In the first sum, after adding 0 to it the value remains the same(2147483647) and hence it gets printed as it is.
  • In the second sum, after adding 1, it exceeds the maximum value of an integer, hence it gets converted to Integer.MIN_VALUE and continues from there.
  • In the third sum, after adding 2, it exceeds the maximum value of an integer when 1 gets added, hence it gets converted to Integer.MIN_VALUE and continues from there. The remaining number is then added to the value.

Conclusion

  • Sum deals with the addition of given numbers.
  • In Java we can find the sum of two numbers by various ways like- user input , command line arguments , user-defined and built-in method and by loops .

Источник

Java Program to Add Two Numbers

You will learn how to create a Java program that adds two integers in this tutorial. This is a very simple Java program that asks the user to enter two integers, saves those inputs in two different variables, and then shows the total of the two values.

To determine the sum of two integer numbers provided by the user, we shall create two variables. The user is prompted to enter two integer values in the first variable, after which the variable shows the total of the two integers. Using a user-defined function, we are carrying out the identical action in the second C program.

What is Addition of Two Numbers in Java?

In the Java programming language, adding two integers entails taking two integer numbers, adding them, and then printing the result. Let’s look at the Java programming language’s technique for adding two numbers, which is a straightforward process.

Algorithm for Addition of Two Numbers in Java

  1. Declare two variables.
  2. Initialize the variables with some values.
  3. Declare another variable to store the sum of the numbers.
  4. Apply the mathematical plus(+) operator between two values and store the result.

Method 1: Standard Program for the Addition of Two Numbers in Java

The sum of two numbers is: 50

This method of computing the sum of two numbers in Java is simple. Let’s look for the sum of two numbers in Java using methods.

There are two ways to find the addition of two numbers in java using the method

Method 2: Sum of Two Numbers in Java by using the User-defined Method

Java allows the reading of user input. The user-defined method sum() can accept two numbers from the user as input.
The Java program’s implementation to add two numbers is shown below.

import java.util.Scanner; class SumOfNumbers2 < public static void main(String args[]) < int x, y, sum; Scanner sc = new Scanner(System.in); x = sc.nextInt(); y = sc.nextInt(); sum = sum(x, y); System.out.println("The sum of numbers " + x + " and " + y + " is: " +sum ); >public static int sum(int a, int b) < int sum = a + b; return sum; >>
The sum of numbers 10 and 20 is: 30

Method 3: Addition of Two Numbers in Java by using Integer.sum() Method

The sum() method is available from the integer class. A static method called sum() adds two numbers according to the operator.

public static int sum(int a, int b);
The sum of x and y is: 30 The sum of x and y is: 10

Method 4: Addition of Two Numbers in Java by using Command Line Arguments

Another method to taking input from user is command line arguments. We will discuss the java program to add two numbers where both the numbers are provided by the user using arguments from the command line.

The sum of x and y is: 100

Explanation:
Compile the above program using the command javac SumofNumbers.java. After that, run the program by using command java SumofNumbers 50 50.
Where 50 and 50 are command line arguments.

Conclusion:
We had discussed four different approaches for the Java program to add two numbers. Along with that we have also learned how to take input from users. Addition of two numbers in Java is a simple program, but there are many different approaches for the addition of two numbers in Java. You have to figure out more approaches for the addition of two numbers in Java.

FAQ For Java Program To Add Two Numbers

Q1. What is sum += in Java?
Ans. Java uses the compound addition assignment operator, which looks like: += (plus sign, followed by equal sign). sum += 10 ; // Add 10 to sum.

Q2. What is a keyword in Java?
Ans. A Java keyword is one of 50 reserved terms that have a special function and a set definition in the Java programming language. The fact that the terms are reserved means that they cannot be used as identifiers for any other program elements, including classes, subclasses, variables, methods and objects.

Q3. What is the method in Java?
Ans. A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if you have written instructions to draw a circle in the method, it will do that task. You can insert values or parameters into methods, and they will only be executed when called.

Q4. What is a class in Java?
Ans. A class in Java is a logical template to create objects that share common properties and methods. Hence, all objects in a given class will have the same methods or properties. For example: in the real world, a specific cat is an object of the “cats” class.

Other Java Programs

Источник

Оцените статью