Wednesday, December 24, 2008

How to do I sum and print two numbers in Java Program

Here is the sample program , which will print two number sum in different ways:

public class  SumNumbers
{
  /*
    Create a java file as SumNumbers.java
    Save this code in it.
  */
  public static void main(String[] args) 
  {
    /* defining two variables.
      1. int x
      2. int y
      Variable x and y are prefixed by keyword called int.
      'int' means integer datatype can contain any integer non decimal value.
    */
    int x = 10;
    int y = 20;
    // Different ways we can print the sum value as mentioned below.
    int sum = x+ y;
    System.out.println(" Sum of two numbers : Style 1 : "+sum);
    System.out.println(" Sum of two numbers : Style 2 : "+(x+y));
    System.out.println(" Sum of two numbers "+x+" and "+y+" is : Style 3 : "+(x+y)); 
  }
}
Output will be:
-----------------------
Sum of two numbers : Style 1 : 30
Sum of two numbers : Style 2 : 30
Sum of two numbers 10 and 20 is : Style 3 : 30