Ajay Kumar Ajay Kumar - 3 months ago 9
Java Question

why i didnot get output for below code need explanation?

public class Triangle
{

float length; //declared length as float
float breadth; //declared breadth as float
public static void main(String[] args)
{
Triangle Triangle1 = new Triangle();
Triangle Triangle2 = new Triangle();

float area; //declared area as float

Triangle1.length = 11;
Triangle1.breadth = 22;
Triangle2.breadth = 15;
Triangle2.length = 20;

area = 0.5 * Triangle1.length * Triangle1.breadth;
System.out.println("The area of Triangle is" + " " + area);

area = 0.5 * Triangle2.length * Triangle2.breadth;
System.out.println("The area of Triangle is" + " " + area);

}
}


i have declared the area as float earlier and i got complie time error for that, when i changed it into double, i can able to get the below output.
need to know why...??

float area;

Error:(24, 49) java: incompatible types: possible lossy conversion from double to float
Error:(27, 49) java: incompatible types: possible lossy conversion from double to float

Answer

Your code has several mistakes.

  • Please keep the naming conventions. Class starts with the capitalized letter, variable don't. So.. Triangle triangle1 = new Triangle().

  • In order to keep all the data in float, you need to multiply all the numbers in float as well. 0,5 is double as default, having the bigger decimal precision than float. There are two ways to fix that:

Use F or f indicator (I recommend the capitalized one) to say that you work with float. Otherwise Java unserstands it as double:

area = 0.5F * triangle1.length * triangle1.breadth;

Or cast all the resutl to float:

area = (float) 0.5 * triangle1.length * triangle1.breadth;