Computer Science 15-110, Spring 2010
Class Notes: Writing Static Methods
Writing Static Methods
class MyCode {
public static int minSquared(int x, int y) {
int min = Math.min(x, y);
return (min * min);
}
public static void main(String[] args) {
System.out.println(minSquared(3, 4));
System.out.println(minSquared(4, 3));
}
}
Another example:
class MyCode {
// This method computes the area in the first quadrant under
// the line y=mx+b. It assumes m is negative and b is positive,
// so we in fact have a triangle in the first quadrant.
public static int areaUnderLine(int m, int b) {
// The x-intercept of y=mx+b is where y=0, so
// mx+b=0, so x=-b/m
int width =
-b/m;
// b is the y-intercept
int height =
b;
// now we have the width and height of the right triangle
// under the line in the first quadrant, so...
return width*height/2;
}
public static void main(String[] args) {
System.out.println("Area under y=-2x+8 is: " + areaUnderLine(-2,8));
}
}
Yet another example:
class MyCode {
public static
boolean isEvenPositive(int x) {
boolean
isEven = ((x % 2) == 0);
boolean isPositive
= (x > 0);
return (isEven && isPositive);
}
public static void main(String[] args) {
System.out.println(isEvenPositive(-2));
System.out.println(isEvenPositive(-1));
System.out.println(isEvenPositive(0));
System.out.println(isEvenPositive(1));
System.out.println(isEvenPositive(2));
}
}
And yet another example:
class MyCode {
public static String
initials(String firstName, String lastName) {
char firstInitial
= firstName.charAt(0);
char lastInitial
= lastName.charAt(0);
return "" + firstInitial + lastInitial;
}
public static void main(String[] args) {
System.out.println(initials("Donald","Knuth"));
}
}
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem