Product and Division of two numbers – Computer Sir Ki Class

Code Learning #JAVA#571

## Product and Division of two numbers

Product and Division to show data type compatibility difference.

## Learning Objectives

To learn java concepts related to :

• Initializing variables dynamically.
• Compatibility of data types.

## Program Approach

The objective is to demonstrate the dynamic initialization and declaration of variables along with the compatibility of the data types with certain type of numerical values.

We will be first declaring two variables with their initial values. Then we will be initializing a third variable with the product and the fourth variable with division of the stored values. The fourth variable will be of double data type as we do not know whether the outcome of the division would be an integer or real number.

## Source Code

 class ProductDivision { public static void main (String[] args) { int num1=20; int num2=5; int num3=num1*num2; System.out.println("The product is : "+num3); double num4=num1/num2; //This should be commented when variation below is tried. //double num4=num1*1.0/num2; //this variation should be tried when //expected output is not an whole number System.out.println("The division is : "+num4); } } .linedwrap { border: 1px solid #c0c0c0; padding-top: 5px; padding-bottom: 5px; border-radius: 4px; background-color:#F8F8F8; } .linedtextarea { padding: 0px; margin: 0px; background-color:#F8F8F8; } .linedtextarea textarea, .linedwrap .codelines .lineno { font-size: 12pt; font-family: monospace; line-height: normal !important; } .linedtextarea textarea { padding-right:0.3em; padding-top:0.3em; border: 0; } .linedwrap .lines { margin-top: 0px; width: 20px; float: left; overflow: hidden; border-right: 1px solid #c0c0c0; margin-right: 10px; } .linedwrap .codelines { padding-top: 5px; } .linedwrap .codelines .lineno { color:#AAAAAA; padding-right: 2px; padding-top: 0.0em; text-align: right; white-space: nowrap; } .linedwrap .codelines .lineselect { color: red; }

## Run Output

``````The product is : 100
The division is : 4.0``````

## Code Understanding

int num3=num1*num2;

In this line we have initialized the variable sum with the product of the values stored in the variables num1 and num2.

double num4=num1/num2;

In this line we have initialized the variable num4 with the division of the values stored in the variables num2 and num1. The data type for this variable is double as we are not sure whether the outcome of the division will be an integer or a real number. Also the right side should also be double data type. For this at least the numerator should be double. For this we can write
double num4 = (num1*1.0)/num2; This will make the numerator of right hand side as double and now the calculations would be perfect. To test this you can check with num1 set as 21.

Suggested Filename(s): ProductDivision.java

admin| Created: 16-Aug-2016 | Updated: 21-Mar-2018|

×