Adding two numbers in Java

Adding two numbers in Java

If you have started learning Java and want to start programming real-world problems, the basic program is adding two numbers in java.

For people who are just starting with Java. One of the most basic requirements is one’s ability to use Arithmetic Operators. There are multiple ways to reach the required target.

Basically, in this section, we are focusing on how to use operators. Operators perform an operation on data called Operands

Static Method – Adding Two numbers in Java

In this method we will add data in a static manner, i.e. giving hardbound values while coding which cannot be changed by the user who has no knowledge of how stuff works.

 

[java]
public class ShoutCoders{

public static void main(String[] args) {

int a=7; //First number
int b=15; //Second number

int c; //Variable to store result
c=a+b; // Addition Operation

System.out.println(“The Sum of “+a+” & “+b+” is :”+c);

}
}

[/java]

Exercise – Create the same program of adding two numbers in java using other data types such as float, double.

Dynamic Method – Adding two numbers in Java

In this method we will add data dynamically, i.e. user can enter values according to its will and can run the routine with different value sets. For such functionality, we have to import a Java class called Scanner. Then we make an object of scanner class and access its functions to fetch the user entered data.

[java]
import java.io.*;
import java.util.Scanner;

public class ShoutCoders{

public static void main(String[] args) {

Scanner obj=new Scanner(System.in);
System.out.println(“Enter First Number :”);
int a=obj.nextInt(); //Getting first number via scanner
System.out.println(“Enter Second Number :”);
int b=obj.nextInt(); //Getting second number via scanner

int c; //Variable to store results
c=a+b;

System.out.println(“The Sum of and b :”+c); // printing results

}
}

[/java]

Exercise – Create the same program but rather than adding the two numbers subtract the two numbers.

Recommend Posts

  1. Introduction of Java For Beginners.
  2. Structure of Java Program.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami