RefValEx.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
class TestClass { private int val; public TestClass(int val){ this.val = val; } public int getVal(){ return val; } public void setVal(int v){ val = v; } } public class RefValEx { public static void modifyRef(TestClass c){ c.setVal(42); } public static void modifyVal(int i){ i++; } public static void refVsVal(){ int v = 19; int v2 = v; System.out.println("int v: " + v); v2++; System.out.println("int v: " + v); System.out.println("int v2: " + v2); TestClass tc = new TestClass(19); TestClass tc2 = tc; System.out.println("tc.getVal(): " + tc.getVal()); tc2.setVal(47); System.out.println("tc.getVal(): " + tc.getVal()); System.out.println("tc2.getVal(): " + tc2.getVal()); // Examining reference equality. System.out.println("tc==tc2: " + (tc == tc2)); TestClass tc3 = new TestClass(47); System.out.println("tc==tc3: " + (tc == tc3)); } public static void passByRefVsVal(){ int v = 19; System.out.println("int v: " + v); modifyVal(v); System.out.println("int v: " + v); TestClass tc = new TestClass(19); System.out.println("tc.getVal(): " + tc.getVal()); modifyRef(tc); System.out.println("tc.getVal(): " + tc.getVal()); } public static void main(String[] args){ System.out.println("--- Ref vs. Val ---"); refVsVal(); System.out.println("--- Pass by ref vs. Pass by val ---"); passByRefVsVal(); } } |
EnumTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// An adaptation of code from // https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html public class EnumTest { public enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } private Day day; public EnumTest(Day day){ this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } public static void main(String[] args){ EnumTest e = new EnumTest(Day.FRIDAY); e.tellItLikeItIs(); } } |