Popcorn Hack 1
public class PopcornMax {
// TODO: write int version of max
public static int max(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
// TODO: write double version of max
public static double max(double x, double y) {
if (x > y) {
return x;
} else {
return y;
}
}
public static void main(String[] args) {
System.out.println(max(3, 9)); // expected: 9
System.out.println(max(-2, -7)); // expected: -2
System.out.println(max(3.5, 2.9)); // expected: 3.5
System.out.println(max(2, 2.0)); // should call double version → 2.0
}
}
PopcornMax.main(null);
Popcorn Hack 2
public class PopcornPrint {
// TODO: write print(int n)
public static void print(int n) {
System.out.printf("int:%d\n", n);
}
// TODO: write print(String s)
public static void print(String s) {
System.out.printf("str:%s\n", s);
}
public static void main(String[] args) {
print(42); // expected: int:42
print("hello"); // expected: str:hello
print('A' + "!"); // char + String → String → expected: str:A!
}
}
PopcornPrint.main(null);
Short Answers
int sum(int a, int b) and double sum(int a, int b) cannot both exist as they have the same method signature of sum(int, int).
- The difference between a parameter and argument is that a parameter are placeholders for functions of variables it can accept, while arguments are real values passed into functions.
Coding Tasks
public class Main {
public static int abs(int x) {
return (x < 0) ? x *= -1 : x;
}
public static double abs(double x) {
return (x < 0) ? x *= -1 : x;
}
public static long abs(long x) {
return (x < 0) ? x *= -1 : x;
}
public static String concat(String a, String b) {
return (a + b);
}
public static String concat(String a, int n) {
return a.repeat(n);
}
static void show(int x) {
System.out.println("int");
}
static void show(double x) {
System.out.println("double");
}
static void show(long x) {
System.out.println("long");
}
public static void main(String[] args) {
show(7);
show(7L);
show(7.0);
System.out.println(abs(-7.5));
System.out.println(concat("Hello", 5));
}
}
Main.main(null);
int
long
double
7.5
HelloHelloHelloHelloHello