Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Created October 6, 2014 22:15
Show Gist options
  • Save rshepherd/bee48a417932ccf5cf9e to your computer and use it in GitHub Desktop.
Save rshepherd/bee48a417932ccf5cf9e to your computer and use it in GitHub Desktop.
Methods
import java.util.Arrays;
public class Methods {
public static void main(String[] args) {
// Methods are just functions that belong to a particular class
// Methods are sub-routines. Reusable code.
// Method have parameters, are called with arguments
int y = calc(1, 1);
print("y="+y);
// Methods can be 'over-loaded'
double x = calc(1.0, 2.0);
print("x="+x);
// Methods can be code abbreviations
String grade = getGrade(76);
print(grade);
// Methods calls are pass-by-value!!
// http://javadude.com/articles/passbyvalue.htm
int g = 90;
passByValueDammit(g);
System.out.println(g);
// Methods are values! Java 8 only
Arrays.asList("peter", "anna", "mike", "xenia").forEach(System.out::println);
}
// x and y are 'formal parameters'
public static int calc(int x, int y) {
return (x + y) * 20 % 3;
}
// overload! note that return type is not enough!
public static double calc(double x, double y) {
return (x + y) * 20.0 % 3.0;
}
public static void passByValueDammit(int x) {
x = x * 2;
}
// returning 'void' means side-effect!
// void is the lack of a type. Different than null!
public static void print(String printMe) {
System.out.println(printMe);
}
public static String getGrade(int testScore){
String grade;
if (testScore >= 90 && testScore <= 100) {
grade = "A";
} else if (testScore >= 80) {
grade = "B";
} else if (testScore >= 70) {
grade = "C";
} else if (testScore >= 60) {
grade = "D";
} else {
grade = "F";
}
return grade;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment