Java Basics Excercise
Problem Statement-1:
Write a Java program to print the area and perimeter of a rectangle
Test Data :
Width = 5.5
Height = 8.5
Expected Output :
Area = 47.60
Perimeter = 28.20
Solution:
public class Exercise1{
public static void main(String[] strings) {
final double width = 5.6;
final double height = 8.5;
double perimeter = 2*(height + width);
double area = width * height;
System.out.println("Perimeter = %.2f \\n", height, width, perimeter);
System.out.println("Area = %.2f \\n", width, height, area);
}}
Output:
Perimeter = 28.20
Area = 47.60
Explanation:
The class `Exercise1` consists of the fields such us `width = 5.6` and `height = 8.5` .Hence the perimeter of rectangle is 2*(height+width) and area of rectangle is width*height is calculated. The values are printed using `println()` function.
Problem Statement-2:
Write a Java program to convert double data type into long type and int type.
Test Data :
d = 166.66
Expected Data:
Before conversion: 166.66After conversion into long type: 166After conversion into int type: 166
Solution:
public class Exercise2 {
public static void main(String args[]) {
double d = 166.66;
//converting double data type into long data type
long l = (long) d;
//converting long data type into int data type
int i = (int) l;
System.out.println("Before conversion: " + d);
//fractional part lost
System.out.println("After conversion into long type: " + l);
//fractional part lost
System.out.println("After conversion into int type: " + i);
}
}
output:
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Explanation:
The class Exercise2 consists of fields such us double d = 166.66. The double type is converted into long type by using long l = (long) d and long type is converted intoint type by using
int i = (int) l. The values are printed using println() function.