Reputation: 53
This might be a dumb question but I'm teaching myself from a book and I noticed that a lot of examples have the print statement inside a method other than main. I was wondering if it makes a difference where you put it so I pasted the program I was working on when the question occurred to me. Would it be more efficient for me to have the getArea method print the area or leave it in main?
private static Scanner in;
private static double s;
private static double a;
public static void main(String[] args) {
in = new Scanner(System.in);
DecimalFormat two = new DecimalFormat("#.##");
System.out.println("Enter the length from center to vertex: ");
double r = in.nextDouble();
s = getSide(r);
a = getArea(s);
System.out.println("The area of a pentagon of radius "+r+" is "+two.format(a));
}
public static double getSide(double radius){
double side = 2 * radius * Math.sin((Math.PI) / 5);
return side;
}
public static double getArea(double side){
double area = (5 * Math.pow(side, 2)) / (4 * Math.tan((Math.PI) / 5));
return area;
}
Upvotes: 5
Views: 853
Reputation: 1068
Print operation is a simple logging feature and it has no any performance penalties/benefits. Whenever you write code you can ask next questions to yourself:
Upvotes: 1
Reputation: 171206
There is no difference in efficiency. This can be seen by the fact that a function can't find out what other function called it. It can't possibly behave in a different way. (Except for stack introspection and inlining...)
Architecturally it is better to try to keep methods pure in the sense that they do not cause side-effects if that is not required. That makes the program simpler to understand. A pure function takes some values and returns a value without changing anything else. Printing is a side-effect so try to keep it out of computation-style functions.
Upvotes: 9