├── 05 - A Hello World Program └── src │ └── Application.java ├── 06 - Using Variables └── src │ └── Application.java ├── 07 - Strings - Working With Text └── src │ └── Application.java ├── 08 - While Loops └── src │ └── Application.java ├── 09 - For Loops └── src │ └── Application.java ├── 10 - if └── src │ └── Application.java ├── 11 - Getting User Input └── src │ └── App.java ├── 12 - Do While └── src │ └── App.java ├── 13 - Switch └── src │ └── Application.java ├── 14 - Arrays └── src │ └── App.java ├── 15 - Arrays of Strings └── src │ └── App.java ├── 16 - Multi-Dimensional Arrays └── src │ └── App.java ├── 17 - Classes and Objects └── src │ └── App.java ├── 18 - Methods └── src │ └── App.java ├── 19 - Getters and Return Values └── src │ └── App.java ├── 20 - Method Parameters └── src │ └── App.java ├── 22 - Constructors └── src │ └── App.java ├── 23 - Static (and Final) └── src │ └── App.java ├── 24 - StringBuilder and String Formatting └── src │ └── App.java ├── 25 - The toString Method └── src │ └── App.java ├── 26 - Inheritance └── src │ ├── App.java │ ├── Car.java │ └── Machine.java ├── 27 - Packages └── src │ ├── App.java │ ├── com │ └── caveofprogramming │ │ └── oceangame │ │ └── Aquarium.java │ └── ocean │ ├── Fish.java │ └── plants │ ├── Algae.java │ └── Seaweed.java ├── 28 - Interfaces └── src │ ├── App.java │ ├── IStartable.java │ ├── Info.java │ ├── Machine.java │ └── Person.java ├── 29 - Public,Private,Protected └── src │ ├── App.java │ ├── Grass.java │ └── world │ ├── Field.java │ ├── Oak.java │ └── Plant.java ├── 30 - Polymorphism └── src │ ├── App.java │ ├── Plant.java │ └── Tree.java ├── 31 - Encapsulation and the API Docs └── src │ └── App.java ├── 32 - Casting Numerical Values └── src │ └── App.java ├── 33 - Upcasting and Downcasting └── src │ └── App.java ├── 34 - Using Generics └── src │ └── App.java ├── 35 - Generics and Wildcards └── src │ └── App.java ├── 36 - Anonymous Classes └── src │ └── App.java ├── 37 - Reading Files using Scanner └── src │ └── App.java ├── 38 - Handling exceptions └── src │ ├── demo1 │ └── App.java │ ├── demo2 │ └── App.java │ └── demo3 │ └── App.java ├── 39 - Multiple Exceptions └── src │ ├── App.java │ └── Test.java ├── 40 - Runtime vs. checked Exceptions └── src │ └── App.java ├── 41 - Abstract Classes └── src │ ├── App.java │ ├── Camera.java │ ├── Car.java │ └── Machine.java ├── 42 - Reading Files With File Reader └── src │ └── App.java ├── 43 - Try With Resources └── src │ ├── App.java │ └── App2.java ├── 44 - Creating and Writing Text Files ├── src │ └── App.java └── test.txt ├── 45 - The equals() Method └── src │ └── App.java ├── 46 - Inner Classes └── src │ ├── App.java │ └── Robot.java ├── 47 - Enum Types - Basic and Advanced Usage └── src │ ├── Animal.java │ └── App.java ├── 48 - Recursion - A useful trick up your sleeve └── src │ └── App.java ├── 49 - Serialization - Saving Objects to Files ├── people.bin └── src │ ├── Person.java │ ├── ReadObjects.java │ └── WriteObjects.java ├── 50 - Serializing Arrays ├── src │ ├── Person.java │ ├── ReadObjects.java │ └── WriteObjects.java └── test.ser ├── 51 - ArrayList - Arrays the Easy Way └── src │ └── App.java ├── 52 - Linked Lists └── src │ └── App.java ├── 53 - HashMaps - Retrieving Objects via a Key └── src │ └── App.java ├── 54 - Sorted Maps └── src │ └── App.java ├── 55 - Sets └── src │ └── App.java ├── 56 - Using Custom Objects in Sets and as Keys in Maps └── src │ └── App.java ├── 57 - Sorting Lists └── src │ └── App.java ├── 58 - Natural Ordering └── src │ └── App.java ├── 59 - Queues └── src │ └── App.java ├── 60 - Using Iterators └── src │ └── App.java ├── 61 - Implementing Iterable └── src │ └── UrlLibrary.java ├── 62 - Deciding Which Collections to use └── src │ └── App.java ├── 63 - Complex Data Structures └── src │ └── App.java └── README.md /05 - A Hello World Program/src/Application.java: -------------------------------------------------------------------------------- 1 | public class Application { 2 | 3 | public static void main(String[] args) { 4 | System.out.println("Hello World!"); 5 | } 6 | 7 | } -------------------------------------------------------------------------------- /06 - Using Variables/src/Application.java: -------------------------------------------------------------------------------- 1 | public class Application { 2 | 3 | public static void main(String[] args) { 4 | int myNumber = 88; 5 | short myShort = 847; 6 | long myLong = 9797; 7 | 8 | double myDouble = 7.3243; 9 | float myFloat = 324.3f; 10 | 11 | char myChar = 'y'; 12 | boolean myBoolean = false; 13 | 14 | byte myByte = 127; 15 | 16 | 17 | System.out.println(myNumber); 18 | System.out.println(myShort); 19 | System.out.println(myLong); 20 | System.out.println(myDouble); 21 | System.out.println(myFloat); 22 | System.out.println(myChar); 23 | System.out.println(myBoolean); 24 | System.out.println(myByte); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /07 - Strings - Working With Text/src/Application.java: -------------------------------------------------------------------------------- 1 | public class Application { 2 | public static void main(String[] args) { 3 | 4 | int myInt = 7; 5 | 6 | String text = "Hello"; 7 | 8 | String blank = " "; 9 | 10 | String name = "Bob"; 11 | 12 | String greeting = text + blank + name; 13 | 14 | System.out.println(greeting); 15 | 16 | System.out.println("Hello" + " " + "Bob"); 17 | 18 | System.out.println("My integer is: " + myInt); 19 | 20 | double myDouble = 7.8; 21 | 22 | System.out.println("My number is: " + myDouble + "."); 23 | } 24 | } -------------------------------------------------------------------------------- /08 - While Loops/src/Application.java: -------------------------------------------------------------------------------- 1 | public class Application { 2 | public static void main(String[] args) { 3 | 4 | int value = 0; 5 | 6 | while(value < 10) 7 | { 8 | System.out.println("Hello " + value); 9 | 10 | value = value + 1; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /09 - For Loops/src/Application.java: -------------------------------------------------------------------------------- 1 | public class Application { 2 | public static void main(String[] args) { 3 | 4 | for(int i=0; i < 5; i++) { 5 | System.out.printf("The value of i is: %d\n", i); 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /10 - if/src/Application.java: -------------------------------------------------------------------------------- 1 | public class Application { 2 | public static void main(String[] args) { 3 | 4 | // Some useful conditions: 5 | System.out.println(5 == 5); 6 | System.out.println(10 != 11); 7 | System.out.println(3 < 6); 8 | System.out.println(10 > 100); 9 | 10 | // Using loops with "break": 11 | int loop = 0; 12 | 13 | while(true) { 14 | System.out.println("Looping: " + loop); 15 | 16 | if(loop == 3) { 17 | break; 18 | } 19 | 20 | loop++; 21 | 22 | System.out.println("Running"); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /11 - Getting User Input/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class App { 4 | public static void main(String[] args) { 5 | 6 | // Create scanner object 7 | Scanner input = new Scanner(System.in); 8 | 9 | // Output the prompt 10 | System.out.println("Enter a floating point value: "); 11 | 12 | // Wait for the user to enter something. 13 | double value = input.nextDouble(); 14 | 15 | // Tell them what they entered. 16 | System.out.println("You entered: " + value); 17 | } 18 | } -------------------------------------------------------------------------------- /12 - Do While/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | 4 | public class App { 5 | 6 | public static void main(String[] args) { 7 | 8 | 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | /* 12 | System.out.println("Enter a number: "); 13 | int value = scanner.nextInt(); 14 | 15 | while(value != 5) { 16 | System.out.println("Enter a number: "); 17 | value = scanner.nextInt(); 18 | } 19 | */ 20 | 21 | int value = 0; 22 | do { 23 | System.out.println("Enter a number: "); 24 | value = scanner.nextInt(); 25 | } 26 | while(value != 5); 27 | 28 | System.out.println("Got 5!"); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /13 - Switch/src/Application.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Application { 4 | 5 | 6 | public static void main(String[] args) { 7 | 8 | Scanner input = new Scanner(System.in); 9 | 10 | System.out.println("Please enter a command: "); 11 | String text = input.nextLine(); 12 | 13 | switch (text) { 14 | case "start": 15 | System.out.println("Machine started!"); 16 | break; 17 | 18 | case "stop": 19 | System.out.println("Machine stopped."); 20 | break; 21 | 22 | default: 23 | System.out.println("Command not recognized"); 24 | } 25 | 26 | 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /14 - Arrays/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | public static void main(String[] args) { 3 | 4 | int value = 7; 5 | 6 | int[] values; 7 | values = new int[3]; 8 | 9 | System.out.println(values[0]); 10 | 11 | values[0] = 10; 12 | values[1] = 20; 13 | values[2] = 30; 14 | 15 | System.out.println(values[0]); 16 | System.out.println(values[1]); 17 | System.out.println(values[2]); 18 | 19 | for(int i=0; i < values.length; i++) { 20 | System.out.println(values[i]); 21 | } 22 | 23 | int[] numbers = {5, 6, 7}; 24 | 25 | for(int i=0; i < numbers.length; i++) { 26 | System.out.println(numbers[i]); 27 | } 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /15 - Arrays of Strings/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | 4 | public static void main(String[] args) { 5 | 6 | // Declare array of (references to) strings. 7 | String[] words = new String[3]; 8 | 9 | // Set the array elements (point the references 10 | // at strings) 11 | words[0] = "Hello"; 12 | words[1] = "to"; 13 | words[2] = "you"; 14 | 15 | // Access an array element and print it. 16 | System.out.println(words[2]); 17 | 18 | // Simultaneously declare and initialize an array of strings 19 | String[] fruits = {"apple", "banana", "pear", "kiwi"}; 20 | 21 | // Iterate through an array 22 | for(String fruit: fruits) { 23 | System.out.println(fruit); 24 | } 25 | 26 | // "Default" value for an integer 27 | int value = 0; 28 | 29 | // Default value for a reference is "null" 30 | String text = null; 31 | 32 | System.out.println(text); 33 | 34 | // Declare an array of strings 35 | String[] texts = new String[2]; 36 | 37 | // The references to strings in the array 38 | // are initialized to null. 39 | System.out.println(texts[0]); 40 | 41 | // ... But of course we can set them to actual strings. 42 | texts[0] = "one"; 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /16 - Multi-Dimensional Arrays/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | // 1D array 6 | int[] values = {3, 5, 2343}; 7 | 8 | // Only need 1 index to access values. 9 | System.out.println(values[2]); 10 | 11 | // 2D array (grid or table) 12 | int[][] grid = { 13 | {3, 5, 2343}, 14 | {2, 4}, 15 | {1, 2, 3, 4} 16 | }; 17 | 18 | // Need 2 indices to access values 19 | System.out.println(grid[1][1]); 20 | System.out.println(grid[0][2]); 21 | 22 | // Can also create without initializing. 23 | String[][] texts = new String[2][3]; 24 | 25 | texts[0][1] = "Hello there"; 26 | 27 | System.out.println(texts[0][1]); 28 | 29 | // How to iterate through 2D arrays. 30 | // first iterate through rows, then for each row 31 | // go through the columns. 32 | for(int row=0; row < grid.length; row++) { 33 | for(int col=0; col < grid[row].length; col++) { 34 | System.out.print(grid[row][col] + "\t"); 35 | } 36 | 37 | System.out.println(); 38 | } 39 | 40 | // The last array index is optional. 41 | String[][] words = new String[2][]; 42 | 43 | // Each sub-array is null. 44 | System.out.println(words[0]); 45 | 46 | // We can create the subarrays 'manually'. 47 | words[0] = new String[3]; 48 | 49 | // Can set a values in the sub-array we 50 | // just created. 51 | words[0][1] = "hi there"; 52 | 53 | System.out.println(words[0][1]); 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /17 - Classes and Objects/src/App.java: -------------------------------------------------------------------------------- 1 | class Person { 2 | 3 | // Instance variables (data or "state") 4 | String name; 5 | int age; 6 | 7 | 8 | // Classes can contain 9 | 10 | // 1. Data 11 | // 2. Subroutines (methods) 12 | } 13 | 14 | 15 | public class App { 16 | 17 | public static void main(String[] args) { 18 | 19 | 20 | // Create a Person object using the Person class 21 | Person person1 = new Person(); 22 | person1.name = "Joe Bloggs"; 23 | person1.age = 37; 24 | 25 | // Create a second Person object 26 | Person person2 = new Person(); 27 | person2.name = "Sarah Smith"; 28 | person2.age = 20; 29 | 30 | System.out.println(person1.name); 31 | 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /18 - Methods/src/App.java: -------------------------------------------------------------------------------- 1 | class Person { 2 | 3 | // Instance variables (data or "state") 4 | String name; 5 | int age; 6 | 7 | // Classes can contain 8 | 9 | // 1. Data 10 | // 2. Subroutines (methods) 11 | 12 | void speak() { 13 | for(int i=0; i<3; i++) { 14 | System.out.println("My name is: " + name + " and I am " + age + " years old "); 15 | } 16 | } 17 | 18 | void sayHello() { 19 | System.out.println("Hello there!"); 20 | } 21 | } 22 | 23 | public class App { 24 | 25 | public static void main(String[] args) { 26 | 27 | // Create a Person object using the Person class 28 | Person person1 = new Person(); 29 | person1.name = "Joe Bloggs"; 30 | person1.age = 37; 31 | person1.speak(); 32 | person1.sayHello(); 33 | 34 | // Create a second Person object 35 | Person person2 = new Person(); 36 | person2.name = "Sarah Smith"; 37 | person2.age = 20; 38 | person2.speak(); 39 | person1.sayHello(); 40 | 41 | System.out.println(person1.name); 42 | 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /19 - Getters and Return Values/src/App.java: -------------------------------------------------------------------------------- 1 | class Person { 2 | String name; 3 | int age; 4 | 5 | void speak() { 6 | System.out.println("My name is: " + name); 7 | } 8 | 9 | int calculateYearsToRetirement() { 10 | int yearsLeft = 65 - age; 11 | 12 | return yearsLeft; 13 | } 14 | 15 | int getAge() { 16 | return age; 17 | } 18 | 19 | String getName() { 20 | return name; 21 | } 22 | } 23 | 24 | 25 | public class App { 26 | 27 | public static void main(String[] args) { 28 | Person person1 = new Person(); 29 | 30 | person1.name = "Joe"; 31 | person1.age = 25; 32 | 33 | // person1.speak(); 34 | 35 | int years = person1.calculateYearsToRetirement(); 36 | 37 | System.out.println("Years till retirements " + years); 38 | 39 | int age = person1.getAge(); 40 | String name = person1.getName(); 41 | 42 | System.out.println("Name is: " + name); 43 | System.out.println("Age is: " + age); 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /20 - Method Parameters/src/App.java: -------------------------------------------------------------------------------- 1 | class Frog { 2 | private String name; 3 | private int age; 4 | 5 | public void setName(String name) { 6 | this.name = name; 7 | } 8 | 9 | public void setAge(int age) { 10 | this.age = age; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public int getAge() { 18 | return age; 19 | } 20 | 21 | public void setInfo(String name, int age) { 22 | setName(name); 23 | setAge(age); 24 | } 25 | } 26 | 27 | public class App { 28 | 29 | public static void main(String[] args) { 30 | 31 | Frog frog1 = new Frog(); 32 | 33 | //frog1.name = "Bertie"; 34 | //frog1.age = 1; 35 | 36 | frog1.setName("Bertie"); 37 | frog1.setAge(1); 38 | 39 | System.out.println(frog1.getName()); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /22 - Constructors/src/App.java: -------------------------------------------------------------------------------- 1 | class Machine { 2 | private String name; 3 | private int code; 4 | 5 | public Machine() { 6 | this("Arnie", 0); 7 | 8 | System.out.println("Constructor running!"); 9 | } 10 | 11 | public Machine(String name) { 12 | this(name, 0); 13 | 14 | System.out.println("Second constructor running"); 15 | // No longer need following line, since we're using the other constructor above. 16 | //this.name = name; 17 | } 18 | 19 | public Machine(String name, int code) { 20 | 21 | System.out.println("Third constructor running"); 22 | this.name = name; 23 | this.code = code; 24 | } 25 | } 26 | 27 | public class App { 28 | public static void main(String[] args) { 29 | Machine machine1 = new Machine(); 30 | 31 | Machine machine2 = new Machine("Bertie"); 32 | 33 | Machine machine3 = new Machine("Chalky", 7); 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /23 - Static (and Final)/src/App.java: -------------------------------------------------------------------------------- 1 | class Thing { 2 | public final static int LUCKY_NUMBER = 7; 3 | 4 | public String name; 5 | public static String description; 6 | 7 | public static int count = 0; 8 | 9 | public int id; 10 | 11 | public Thing() { 12 | 13 | id = count; 14 | 15 | count++; 16 | } 17 | 18 | public void showName() { 19 | System.out.println("Object id: " + id + ", " + description + ": " + name); 20 | } 21 | 22 | public static void showInfo() { 23 | System.out.println(description); 24 | // Won't work: System.out.println(name); 25 | } 26 | } 27 | 28 | 29 | public class App { 30 | 31 | public static void main(String[] args) { 32 | 33 | Thing.description = "I am a thing"; 34 | 35 | Thing.showInfo(); 36 | 37 | System.out.println("Before creating objects, count is: " + Thing.count); 38 | 39 | Thing thing1 = new Thing(); 40 | Thing thing2 = new Thing(); 41 | 42 | System.out.println("After creating objects, count is: " + Thing.count); 43 | 44 | thing1.name = "Bob"; 45 | thing2.name = "Sue"; 46 | 47 | thing1.showName(); 48 | thing2.showName(); 49 | 50 | System.out.println(Math.PI); 51 | 52 | System.out.println(Thing.LUCKY_NUMBER); 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /24 - StringBuilder and String Formatting/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | 4 | public static void main(String[] args) { 5 | 6 | // Inefficient 7 | String info = ""; 8 | 9 | info += "My name is Bob."; 10 | info += " "; 11 | info += "I am a builder."; 12 | 13 | System.out.println(info); 14 | 15 | // More efficient. 16 | StringBuilder sb = new StringBuilder(""); 17 | 18 | sb.append("My name is Sue."); 19 | sb.append(" "); 20 | sb.append("I am a lion tamer."); 21 | 22 | System.out.println(sb.toString()); 23 | 24 | // The same as above, but nicer .... 25 | 26 | StringBuilder s = new StringBuilder(); 27 | 28 | s.append("My name is Roger.") 29 | .append(" ") 30 | .append("I am a skydiver."); 31 | 32 | System.out.println(s.toString()); 33 | 34 | ///// Formatting ////////////////////////////////// 35 | 36 | // Outputting newlines and tabs 37 | System.out.print("Here is some text.\tThat was a tab.\nThat was a newline."); 38 | System.out.println(" More text."); 39 | 40 | // Formatting integers 41 | // %-10d means: output an integer in a space ten characters wide, 42 | // padding with space and left-aligning (%10d would right-align) 43 | System.out.printf("Total cost %-10d; quantity is %d\n", 5, 120); 44 | 45 | // Demo-ing integer and string formatting control sequences 46 | for(int i=0; i<20; i++) { 47 | System.out.printf("%-2d: %s\n", i, "here is some text"); 48 | } 49 | 50 | // Formatting floating point value 51 | 52 | // Two decimal place: 53 | System.out.printf("Total value: %.2f\n", 5.6874); 54 | 55 | // One decimal place, left-aligned in 6-character field: 56 | System.out.printf("Total value: %-6.1f\n", 343.23423); 57 | 58 | // You can also use the String.format() method if you want to retrieve 59 | // a formatted string. 60 | String formatted = String.format("This is a floating-point value: %.3f", 5.12345); 61 | System.out.println(formatted); 62 | 63 | // Use double %% for outputting a % sign. 64 | System.out.printf("Giving it %d%% is physically impossible.", 100); 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /25 - The toString Method/src/App.java: -------------------------------------------------------------------------------- 1 | class Frog { 2 | 3 | private int id; 4 | private String name; 5 | 6 | public Frog(int id, String name) { 7 | this.id = id; 8 | this.name = name; 9 | } 10 | 11 | public String toString() { 12 | 13 | return String.format("%-4d: %s", id, name); 14 | 15 | /* 16 | StringBuilder sb = new StringBuilder(); 17 | sb.append(id).append(": ").append(name); 18 | 19 | return sb.toString(); 20 | */ 21 | } 22 | } 23 | 24 | public class App { 25 | 26 | public static void main(String[] args) { 27 | Frog frog1 = new Frog(7, "Freddy"); 28 | Frog frog2 = new Frog(5, "Roger"); 29 | 30 | System.out.println(frog1); 31 | System.out.println(frog2); 32 | } 33 | } -------------------------------------------------------------------------------- /26 - Inheritance/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | Machine mach1 = new Machine(); 5 | 6 | mach1.start(); 7 | mach1.stop(); 8 | 9 | Car car1 = new Car(); 10 | 11 | car1.start(); 12 | car1.wipeWindShield(); 13 | car1.showInfo(); 14 | car1.stop(); 15 | 16 | 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /26 - Inheritance/src/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Machine { 2 | 3 | 4 | @Override 5 | public void start() { 6 | System.out.println("Car started"); 7 | } 8 | 9 | public void wipeWindShield() { 10 | System.out.println("Wiping windshield"); 11 | } 12 | 13 | public void showInfo() { 14 | System.out.println("Car name: " + name); 15 | } 16 | } -------------------------------------------------------------------------------- /26 - Inheritance/src/Machine.java: -------------------------------------------------------------------------------- 1 | public class Machine { 2 | 3 | protected String name = "Machine Type 1"; 4 | 5 | public void start() { 6 | System.out.println("Machine started."); 7 | } 8 | 9 | public void stop() { 10 | System.out.println("Machine stopped."); 11 | } 12 | } -------------------------------------------------------------------------------- /27 - Packages/src/App.java: -------------------------------------------------------------------------------- 1 | import ocean.Fish; 2 | import ocean.plants.Seaweed; 3 | 4 | public class App { 5 | 6 | 7 | public static void main(String[] args) { 8 | Fish fish = new Fish(); 9 | Seaweed weed = new Seaweed(); 10 | } 11 | 12 | } -------------------------------------------------------------------------------- /27 - Packages/src/com/caveofprogramming/oceangame/Aquarium.java: -------------------------------------------------------------------------------- 1 | package com.caveofprogramming.oceangame; 2 | 3 | public class Aquarium { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /27 - Packages/src/ocean/Fish.java: -------------------------------------------------------------------------------- 1 | package ocean; 2 | 3 | public class Fish { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /27 - Packages/src/ocean/plants/Algae.java: -------------------------------------------------------------------------------- 1 | package ocean.plants; 2 | 3 | public class Algae { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /27 - Packages/src/ocean/plants/Seaweed.java: -------------------------------------------------------------------------------- 1 | package ocean.plants; 2 | 3 | public class Seaweed { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /28 - Interfaces/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | Machine mach1 = new Machine(); 6 | mach1.start(); 7 | 8 | Person person1 = new Person("Bob"); 9 | person1.greet(); 10 | 11 | Info info1 = new Machine(); 12 | info1.showInfo(); 13 | 14 | Info info2 = person1; 15 | info2.showInfo(); 16 | 17 | System.out.println(); 18 | 19 | outputInfo(mach1); 20 | outputInfo(person1); 21 | } 22 | 23 | private static void outputInfo(Info info) { 24 | info.showInfo(); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /28 - Interfaces/src/IStartable.java: -------------------------------------------------------------------------------- 1 | public interface IStartable { 2 | public void start(); 3 | public void stop(); 4 | } -------------------------------------------------------------------------------- /28 - Interfaces/src/Info.java: -------------------------------------------------------------------------------- 1 | public interface Info { 2 | public void showInfo(); 3 | } -------------------------------------------------------------------------------- /28 - Interfaces/src/Machine.java: -------------------------------------------------------------------------------- 1 | public class Machine implements Info { 2 | 3 | private int id = 7; 4 | 5 | public void start() { 6 | System.out.println("Machine started."); 7 | } 8 | 9 | public void showInfo() { 10 | System.out.println("Machine ID is: " + id); 11 | } 12 | } -------------------------------------------------------------------------------- /28 - Interfaces/src/Person.java: -------------------------------------------------------------------------------- 1 | public class Person implements Info { 2 | 3 | private String name; 4 | 5 | public Person(String name) { 6 | this.name = name; 7 | } 8 | 9 | public void greet() { 10 | System.out.println("Hello there."); 11 | } 12 | 13 | @Override 14 | public void showInfo() { 15 | System.out.println("Person name is: " + name); 16 | } 17 | } -------------------------------------------------------------------------------- /29 - Public,Private,Protected/src/App.java: -------------------------------------------------------------------------------- 1 | import world.Plant; 2 | 3 | /* 4 | * private --- only within same class 5 | * public --- from anywhere 6 | * protected -- same class, subclass, and same package 7 | * no modifier -- same package only 8 | */ 9 | 10 | public class App { 11 | 12 | /** 13 | * @param args 14 | */ 15 | public static void main(String[] args) { 16 | Plant plant = new Plant(); 17 | 18 | System.out.println(plant.name); 19 | 20 | System.out.println(plant.ID); 21 | 22 | // Won't work --- type is private 23 | //System.out.println(plant.type); 24 | 25 | // size is protected; App is not in the same package as Plant. 26 | // Won't work 27 | // System.out.println(plant.size); 28 | 29 | // Won't work; App and Plant in different packages, height has package-level visibility. 30 | //System.out.println(plant.height); 31 | 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /29 - Public,Private,Protected/src/Grass.java: -------------------------------------------------------------------------------- 1 | import world.Plant; 2 | 3 | 4 | public class Grass extends Plant { 5 | public Grass() { 6 | 7 | // Won't work --- Grass not in same package as plant, even though it's a subclass 8 | // System.out.println(this.height); 9 | } 10 | } -------------------------------------------------------------------------------- /29 - Public,Private,Protected/src/world/Field.java: -------------------------------------------------------------------------------- 1 | package world; 2 | 3 | public class Field { 4 | private Plant plant = new Plant(); 5 | 6 | public Field() { 7 | 8 | // size is protected; Field is in the same package as Plant. 9 | System.out.println(plant.size); 10 | } 11 | } -------------------------------------------------------------------------------- /29 - Public,Private,Protected/src/world/Oak.java: -------------------------------------------------------------------------------- 1 | package world; 2 | 3 | public class Oak extends Plant { 4 | 5 | public Oak() { 6 | 7 | // Won't work -- type is private 8 | // type = "tree"; 9 | 10 | // This works --- size is protected, Oak is a subclass of plant. 11 | this.size = "large"; 12 | 13 | // No access specifier; works because Oak and Plant in same package 14 | this.height = 10; 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /29 - Public,Private,Protected/src/world/Plant.java: -------------------------------------------------------------------------------- 1 | package world; 2 | 3 | class Something { 4 | 5 | } 6 | 7 | public class Plant { 8 | // Bad practice 9 | public String name; 10 | 11 | // Accepatable practice --- it's final. 12 | public final static int ID = 8; 13 | 14 | private String type; 15 | 16 | protected String size; 17 | 18 | int height; 19 | 20 | public Plant() { 21 | this.name = "Freddy"; 22 | this.type = "plant"; 23 | this.size = "medium"; 24 | this.height = 8; 25 | } 26 | } -------------------------------------------------------------------------------- /30 - Polymorphism/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | 6 | Plant plant1 = new Plant(); 7 | 8 | // Tree is a kind of Plant (it extends Plant) 9 | Tree tree = new Tree(); 10 | 11 | // Polymorphism guarantees that we can use a child class 12 | // wherever a parent class is expected. 13 | Plant plant2 = tree; 14 | 15 | // plant2 references a Tree, so the Tree grow() method is called. 16 | plant2.grow(); 17 | 18 | // The type of the reference decided what methods you can actually call; 19 | // we need a Tree-type reference to call tree-specific methods. 20 | tree.shedLeaves(); 21 | 22 | // ... so this won't work. 23 | //plant2.shedLeaves(); 24 | 25 | // Another example of polymorphism. 26 | doGrow(tree); 27 | } 28 | 29 | public static void doGrow(Plant plant) { 30 | plant.grow(); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /30 - Polymorphism/src/Plant.java: -------------------------------------------------------------------------------- 1 | public class Plant { 2 | public void grow() { 3 | System.out.println("Plant growing"); 4 | } 5 | } -------------------------------------------------------------------------------- /30 - Polymorphism/src/Tree.java: -------------------------------------------------------------------------------- 1 | public class Tree extends Plant { 2 | 3 | @Override 4 | public void grow() { 5 | System.out.println("Tree growing"); 6 | } 7 | 8 | public void shedLeaves() { 9 | System.out.println("Leaves shedding."); 10 | } 11 | 12 | } -------------------------------------------------------------------------------- /31 - Encapsulation and the API Docs/src/App.java: -------------------------------------------------------------------------------- 1 | class Plant { 2 | 3 | // Usually only static final members are public 4 | public static final int ID = 7; 5 | 6 | // Instance variables should be declared private, 7 | // or at least protected. 8 | private String name; 9 | 10 | // Only methods intended for use outside the class 11 | // should be public. These methods should be documented 12 | // carefully if you distribute your code. 13 | public String getData() { 14 | String data = "some stuff" + calculateGrowthForecast(); 15 | 16 | return data; 17 | } 18 | 19 | // Methods only used the the class itself should 20 | // be private or protected. 21 | private int calculateGrowthForecast() { 22 | return 9; 23 | } 24 | 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public void setName(String name) { 31 | this.name = name; 32 | } 33 | 34 | 35 | } 36 | 37 | 38 | public class App { 39 | 40 | public static void main(String[] args) { 41 | 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /32 - Casting Numerical Values/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | /** 4 | * @param args 5 | */ 6 | public static void main(String[] args) { 7 | 8 | byte byteValue = 20; 9 | short shortValue = 55; 10 | int intValue = 888; 11 | long longValue = 23355; 12 | 13 | float floatValue = 8834.8f; 14 | float floatValue2 = (float)99.3; 15 | double doubleValue = 32.4; 16 | 17 | System.out.println(Byte.MAX_VALUE); 18 | 19 | intValue = (int)longValue; 20 | 21 | System.out.println(intValue); 22 | 23 | doubleValue = intValue; 24 | System.out.println(doubleValue); 25 | 26 | intValue = (int)floatValue; 27 | System.out.println(intValue); 28 | 29 | 30 | // The following won't work as we expect it to!! 31 | // 128 is too big for a byte. 32 | byteValue = (byte)128; 33 | System.out.println(byteValue); 34 | 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /33 - Upcasting and Downcasting/src/App.java: -------------------------------------------------------------------------------- 1 | class Machine { 2 | public void start() { 3 | System.out.println("Machine started."); 4 | } 5 | } 6 | 7 | class Camera extends Machine { 8 | public void start() { 9 | System.out.println("Camera started."); 10 | } 11 | 12 | public void snap() { 13 | System.out.println("Photo taken."); 14 | } 15 | } 16 | 17 | 18 | public class App { 19 | public static void main(String[] args) { 20 | 21 | Machine machine1 = new Machine(); 22 | Camera camera1 = new Camera(); 23 | 24 | machine1.start(); 25 | camera1.start(); 26 | camera1.snap(); 27 | 28 | // Upcasting 29 | Machine machine2 = camera1; 30 | machine2.start(); 31 | // error: machine2.snap(); 32 | 33 | // Downcasting 34 | Machine machine3 = new Camera(); 35 | Camera camera2 = (Camera)machine3; 36 | camera2.start(); 37 | camera2.snap(); 38 | 39 | // Doesn't work --- runtime error. 40 | Machine machine4 = new Machine(); 41 | // Camera camera3 = (Camera)machine4; 42 | // camera3.start(); 43 | // camera3.snap(); 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /34 - Using Generics/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | 4 | class Animal { 5 | 6 | } 7 | 8 | 9 | public class App { 10 | 11 | public static void main(String[] args) { 12 | 13 | /////////////////// Before Java 5 //////////////////////// 14 | ArrayList list = new ArrayList(); 15 | 16 | list.add("apple"); 17 | list.add("banana"); 18 | list.add("orange"); 19 | 20 | String fruit = (String)list.get(1); 21 | 22 | System.out.println(fruit); 23 | 24 | /////////////// Modern style ////////////////////////////// 25 | 26 | ArrayList strings = new ArrayList(); 27 | 28 | strings.add("cat"); 29 | strings.add("dog"); 30 | strings.add("alligator"); 31 | 32 | String animal = strings.get(1); 33 | 34 | System.out.println(animal); 35 | 36 | 37 | ///////////// There can be more than one type argument //////////////////// 38 | 39 | HashMap map = new HashMap(); 40 | 41 | 42 | //////////// Java 7 style ///////////////////////////////// 43 | 44 | ArrayList someList = new ArrayList<>(); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /35 - Generics and Wildcards/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class Machine { 4 | 5 | @Override 6 | public String toString() { 7 | return "I am a machine"; 8 | } 9 | 10 | public void start() { 11 | System.out.println("Machine starting."); 12 | } 13 | 14 | } 15 | 16 | class Camera extends Machine { 17 | @Override 18 | public String toString() { 19 | return "I am a camera"; 20 | } 21 | 22 | public void snap() { 23 | System.out.println("snap!"); 24 | } 25 | } 26 | 27 | public class App { 28 | 29 | public static void main(String[] args) { 30 | 31 | ArrayList list1 = new ArrayList(); 32 | 33 | list1.add(new Machine()); 34 | list1.add(new Machine()); 35 | 36 | ArrayList list2 = new ArrayList(); 37 | 38 | list2.add(new Camera()); 39 | list2.add(new Camera()); 40 | 41 | showList(list2); 42 | showList2(list1); 43 | showList3(list1); 44 | } 45 | 46 | public static void showList(ArrayList list) { 47 | for (Machine value : list) { 48 | System.out.println(value); 49 | value.start(); 50 | } 51 | 52 | } 53 | 54 | public static void showList2(ArrayList list) { 55 | for (Object value : list) { 56 | System.out.println(value); 57 | } 58 | } 59 | 60 | public static void showList3(ArrayList list) { 61 | for (Object value : list) { 62 | System.out.println(value); 63 | } 64 | } 65 | 66 | 67 | } -------------------------------------------------------------------------------- /36 - Anonymous Classes/src/App.java: -------------------------------------------------------------------------------- 1 | class Machine { 2 | public void start() { 3 | System.out.println("Starting machine ..."); 4 | } 5 | } 6 | 7 | interface Plant { 8 | public void grow(); 9 | } 10 | 11 | public class App { 12 | 13 | public static void main(String[] args) { 14 | 15 | // This is equivalent to creating a class that "extends" 16 | // Machine and overrides the start method. 17 | Machine machine1 = new Machine() { 18 | @Override public void start() { 19 | System.out.println("Camera snapping ...."); 20 | } 21 | }; 22 | 23 | machine1.start(); 24 | 25 | // This is equivalent to creating a class that "implements" 26 | // the Plant interface 27 | Plant plant1 = new Plant() { 28 | @Override 29 | public void grow() { 30 | System.out.println("Plant growing"); 31 | 32 | } 33 | }; 34 | 35 | plant1.grow(); 36 | } 37 | } -------------------------------------------------------------------------------- /37 - Reading Files using Scanner/src/App.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.FileNotFoundException; 3 | import java.util.Scanner; 4 | 5 | 6 | public class App { 7 | 8 | public static void main(String[] args) throws FileNotFoundException { 9 | //String fileName = "C:/Users/John/Desktop/example.txt"; 10 | String fileName = "example.txt"; 11 | 12 | File textFile = new File(fileName); 13 | 14 | Scanner in = new Scanner(textFile); 15 | 16 | int value = in.nextInt(); 17 | System.out.println("Read value: " + value); 18 | 19 | in.nextLine(); 20 | 21 | int count = 2; 22 | while(in.hasNextLine()) { 23 | String line = in.nextLine(); 24 | 25 | System.out.println(count + ": " + line); 26 | count++; 27 | } 28 | 29 | in.close(); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /38 - Handling exceptions/src/demo1/App.java: -------------------------------------------------------------------------------- 1 | package demo1; 2 | import java.io.File; 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | 6 | 7 | 8 | public class App { 9 | 10 | public static void main(String[] args) throws FileNotFoundException { 11 | 12 | File file = new File("test.txt"); 13 | 14 | FileReader fr = new FileReader(file); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /38 - Handling exceptions/src/demo2/App.java: -------------------------------------------------------------------------------- 1 | package demo2; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | 7 | public class App { 8 | 9 | public static void main(String[] args) { 10 | File file = new File("test.txt"); 11 | 12 | try { 13 | FileReader fr = new FileReader(file); 14 | 15 | // This will not be executed if an exception is thrown. 16 | System.out.println("Continuing ...."); 17 | } catch (FileNotFoundException e) { 18 | System.out.println("File not found: " + file.toString()); 19 | } 20 | 21 | System.out.println("Finished."); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /38 - Handling exceptions/src/demo3/App.java: -------------------------------------------------------------------------------- 1 | package demo3; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | 7 | public class App { 8 | 9 | public static void main(String[] args) { 10 | try { 11 | openFile(); 12 | } catch (FileNotFoundException e) { 13 | // PS. This message is too vague : ) 14 | System.out.println("Could not open file"); 15 | } 16 | } 17 | 18 | public static void openFile() throws FileNotFoundException { 19 | File file = new File("test.txt"); 20 | 21 | FileReader fr = new FileReader(file); 22 | 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /39 - Multiple Exceptions/src/App.java: -------------------------------------------------------------------------------- 1 | import java.io.FileNotFoundException; 2 | import java.io.IOException; 3 | import java.text.ParseException; 4 | 5 | public class App { 6 | 7 | public static void main(String[] args) { 8 | Test test = new Test(); 9 | 10 | // Multiple catch blocks 11 | try { 12 | test.run(); 13 | } catch (IOException e) { 14 | // TODO Auto-generated catch block 15 | e.printStackTrace(); 16 | } catch (ParseException e) { 17 | System.out.println("Couldn't parse command file."); 18 | } 19 | 20 | // Try multi-catch (Java 7+ only) 21 | try { 22 | test.run(); 23 | } catch (IOException | ParseException e) { 24 | // TODO Auto-generated catch block 25 | e.printStackTrace(); 26 | } 27 | 28 | // Using polymorphism to catch the parent of all exceptions 29 | try { 30 | test.run(); 31 | } catch (Exception e) { 32 | // TODO Auto-generated catch block 33 | e.printStackTrace(); 34 | } 35 | 36 | // Important to catch exceptions in the right order! 37 | // IOException cannot come first, because it's the parent 38 | // of FileNotFoundException, so would catch both exceptions 39 | // in this case. 40 | try { 41 | test.input(); 42 | } catch (FileNotFoundException e) { 43 | // TODO Auto-generated catch block 44 | e.printStackTrace(); 45 | } catch (IOException e) { 46 | // TODO Auto-generated catch block 47 | e.printStackTrace(); 48 | } 49 | 50 | 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /39 - Multiple Exceptions/src/Test.java: -------------------------------------------------------------------------------- 1 | import java.io.FileNotFoundException; 2 | import java.io.IOException; 3 | import java.text.ParseException; 4 | 5 | 6 | public class Test { 7 | public void run() throws IOException, ParseException { 8 | 9 | 10 | //throw new IOException(); 11 | 12 | throw new ParseException("Error in command list.", 2); 13 | 14 | 15 | } 16 | 17 | public void input() throws IOException, FileNotFoundException { 18 | 19 | } 20 | } -------------------------------------------------------------------------------- /40 - Runtime vs. checked Exceptions/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | // Null pointer exception .... 6 | String text = null; 7 | 8 | System.out.println(text.length()); 9 | 10 | // Arithmetic exception ... (divide by zero) 11 | int value = 7/0; 12 | 13 | // You can actually handle RuntimeExceptions if you want to; 14 | // for example, here we handle an ArrayIndexOutOfBoundsException 15 | String[] texts = { "one", "two", "three" }; 16 | 17 | try { 18 | System.out.println(texts[3]); 19 | } catch (ArrayIndexOutOfBoundsException e) { 20 | System.out.println(e.toString()); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /41 - Abstract Classes/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | Camera cam1 = new Camera(); 5 | cam1.setId(5); 6 | 7 | Car car1 = new Car(); 8 | car1.setId(4); 9 | 10 | car1.run(); 11 | 12 | //Machine machine1 = new Machine(); 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /41 - Abstract Classes/src/Camera.java: -------------------------------------------------------------------------------- 1 | public class Camera extends Machine { 2 | 3 | @Override 4 | public void start() { 5 | System.out.println("Starting camera."); 6 | } 7 | 8 | @Override 9 | public void doStuff() { 10 | System.out.println("Taking a photo"); 11 | 12 | } 13 | 14 | @Override 15 | public void shutdown() { 16 | System.out.println("Shutting down the camera."); 17 | 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /41 - Abstract Classes/src/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Machine { 2 | 3 | @Override 4 | public void start() { 5 | System.out.println("Starting ignition..."); 6 | 7 | } 8 | 9 | @Override 10 | public void doStuff() { 11 | System.out.println("Driving..."); 12 | } 13 | 14 | @Override 15 | public void shutdown() { 16 | System.out.println("Switch off ignition."); 17 | 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /41 - Abstract Classes/src/Machine.java: -------------------------------------------------------------------------------- 1 | public abstract class Machine { 2 | private int id; 3 | 4 | public int getId() { 5 | return id; 6 | } 7 | 8 | public void setId(int id) { 9 | this.id = id; 10 | } 11 | 12 | public abstract void start(); 13 | public abstract void doStuff(); 14 | public abstract void shutdown(); 15 | 16 | public void run() { 17 | start(); 18 | doStuff(); 19 | shutdown(); 20 | } 21 | } -------------------------------------------------------------------------------- /42 - Reading Files With File Reader/src/App.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.File; 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | 7 | 8 | public class App { 9 | 10 | public static void main(String[] args) { 11 | 12 | File file = new File("test.txt"); 13 | 14 | BufferedReader br = null; 15 | 16 | try { 17 | FileReader fr = new FileReader(file); 18 | br = new BufferedReader(fr); 19 | 20 | String line; 21 | 22 | while( (line = br.readLine()) != null ) { 23 | System.out.println(line); 24 | } 25 | 26 | } catch (FileNotFoundException e) { 27 | System.out.println("File not found: " + file.toString()); 28 | } catch (IOException e) { 29 | System.out.println("Unable to read file: " + file.toString()); 30 | } 31 | finally { 32 | try { 33 | br.close(); 34 | } catch (IOException e) { 35 | System.out.println("Unable to close file: " + file.toString()); 36 | } 37 | catch(NullPointerException ex) { 38 | // File was probably never opened! 39 | } 40 | } 41 | 42 | 43 | 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /43 - Try With Resources/src/App.java: -------------------------------------------------------------------------------- 1 | class Temp implements AutoCloseable { 2 | 3 | @Override 4 | public void close() throws Exception { 5 | System.out.println("Closing!"); 6 | throw new Exception("oh no!"); 7 | } 8 | 9 | } 10 | 11 | 12 | public class App { 13 | 14 | public static void main(String[] args) { 15 | 16 | try(Temp temp = new Temp()) { 17 | 18 | } catch (Exception e) { 19 | // TODO Auto-generated catch block 20 | e.printStackTrace(); 21 | } 22 | 23 | 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /43 - Try With Resources/src/App2.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.File; 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | 7 | public class App2 { 8 | 9 | public static void main(String[] args) { 10 | File file = new File("test.txt"); 11 | 12 | try (BufferedReader br = new BufferedReader(new FileReader(file))) { 13 | String line; 14 | 15 | while ((line = br.readLine()) != null) { 16 | System.out.println(line); 17 | } 18 | } catch (FileNotFoundException e) { 19 | System.out.println("Can't find file " + file.toString()); 20 | } catch (IOException e) { 21 | System.out.println("Unable to read file " + file.toString()); 22 | } 23 | 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /44 - Creating and Writing Text Files/src/App.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedWriter; 2 | import java.io.File; 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | 7 | public class App { 8 | 9 | 10 | public static void main(String[] args) { 11 | File file = new File("test.txt"); 12 | 13 | try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) { 14 | br.write("This is line one"); 15 | br.newLine(); 16 | br.write("This is line two"); 17 | br.newLine(); 18 | br.write("Last line."); 19 | } catch (IOException e) { 20 | System.out.println("Unable to read file " + file.toString()); 21 | } 22 | 23 | 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /44 - Creating and Writing Text Files/test.txt: -------------------------------------------------------------------------------- 1 | This is line one 2 | This is line two 3 | Last line. -------------------------------------------------------------------------------- /45 - The equals() Method/src/App.java: -------------------------------------------------------------------------------- 1 | class Person { 2 | private int id; 3 | private String name; 4 | 5 | public Person(int id, String name) { 6 | this.id = id; 7 | this.name = name; 8 | } 9 | 10 | @Override 11 | public String toString() { 12 | return "Person [id=" + id + ", name=" + name + "]"; 13 | } 14 | 15 | @Override 16 | public int hashCode() { 17 | final int prime = 31; 18 | int result = 1; 19 | result = prime * result + id; 20 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 21 | return result; 22 | } 23 | 24 | @Override 25 | public boolean equals(Object obj) { 26 | if (this == obj) 27 | return true; 28 | if (obj == null) 29 | return false; 30 | if (getClass() != obj.getClass()) 31 | return false; 32 | Person other = (Person) obj; 33 | if (id != other.id) 34 | return false; 35 | if (name == null) { 36 | if (other.name != null) 37 | return false; 38 | } else if (!name.equals(other.name)) 39 | return false; 40 | return true; 41 | } 42 | 43 | 44 | } 45 | 46 | public class App { 47 | 48 | public static void main(String[] args) { 49 | 50 | System.out.println(new Object()); 51 | 52 | Person person1 = new Person(5, "Bob"); 53 | Person person2 = new Person(5, "Bob"); 54 | 55 | 56 | System.out.println(person1.equals(person2)); 57 | 58 | Double value1 = 7.2; 59 | Double value2 = 7.2; 60 | 61 | System.out.println(value1.equals(value2)); 62 | 63 | Integer number1 = 6; 64 | Integer number2 = 6; 65 | 66 | System.out.println(number1.equals(number2)); 67 | 68 | String text1 = "Hello"; 69 | String text2 = "Hellodfadf".substring(0, 5); 70 | 71 | System.out.println(text2); 72 | 73 | System.out.println(text1.equals(text2)); 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /46 - Inner Classes/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | 4 | public static void main(String[] args) { 5 | 6 | Robot robot = new Robot(7); 7 | robot.start(); 8 | 9 | // The syntax below will only work if Brain is 10 | // declared public. It is quite unusual to do this. 11 | // Robot.Brain brain = robot.new Brain(); 12 | // brain.think(); 13 | 14 | // This is very typical Java syntax, using 15 | // a static inner class. 16 | Robot.Battery battery = new Robot.Battery(); 17 | battery.charge(); 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /46 - Inner Classes/src/Robot.java: -------------------------------------------------------------------------------- 1 | public class Robot { 2 | 3 | private int id; 4 | 5 | // Non-static nested classes have access to the enclosing 6 | // class's instance data. E.g. implement Iterable 7 | // http://www.caveofprogramming.com/java/using-iterable-java-collections-framework-video-tutorial-part-11/ 8 | // Use them to group functionality. 9 | private class Brain { 10 | public void think() { 11 | System.out.println("Robot " + id + " is thinking."); 12 | } 13 | } 14 | 15 | // static inner classes do not have access to instance data. 16 | // They are really just like "normal" classes, except that they are grouped 17 | // within an outer class. Use them for grouping classes together. 18 | public static class Battery { 19 | public void charge() { 20 | System.out.println("Battery charging..."); 21 | } 22 | } 23 | 24 | public Robot(int id) { 25 | this.id = id; 26 | } 27 | 28 | public void start() { 29 | System.out.println("Starting robot " + id); 30 | 31 | // Use Brain. We don't have an instance of brain 32 | // until we create one. Instances of brain are 33 | // always associated with instances of Robot (the 34 | // enclosing class). 35 | Brain brain = new Brain(); 36 | brain.think(); 37 | 38 | final String name = "Robert"; 39 | 40 | // Sometimes it's useful to create local classes 41 | // within methods. You can use them only within the method. 42 | class Temp { 43 | public void doSomething() { 44 | System.out.println("ID is: " + id); 45 | System.out.println("My name is " + name); 46 | } 47 | } 48 | 49 | Temp temp = new Temp(); 50 | temp.doSomething(); 51 | } 52 | } -------------------------------------------------------------------------------- /47 - Enum Types - Basic and Advanced Usage/src/Animal.java: -------------------------------------------------------------------------------- 1 | public enum Animal { 2 | CAT("Fergus"), DOG("Fido"), MOUSE("Jerry"); 3 | 4 | private String name; 5 | 6 | Animal(String name) { 7 | this.name = name; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public String toString() { 15 | return "This animal is called: " + name; 16 | } 17 | } -------------------------------------------------------------------------------- /47 - Enum Types - Basic and Advanced Usage/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | Animal animal = Animal.DOG; 6 | 7 | switch(animal) { 8 | case CAT: 9 | System.out.println("Cat"); 10 | break; 11 | case DOG: 12 | System.out.println("Dog"); 13 | break; 14 | case MOUSE: 15 | break; 16 | default: 17 | break; 18 | 19 | } 20 | 21 | System.out.println(Animal.DOG); 22 | System.out.println("Enum name as a string: " + Animal.DOG.name()); 23 | 24 | System.out.println(Animal.DOG.getClass()); 25 | 26 | System.out.println(Animal.DOG instanceof Enum); 27 | 28 | System.out.println(Animal.MOUSE.getName()); 29 | 30 | Animal animal2 = Animal.valueOf("CAT"); 31 | 32 | System.out.println(animal2); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /48 - Recursion - A useful trick up your sleeve/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | 4 | public static void main(String[] args) { 5 | 6 | // E.g. 4! = 4*3*2*1 (factorial 4) 7 | 8 | System.out.println(factorial(5)); 9 | } 10 | 11 | private static int factorial(int value) { 12 | //System.out.println(value); 13 | 14 | if(value == 1) { 15 | return 1; 16 | } 17 | 18 | return factorial(value - 1) * value; 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /49 - Serialization - Saving Objects to Files/people.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/caveofprogramming/java-beginners/c9bb3a385955044594e3a064ee44a50bda02a361/49 - Serialization - Saving Objects to Files/people.bin -------------------------------------------------------------------------------- /49 - Serialization - Saving Objects to Files/src/Person.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | 3 | public class Person implements Serializable { 4 | 5 | private static final long serialVersionUID = 4801633306273802062L; 6 | 7 | private int id; 8 | private String name; 9 | 10 | public Person(int id, String name) { 11 | this.id = id; 12 | this.name = name; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return "Person [id=" + id + ", name=" + name + "]"; 18 | } 19 | } 20 | 21 | // www.caveofprogramming.com -------------------------------------------------------------------------------- /49 - Serialization - Saving Objects to Files/src/ReadObjects.java: -------------------------------------------------------------------------------- 1 | import java.io.FileInputStream; 2 | import java.io.FileNotFoundException; 3 | import java.io.IOException; 4 | import java.io.ObjectInputStream; 5 | 6 | 7 | 8 | public class ReadObjects { 9 | 10 | 11 | public static void main(String[] args) { 12 | System.out.println("Reading objects..."); 13 | 14 | try(FileInputStream fi = new FileInputStream("people.bin")) { 15 | 16 | ObjectInputStream os = new ObjectInputStream(fi); 17 | 18 | Person person1 = (Person)os.readObject(); 19 | Person person2 = (Person)os.readObject(); 20 | 21 | os.close(); 22 | 23 | System.out.println(person1); 24 | System.out.println(person2); 25 | 26 | } catch (FileNotFoundException e) { 27 | // TODO Auto-generated catch block 28 | e.printStackTrace(); 29 | } catch (IOException e) { 30 | // TODO Auto-generated catch block 31 | e.printStackTrace(); 32 | } catch (ClassNotFoundException e) { 33 | // TODO Auto-generated catch block 34 | e.printStackTrace(); 35 | } 36 | 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /49 - Serialization - Saving Objects to Files/src/WriteObjects.java: -------------------------------------------------------------------------------- 1 | import java.io.FileNotFoundException; 2 | import java.io.FileOutputStream; 3 | import java.io.IOException; 4 | import java.io.ObjectOutputStream; 5 | 6 | 7 | 8 | public class WriteObjects { 9 | 10 | public static void main(String[] args) { 11 | System.out.println("Writing objects..."); 12 | 13 | Person mike = new Person(543, "Mike"); 14 | Person sue = new Person(123, "Sue"); 15 | 16 | System.out.println(mike); 17 | System.out.println(sue); 18 | 19 | try(FileOutputStream fs = new FileOutputStream("people.bin")) { 20 | 21 | ObjectOutputStream os = new ObjectOutputStream(fs); 22 | 23 | os.writeObject(mike); 24 | os.writeObject(sue); 25 | 26 | os.close(); 27 | 28 | } catch (FileNotFoundException e) { 29 | // TODO Auto-generated catch block 30 | e.printStackTrace(); 31 | } catch (IOException e) { 32 | // TODO Auto-generated catch block 33 | e.printStackTrace(); 34 | } 35 | 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /50 - Serializing Arrays/src/Person.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | 3 | public class Person implements Serializable { 4 | 5 | private static final long serialVersionUID = 4801633306273802062L; 6 | 7 | private int id; 8 | private String name; 9 | 10 | public Person(int id, String name) { 11 | this.id = id; 12 | this.name = name; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return "Person [id=" + id + ", name=" + name + "]"; 18 | } 19 | } 20 | 21 | // www.caveofprogramming.com -------------------------------------------------------------------------------- /50 - Serializing Arrays/src/ReadObjects.java: -------------------------------------------------------------------------------- 1 | import java.io.FileInputStream; 2 | import java.io.FileNotFoundException; 3 | import java.io.IOException; 4 | import java.io.ObjectInputStream; 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | public class ReadObjects { 10 | 11 | public static void main(String[] args) { 12 | System.out.println("Reading objects..."); 13 | 14 | try (FileInputStream fi = new FileInputStream("test.ser"); ObjectInputStream os = new ObjectInputStream(fi)) { 15 | 16 | // Read entire array 17 | Person[] people = (Person[])os.readObject(); 18 | 19 | // Read entire arraylist 20 | @SuppressWarnings("unchecked") 21 | ArrayList peopleList = (ArrayList)os.readObject(); 22 | 23 | for(Person person: people) { 24 | System.out.println(person); 25 | } 26 | 27 | for(Person person: peopleList) { 28 | System.out.println(person); 29 | } 30 | 31 | // Read objects one by one. 32 | int num = os.readInt(); 33 | 34 | for(int i=0; i peopleList = new ArrayList(Arrays.asList(people)); 17 | 18 | try (FileOutputStream fs = new FileOutputStream("test.ser"); ObjectOutputStream os = new ObjectOutputStream(fs)) { 19 | 20 | // Write entire array 21 | os.writeObject(people); 22 | 23 | // Write arraylist 24 | os.writeObject(peopleList); 25 | 26 | // Write objects one by one 27 | os.writeInt(peopleList.size()); 28 | 29 | for(Person person: peopleList) { 30 | os.writeObject(person); 31 | } 32 | 33 | } catch (FileNotFoundException e) { 34 | // TODO Auto-generated catch block 35 | e.printStackTrace(); 36 | } catch (IOException e) { 37 | // TODO Auto-generated catch block 38 | e.printStackTrace(); 39 | } 40 | 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /50 - Serializing Arrays/test.ser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/caveofprogramming/java-beginners/c9bb3a385955044594e3a064ee44a50bda02a361/50 - Serializing Arrays/test.ser -------------------------------------------------------------------------------- /51 - ArrayList - Arrays the Easy Way/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class App { 5 | 6 | public static void main(String[] args) { 7 | ArrayList numbers = new ArrayList(); 8 | 9 | // Adding 10 | numbers.add(10); 11 | numbers.add(100); 12 | numbers.add(40); 13 | 14 | // Retrieving 15 | System.out.println(numbers.get(0)); 16 | 17 | System.out.println("nIteration #1: "); 18 | // Indexed for loop iteration 19 | for (int i = 0; i < numbers.size(); i++) { 20 | System.out.println(numbers.get(i)); 21 | } 22 | 23 | // Removing items (careful!) 24 | numbers.remove(numbers.size() - 1); 25 | 26 | // This is VERY slow 27 | numbers.remove(0); 28 | 29 | System.out.println("nIteration #2: "); 30 | for (Integer value : numbers) { 31 | System.out.println(value); 32 | } 33 | 34 | // List interface ... 35 | List values = new ArrayList(); 36 | } 37 | } -------------------------------------------------------------------------------- /52 - Linked Lists/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.List; 4 | 5 | 6 | public class App { 7 | 8 | 9 | public static void main(String[] args) { 10 | /* 11 | * ArrayLists manage arrays internally. 12 | * [0][1][2][3][4][5] .... 13 | */ 14 | List arrayList = new ArrayList(); 15 | 16 | /* 17 | * LinkedLists consists of elements where each element 18 | * has a reference to the previous and next element 19 | * [0]->[1]->[2] .... 20 | * <- <- 21 | */ 22 | List linkedList = new LinkedList(); 23 | 24 | doTimings("ArrayList", arrayList); 25 | doTimings("LinkedList" , linkedList); 26 | } 27 | 28 | private static void doTimings(String type, List list) { 29 | 30 | for(int i=0; i<1E5; i++) { 31 | list.add(i); 32 | } 33 | 34 | long start = System.currentTimeMillis(); 35 | 36 | /* 37 | // Add items at end of list 38 | for(int i=0; i<1E5; i++) { 39 | list.add(i); 40 | } 41 | */ 42 | 43 | // Add items elsewhere in list 44 | for(int i=0; i<1E5; i++) { 45 | list.add(0, i); 46 | } 47 | 48 | long end = System.currentTimeMillis(); 49 | 50 | System.out.println("Time taken: " + (end - start) + " ms for " + type); 51 | } 52 | 53 | 54 | 55 | } -------------------------------------------------------------------------------- /53 - HashMaps - Retrieving Objects via a Key/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class App { 5 | 6 | 7 | public static void main(String[] args) { 8 | 9 | HashMap map = new HashMap(); 10 | 11 | map.put(5, "Five"); 12 | map.put(8, "Eight"); 13 | map.put(6, "Six"); 14 | map.put(4, "Four"); 15 | map.put(2, "Two"); 16 | 17 | String text = map.get(6); 18 | 19 | System.out.println(text); 20 | 21 | for(Map.Entry entry: map.entrySet()) { 22 | int key = entry.getKey(); 23 | String value = entry.getValue(); 24 | 25 | System.out.println(key + ": " + value); 26 | } 27 | 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /54 - Sorted Maps/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.LinkedHashMap; 3 | import java.util.Map; 4 | import java.util.TreeMap; 5 | 6 | public class App { 7 | 8 | public static void main(String[] args) { 9 | Map hashMap = new HashMap(); 10 | Map linkedHashMap = new LinkedHashMap(); 11 | Map treeMap = new TreeMap(); 12 | 13 | testMap(treeMap); 14 | } 15 | 16 | public static void testMap(Map map) { 17 | map.put(9, "fox"); 18 | map.put(4, "cat"); 19 | map.put(8, "dog"); 20 | map.put(1, "giraffe"); 21 | map.put(0, "swan"); 22 | map.put(15, "bear"); 23 | map.put(6, "snake"); 24 | 25 | for(Integer key: map.keySet()) { 26 | String value = map.get(key); 27 | 28 | System.out.println(key + ": " + value); 29 | } 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /55 - Sets/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | import java.util.TreeSet; 4 | 5 | public class App { 6 | 7 | public static void main(String[] args) { 8 | 9 | // HashSet does not retain order. 10 | // Set set1 = new HashSet(); 11 | 12 | // LinkedHashSet remembers the order you added items in 13 | // Set set1 = new LinkedHashSet(); 14 | 15 | // TreeSet sorts in natural order 16 | Set set1 = new TreeSet(); 17 | 18 | if (set1.isEmpty()) { 19 | System.out.println("Set is empty at start"); 20 | } 21 | 22 | set1.add("dog"); 23 | set1.add("cat"); 24 | set1.add("mouse"); 25 | set1.add("snake"); 26 | set1.add("bear"); 27 | 28 | if (set1.isEmpty()) { 29 | System.out.println("Set is empty after adding (no!)"); 30 | } 31 | 32 | // Adding duplicate items does nothing. 33 | set1.add("mouse"); 34 | 35 | System.out.println(set1); 36 | 37 | // ///////// Iteration //////////////// 38 | 39 | for (String element : set1) { 40 | System.out.println(element); 41 | } 42 | 43 | // ////////// Does set contains a given item? ////////// 44 | if (set1.contains("aardvark")) { 45 | System.out.println("Contains aardvark"); 46 | } 47 | 48 | if (set1.contains("cat")) { 49 | System.out.println("Contains cat"); 50 | } 51 | 52 | /// set2 contains some common elements with set1, and some new 53 | 54 | Set set2 = new TreeSet(); 55 | 56 | set2.add("dog"); 57 | set2.add("cat"); 58 | set2.add("giraffe"); 59 | set2.add("monkey"); 60 | set2.add("ant"); 61 | 62 | ////////////// Intersection /////////////////// 63 | 64 | Set intersection = new HashSet(set1); 65 | 66 | intersection.retainAll(set2); // keeps similarities between set 1 and set 2 67 | 68 | System.out.println(intersection); 69 | 70 | ////////////// Difference ///////////////////////// 71 | 72 | Set difference = new HashSet(set2); 73 | 74 | difference.removeAll(set1); // removes differences between set1 and set2, prints what is left of set2 75 | System.out.println(difference); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /56 - Using Custom Objects in Sets and as Keys in Maps/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedHashMap; 2 | import java.util.LinkedHashSet; 3 | import java.util.Map; 4 | import java.util.Set; 5 | 6 | class Person { 7 | private int id; 8 | private String name; 9 | 10 | public Person(int id, String name) { 11 | this.id = id; 12 | this.name = name; 13 | } 14 | 15 | public String toString() { 16 | return "{ID is: " + id + "; name is: " + name + "}"; 17 | } 18 | 19 | @Override 20 | public int hashCode() { 21 | final int prime = 31; 22 | int result = 1; 23 | result = prime * result + id; 24 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 25 | return result; 26 | } 27 | 28 | @Override 29 | public boolean equals(Object obj) { 30 | if (this == obj) 31 | return true; 32 | if (obj == null) 33 | return false; 34 | if (getClass() != obj.getClass()) 35 | return false; 36 | final Person other = (Person) obj; 37 | if (id != other.id) 38 | return false; 39 | if (name == null) { 40 | if (other.name != null) 41 | return false; 42 | } else if (!name.equals(other.name)) 43 | return false; 44 | return true; 45 | } 46 | 47 | 48 | } 49 | 50 | 51 | public class App { 52 | 53 | public static void main(String[] args) { 54 | 55 | Person p1 = new Person(0, "Bob"); 56 | Person p2 = new Person(1, "Sue"); 57 | Person p3 = new Person(2, "Mike"); 58 | Person p4 = new Person(1, "Sue"); 59 | 60 | Map map = new LinkedHashMap(); 61 | 62 | map.put(p1, 1); 63 | map.put(p2, 2); 64 | map.put(p3, 3); 65 | map.put(p4, 1); 66 | 67 | for(Person key: map.keySet()) { 68 | System.out.println(key + ": " + map.get(key)); 69 | } 70 | 71 | Set set = new LinkedHashSet(); 72 | 73 | set.add(p1); 74 | set.add(p2); 75 | set.add(p3); 76 | set.add(p4); 77 | 78 | System.out.println(set); 79 | } 80 | 81 | } -------------------------------------------------------------------------------- /57 - Sorting Lists/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.Comparator; 4 | import java.util.List; 5 | 6 | class Person { 7 | private int id; 8 | private String name; 9 | 10 | public Person(int id, String name) { 11 | this.id = id; 12 | this.name = name; 13 | } 14 | 15 | public int getId() { 16 | return id; 17 | } 18 | 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public void setName(String name) { 28 | this.name = name; 29 | } 30 | 31 | public String toString() { 32 | return id + ": " + name; 33 | } 34 | } 35 | 36 | class StringLengthComparator implements Comparator { 37 | 38 | @Override 39 | public int compare(String s1, String s2) { 40 | 41 | int len1 = s1.length(); 42 | int len2 = s2.length(); 43 | 44 | if(len1 > len2) { 45 | return 1; 46 | } 47 | else if(len1 < len2) { 48 | return -1; 49 | } 50 | 51 | return 0; 52 | } 53 | } 54 | 55 | class ReverseAlphabeticalComparator implements Comparator { 56 | 57 | @Override 58 | public int compare(String s1, String s2) { 59 | return -s1.compareTo(s2); 60 | } 61 | } 62 | 63 | public class App { 64 | 65 | 66 | public static void main(String[] args) { 67 | 68 | ////////////////////// Sorting Strings //////////////////////////////// 69 | List animals = new ArrayList(); 70 | 71 | animals.add("tiger"); 72 | animals.add("lion"); 73 | animals.add("cat"); 74 | animals.add("snake"); 75 | animals.add("mongoose"); 76 | animals.add("elephant"); 77 | 78 | // Collections.sort(animals, new StringLengthComparator()); 79 | Collections.sort(animals, new ReverseAlphabeticalComparator()); 80 | 81 | for(String animal: animals) { 82 | System.out.println(animal); 83 | } 84 | 85 | ////////////////////// Sorting Numbers //////////////////////////////// 86 | List numbers = new ArrayList(); 87 | 88 | numbers.add(3); 89 | numbers.add(36); 90 | numbers.add(73); 91 | numbers.add(40); 92 | numbers.add(1); 93 | 94 | Collections.sort(numbers, new Comparator() { 95 | public int compare(Integer num1, Integer num2) { 96 | return -num1.compareTo(num2); 97 | } 98 | }); 99 | 100 | for(Integer number: numbers) { 101 | System.out.println(number); 102 | } 103 | 104 | ////////////////////// Sorting arbitary objects //////////////////////////////// 105 | 106 | List people = new ArrayList(); 107 | 108 | people.add(new Person(1, "Joe")); 109 | people.add(new Person(3, "Bob")); 110 | people.add(new Person(4, "Clare")); 111 | people.add(new Person(2, "Sue")); 112 | 113 | // Sort in order of ID 114 | Collections.sort(people, new Comparator() { 115 | public int compare(Person p1, Person p2) { 116 | 117 | if(p1.getId() > p2.getId()) { 118 | return 1; 119 | } 120 | else if(p1.getId() < p2.getId()) { 121 | return -1; 122 | } 123 | 124 | return 0; 125 | } 126 | }); 127 | 128 | for(Person person: people) { 129 | System.out.println(person); 130 | } 131 | 132 | System.out.println("n"); 133 | // Sort in order of name 134 | Collections.sort(people, new Comparator() { 135 | public int compare(Person p1, Person p2) { 136 | return p1.getName().compareTo(p2.getName()); 137 | } 138 | }); 139 | 140 | for(Person person: people) { 141 | System.out.println(person); 142 | } 143 | 144 | } 145 | 146 | } -------------------------------------------------------------------------------- /58 - Natural Ordering/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collection; 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.SortedSet; 6 | import java.util.TreeSet; 7 | 8 | class Person implements Comparable { 9 | private String name; 10 | 11 | public Person(String name) { 12 | this.name = name; 13 | } 14 | 15 | public String toString() { 16 | return name; 17 | } 18 | 19 | @Override 20 | public int hashCode() { 21 | final int prime = 31; 22 | int result = 1; 23 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 24 | return result; 25 | } 26 | 27 | @Override 28 | public boolean equals(Object obj) { 29 | if (this == obj) 30 | return true; 31 | if (obj == null) 32 | return false; 33 | if (getClass() != obj.getClass()) 34 | return false; 35 | final Person other = (Person) obj; 36 | if (name == null) { 37 | if (other.name != null) 38 | return false; 39 | } else if (!name.equals(other.name)) 40 | return false; 41 | return true; 42 | } 43 | 44 | @Override 45 | public int compareTo(Person person) { 46 | int len1 = name.length(); 47 | int len2 = person.name.length(); 48 | 49 | if(len1 > len2) { 50 | return 1; 51 | } 52 | else if(len1 < len2) { 53 | return -1; 54 | } 55 | else { 56 | return name.compareTo(person.name); 57 | } 58 | } 59 | } 60 | 61 | public class App { 62 | 63 | public static void main(String[] args) { 64 | List list = new ArrayList(); 65 | SortedSet set = new TreeSet(); 66 | 67 | addElements(list); 68 | addElements(set); 69 | 70 | Collections.sort(list); 71 | 72 | showElements(list); 73 | System.out.println(); 74 | showElements(set); 75 | } 76 | 77 | private static void addElements(Collection col) { 78 | col.add(new Person("Joe")); 79 | col.add(new Person("Sue")); 80 | col.add(new Person("Juliet")); 81 | col.add(new Person("Clare")); 82 | col.add(new Person("Mike")); 83 | } 84 | 85 | private static void showElements(Collection col) { 86 | for(Person element: col) { 87 | System.out.println(element); 88 | } 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /59 - Queues/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.NoSuchElementException; 2 | import java.util.Queue; 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | 5 | 6 | 7 | 8 | public class App { 9 | 10 | public static void main(String[] args) { 11 | // (head) <- oooooooooooooooooooooooo <- (tail) FIFO (first in, first out) 12 | 13 | Queue q1 = new ArrayBlockingQueue(3); 14 | 15 | // Throws NoSuchElement exception --- no items in queue yet 16 | // System.out.println("Head of queue is: " + q1.element()); 17 | 18 | q1.add(10); 19 | q1.add(20); 20 | q1.add(30); 21 | 22 | System.out.println("Head of queue is: " + q1.element()); 23 | 24 | try { 25 | q1.add(40); 26 | } catch (IllegalStateException e) { 27 | System.out.println("Tried to add too many items to the queue."); 28 | } 29 | 30 | for(Integer value: q1) { 31 | System.out.println("Queue value: " + value); 32 | } 33 | 34 | System.out.println("Removed from queue: " + q1.remove()); 35 | System.out.println("Removed from queue: " + q1.remove()); 36 | System.out.println("Removed from queue: " + q1.remove()); 37 | 38 | try { 39 | System.out.println("Removed from queue: " + q1.remove()); 40 | } catch (NoSuchElementException e) { 41 | System.out.println("Tried to remove too many items from queue"); 42 | } 43 | 44 | //////////////////////////////////////////////////////////////////// 45 | 46 | Queue q2 = new ArrayBlockingQueue(2); 47 | 48 | System.out.println("Queue 2 peek: " + q2.peek()); 49 | 50 | q2.offer(10); 51 | q2.offer(20); 52 | 53 | System.out.println("Queue 2 peek: " + q2.peek()); 54 | 55 | if(q2.offer(30) == false) { 56 | System.out.println("Offer failed to add third item."); 57 | } 58 | 59 | for(Integer value: q2) { 60 | System.out.println("Queue 2 value: " + value); 61 | } 62 | 63 | System.out.println("Queue 2 poll: " + q2.poll()); 64 | System.out.println("Queue 2 poll: " + q2.poll()); 65 | System.out.println("Queue 2 poll: " + q2.poll()); 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /60 - Using Iterators/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.LinkedList; 3 | 4 | public class App { 5 | 6 | public static void main(String[] args) { 7 | 8 | LinkedList animals = new LinkedList(); 9 | 10 | animals.add("fox"); 11 | animals.add("cat"); 12 | animals.add("dog"); 13 | animals.add("rabbit"); 14 | 15 | // "Old" way of iterating through lists (except that generics 16 | // didn't exist pre Java 5). This way is still an integral part 17 | // of Java; it allows you to remove items from the list 18 | // and also supports the "for each" syntax behind the scenes. 19 | 20 | Iterator it = animals.iterator(); 21 | 22 | while (it.hasNext()) { 23 | String value = it.next(); 24 | System.out.println(value); 25 | 26 | if(value.equals("cat")) { 27 | it.remove(); 28 | } 29 | } 30 | 31 | System.out.println(); 32 | 33 | /* 34 | * If you want to add items to a list while iterating through 35 | * it, get a ListIterator using the .listIterator() method. 36 | * ListIterator also has a previous() method, allowing you to 37 | * "rewind" the iterator so that you can add items before 38 | * the current item. 39 | */ 40 | 41 | // / Modern iteration, Java 5 and later; "for each" loop 42 | 43 | for (String animal : animals) { 44 | System.out.println(animal); 45 | 46 | // The following won't work; you need an iterator. 47 | // Throws ConcurrentModificationException 48 | // animals.remove(2); 49 | } 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /61 - Implementing Iterable/src/UrlLibrary.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.net.URL; 4 | import java.util.Iterator; 5 | import java.util.LinkedList; 6 | 7 | 8 | public class UrlLibrary implements Iterable { 9 | private LinkedList urls = new LinkedList(); 10 | 11 | private class UrlIterator implements Iterator { 12 | 13 | private int index = 0; 14 | 15 | @Override 16 | public boolean hasNext() { 17 | return index < urls.size(); 18 | } 19 | 20 | @Override 21 | public String next() { 22 | 23 | StringBuilder sb = new StringBuilder(); 24 | 25 | try { 26 | URL url = new URL(urls.get(index)); 27 | 28 | BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); 29 | 30 | String line = null; 31 | 32 | while( (line = br.readLine()) != null) { 33 | sb.append(line); 34 | sb.append("n"); 35 | } 36 | 37 | br.close(); 38 | 39 | } catch (Exception e) { 40 | // TODO Auto-generated catch block 41 | e.printStackTrace(); 42 | } 43 | 44 | index++; 45 | 46 | return sb.toString(); 47 | } 48 | 49 | @Override 50 | public void remove() { 51 | urls.remove(index); 52 | } 53 | 54 | } 55 | 56 | public UrlLibrary() { 57 | urls.add("http://www.caveofprogramming.com"); 58 | urls.add("http://www.facebook.com/caveofprogramming"); 59 | urls.add("http://news.bbc.co.uk"); 60 | } 61 | 62 | @Override 63 | public Iterator iterator() { 64 | return new UrlIterator(); 65 | } 66 | 67 | /* 68 | @Override 69 | public Iterator iterator() { 70 | return urls.iterator(); 71 | } 72 | */ 73 | 74 | 75 | } -------------------------------------------------------------------------------- /62 - Deciding Which Collections to use/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collection; 3 | import java.util.HashMap; 4 | import java.util.HashSet; 5 | import java.util.LinkedHashMap; 6 | import java.util.LinkedHashSet; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.Set; 11 | import java.util.TreeMap; 12 | import java.util.TreeSet; 13 | 14 | 15 | 16 | 17 | public class App { 18 | 19 | public static void main(String[] args) { 20 | 21 | /* 22 | * Consider: 23 | * 1. what you need the collection to do 24 | * 2. are you using the fastest collection for your purposes 25 | * (think about insertion/deletion, retrieval and traversal 26 | */ 27 | 28 | //////////////// LISTS /////////////////////////////////// 29 | 30 | // Store lists of objects 31 | // Duplicates are allowed 32 | // Objects remain in order 33 | // Elements are indexed via an integer 34 | // cf. shopping list 35 | // Checking for particular item in list is slow 36 | // Looking an item up by index is fast 37 | // Iterating through lists is relatively fast 38 | // Note: you can sort lists if you want to. 39 | 40 | // If you only add or remove items at end of list, use ArrayList. 41 | List list1 = new ArrayList(); 42 | 43 | // Removing or adding items elsewhere in the list? 44 | List list2 = new LinkedList(); 45 | 46 | ////////////////SETS /////////////////////////////////// 47 | 48 | // Only store unique values 49 | // Great for removing duplicates 50 | // Not indexed, unlike lists 51 | // Very fast to check if a particular object exists 52 | // If you want to use your own objects, you must implement hashCode() and equals(). 53 | 54 | // Order is unimportant and OK if it changes? 55 | // HashSet is not ordered. 56 | Set set1 = new HashSet(); 57 | 58 | // Sorted in natural order? Use TreeSet - must implement Comparable for custom types 59 | // (1,2,3 ..., a,b,c.... etc) 60 | Set set2 = new TreeSet(); 61 | 62 | // Elements remain in order they were added 63 | Set set3 = new LinkedHashSet(); 64 | 65 | ////////////////MAPS /////////////////////////////////// 66 | 67 | // Key value pairs. 68 | // Like lookup tables 69 | // Retrieving a value by key is fast 70 | // Iterating over map values is very slow 71 | // Maps not really optimised for iteration 72 | // If you want to use your own objects as keys, you must implement hashCode() and equals(). 73 | 74 | // Keys not in any particular order, and order liable to change. 75 | Map map1 = new HashMap(); 76 | 77 | // Keys sorted in natural order - must implement Comparable for custom types 78 | Map map2 = new TreeMap(); 79 | 80 | // Keys remain in order added 81 | Map map3 = new LinkedHashMap(); 82 | 83 | // There are also the SortedSet and SortedMap interfaces. 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /63 - Complex Data Structures/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.LinkedHashSet; 3 | import java.util.Map; 4 | import java.util.Set; 5 | 6 | public class App { 7 | 8 | public static String[] vehicles = { "ambulance", "helicopter", "lifeboat" }; 9 | 10 | public static String[][] drivers = { 11 | { "Fred", "Sue", "Pete" }, 12 | { "Sue", "Richard", "Bob", "Fred" }, 13 | { "Pete", "Mary", "Bob" }, }; 14 | 15 | public static void main(String[] args) { 16 | 17 | Map> personnel = new HashMap>(); 18 | 19 | for (int i = 0; i < vehicles.length; i++) { 20 | String vehicle = vehicles[i]; 21 | String[] driversList = drivers[i]; 22 | 23 | Set driverSet = new LinkedHashSet(); 24 | 25 | for (String driver : driversList) { 26 | driverSet.add(driver); 27 | } 28 | 29 | personnel.put(vehicle, driverSet); 30 | } 31 | 32 | { // Brackets just to scope driversList variable so can use again later 33 | // Example usage 34 | Set driversList = personnel.get("helicopter"); 35 | 36 | for (String driver : driversList) { 37 | System.out.println(driver); 38 | } 39 | } 40 | 41 | // Iterate through whole thing 42 | for (String vehicle : personnel.keySet()) { 43 | System.out.print(vehicle); 44 | System.out.print(": "); 45 | Set driversList = personnel.get(vehicle); 46 | 47 | for (String driver : driversList) { 48 | System.out.print(driver); 49 | System.out.print(" "); 50 | } 51 | 52 | System.out.println(); 53 | } 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Source code for Java for Complete Beginners. 2 | 3 | You can find more courses at courses.caveofprogramming.com. 4 | 5 | --------------------------------------------------------------------------------