JAVA Basic Programs -- Sum of Two Numbers



Sum of two numbers by receiving value from keyboard








   In this program we use two variables which receive value from the keyboard and add those values and sum of these numbers are stored in the third variable.













In this example we are using Scanner, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double etc. and strings.

It is one of the ways to read input in a Java program.



Syntax for scanner...


Declare the object and initialize with predefined standard input object



Scanner sc = new Scanner(System.in);



String input

     

 String name = sc.nextLine();



Character input



char gender = sc.next().charAt(0);



Numerical data input

byte, short and float can be read

using similar-named functions.

     

 int age = sc.nextInt();

 long mobileNo = sc.nextLong();

 double cgpa = sc.nextDouble();





Xample:



File_name: Addition.java



For Compiling: javac Addition.java



For Execution: java Addition



Remember filename and class name must be the same



import java.util.Scanner;



class Addition

{

public static void main(String[] args)

{

        int a, b, c=0;

Scanner s=new Scanner(System.in);

System.out.println("Enter any two numbers :");

a=s.nextInt();

b=s.nextInt();

c=a+b;

System.out.println("Sum: "+c);

}

}



OutPut:



Enter any two numbers :

10

20

Sum: 30





That's it, I hope it is useful.



Thanks For reading.

Comments

Popular posts from this blog

Android App Version Update using the following cordova cli commands

75 inspirational quotes that will change your life

Retrieval Image From DataBase and Display on WebPage by Using Servlets.