From 88793d445e40371ff25aa1716f2692ab4ccf6345 Mon Sep 17 00:00:00 2001 From: bayarbuyan Date: Thu, 8 Sep 2016 22:25:48 +0200 Subject: [PATCH 01/32] IfPresent takes Consumer --- streams/AboutOptional.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/streams/AboutOptional.java b/streams/AboutOptional.java index 623d041..db67a1f 100644 --- a/streams/AboutOptional.java +++ b/streams/AboutOptional.java @@ -61,14 +61,14 @@ public static void main(String[] args) { Optional obj1 = (value== null) ? Optional.empty(): Optional.of(value); Optional obj2 = Optional.ofNullable(value); - System.out.println(Optional.of(null)); // throws NullPointerException +// System.out.println(Optional.of(null)); // throws NullPointerException System.out.println(Optional.ofNullable(null)); // Optional.empty System.out.println(findAverage(10, 30)); // Optional[20.0] System.out.println(findAverage()); // Optional.empty Double avg1 = findAverage(10, 20).get(); // 20.0 - Double avg2 = findAverage().get(); // throws NoSuchElementException + //Double avg2 = findAverage().get(); // throws NoSuchElementException Double avg3 = findAverage().orElse(Double.NaN); // to avoid this exception thrown // boolean isPresent() @@ -80,6 +80,10 @@ public static void main(String[] args) { // void ifPresent(Consumer) // It runs Consumer logic if value is present, otherwise won't run emptyOptional.ifPresent(System.out::println); // no output + + Optional add = Optional.of(2); + System.out.println(add); // Optional[2] + add.ifPresent(System.out::println); // 2 System.out.println(emptyOptional.orElse(null)); // null System.out.println(emptyOptional.orElse(Double.NaN)); // Nan From 61fe248e66dc5dc80b22f758ca0728cbb84bec47 Mon Sep 17 00:00:00 2001 From: bayarbuyan Date: Mon, 12 Sep 2016 18:28:52 +0200 Subject: [PATCH 02/32] Renamed conflicting class name --- classes/nested/StaticNestedClassExample.java | 23 +++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/classes/nested/StaticNestedClassExample.java b/classes/nested/StaticNestedClassExample.java index 459719b..73151c4 100644 --- a/classes/nested/StaticNestedClassExample.java +++ b/classes/nested/StaticNestedClassExample.java @@ -12,23 +12,23 @@ * can have any access modifier like inner class * outer class can directly access to its static members, but to its instance members only through its instance */ -class OuterClass { +class OuterClassEx{ private static String args = " args"; private String mainGot = " main got "; protected static class StaticNestedClass { - protected OuterClass outerObj; + protected OuterClassEx outerObj; static StaticNestedClass nestedObj; public static void main(String... args) { StaticNestedClass me = new StaticNestedClass(); - me.outerObj = new OuterClass(); - System.out.println("Static nested class's" + me.outerObj.mainGot + args.length + OuterClass.args); + me.outerObj = new OuterClassEx(); + System.out.println("Static nested class's" + me.outerObj.mainGot + args.length + OuterClassEx.args); me.sayMyName(); } void sayMyName(){ - System.out.println("I received arguments through " + new OuterClass().mainGot); + System.out.println("I received arguments through " + new OuterClassEx().mainGot); } } @@ -39,12 +39,19 @@ public StaticNestedClass getStaticNestedObj(){ } public class StaticNestedClassExample { + static class Testing{ + } + + void tester(){ + Testing tt = new Testing(); + } + public static void main(String[] args) { - OuterClass.StaticNestedClass staticNestedObj = new OuterClass.StaticNestedClass(); + OuterClassEx.StaticNestedClass staticNestedObj = new OuterClassEx.StaticNestedClass(); staticNestedObj.main(args); // Static nested class's main got X args - OuterClass outerObj = new OuterClass(); - OuterClass.StaticNestedClass nestedObj = outerObj.getStaticNestedObj(); + OuterClassEx outerObj = new OuterClassEx(); + OuterClassEx.StaticNestedClass nestedObj = outerObj.getStaticNestedObj(); System.out.println(nestedObj == null); // true outerObj.getStaticNestedObj().main(args); // Static nested class's main got X args From c45bfd2baa6d9fdbfc2e48a2b0f10044f27fb76b Mon Sep 17 00:00:00 2001 From: bayarbuyan Date: Tue, 13 Sep 2016 23:16:26 +0200 Subject: [PATCH 03/32] Corrected README of lambda part --- lambdas/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lambdas/README.md b/lambdas/README.md index 546334f..08b2ec8 100644 --- a/lambdas/README.md +++ b/lambdas/README.md @@ -8,13 +8,12 @@ Lambda expression can access to static and instance variables, and local variabl Method reference --- -New feature in Java 8 which makes lambda expression even easier to write. Basically, it is a short syntax containing no parameter declaration or implementation logic which are inferred by compiler. The implementation is defined in somewhere else, so it promotes reusability of code. +New feature in Java 8 which makes a lambda expression even easier to write. Basically, it is a short syntax containing no parameter declaration or implementation logic which is inferred by compiler. The implementation is defined in somewhere else, so it promotes re-usability of code. Functional interface --- -Functional interface is an interface that has one abstract method. Below is commonly used built-in functional -interfaces introduced in Java 8. +Functional interface is an interface that has only one abstract method while it can have any number of static or default methods. Below is commonly used functional interfaces built-in in Java 8. Interface | Returns | Method | Argument | Primitive Specialization From ec4e72fb693cab066647eac707665777978e1185 Mon Sep 17 00:00:00 2001 From: bayarbuyan Date: Sun, 18 Sep 2016 23:53:58 +0200 Subject: [PATCH 04/32] Enum note updated --- enums/AboutEnum.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/enums/AboutEnum.java b/enums/AboutEnum.java index b93be32..89949bc 100644 --- a/enums/AboutEnum.java +++ b/enums/AboutEnum.java @@ -1,8 +1,7 @@ package enums; /** - * - * - Java Enum + * - Java enum * implicitly inherits java.lang.Enum class * JVM converts it to class. Its elements are instance of the enumeration class. * It is public(or default) static final. So can't be extended @@ -12,10 +11,10 @@ * Its constructor can be only private. Making it protected or public lead compilation error * * - Enum methods: - * values(): returns array of all elements - * valueOf(String str) : parses String and converts to Enum element - * name() : returns name of element in String - * ordinal() : returns index of element + * values(): returns an array of all elements + * valueOf(String str) : parses String and converts to Enum element, case-sensitive + * name() : returns a name of element in String + * ordinal() : returns an index of element */ enum Planet { @@ -25,7 +24,10 @@ enum Planet { } enum Season { - Summer, Autumn, Winter { void printWeather() { System.out.println("cold");}}, Spring; + Summer, + Autumn, + Winter { void printWeather() { System.out.println("cold");} }, + Spring; // semicolon is mandatory here void printWeather() { System.out.println("mild"); } } @@ -72,7 +74,7 @@ public static void main(String[] args) { switch(devOne){ case Manager : System.out.println("manager"); case 1: System.out.println("1"); // DOES NOT COMPILE, type mismatch - case JobPosition.CTO : System.out.println("cto"); // DOES NOT COMPILE + case JobPosition.CTO : System.out.println("cto"); // DOES NOT COMPILE, only constant name allowed without qualified name } } } From 3d2b261e067aafe3fe3d117ebb6a3080cb55201f Mon Sep 17 00:00:00 2001 From: ubbn Date: Thu, 22 Feb 2018 16:59:28 +0100 Subject: [PATCH 05/32] Update in Array note --- collections/AboutArray.java | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/collections/AboutArray.java b/collections/AboutArray.java index 76aa4c8..6195fa2 100644 --- a/collections/AboutArray.java +++ b/collections/AboutArray.java @@ -28,6 +28,7 @@ public static void main(String[] args) { int[][] b2 = new int[5][]; int[][] b3 = new int[][]; // DOES NOT COMPILE int[][] b4 = new int[][5]; // DOES NOT COMPILE + int[][] c0[] = new int[5][][]; int[][] c1[] = new int[5][5][]; int[][] c2[] = new int[][][5]; // DOES NOT COMPILE int[][] c3[] = new int[5][][5]; // DOES NOT COMPILE @@ -50,21 +51,21 @@ public static void main(String[] args) { anotherStrings[0] = new StringBuilder(); // DOES NOT COMPILE, StringBuilder to String objects[0] = new StringBuilder(); // Runtime exception, StringBuilder to String - - // Sort and search in array + // Sort Array int numbers[] = {2, 4, 6, 8}; - Arrays.sort(a1); + Arrays.sort(numbers); // sorts given array and returns void - // binarySearch assumes array is already sorted in ascending order + // Search in Array + // binarySearch works by assuming array is already sorted in ascending order // static int binarySearch(List, T) // static int binarySearch(List, T, Comparator) // if found, return existing index - // if not found, return negative sorted position where searched value's can fit - // if list is not ascending ordered, return value is undefined - System.out.println(Arrays.binarySearch(numbers, 2)); // 0 - System.out.println(Arrays.binarySearch(numbers, 4)); // 1 - System.out.println(Arrays.binarySearch(numbers, 1)); // -1 - System.out.println(Arrays.binarySearch(numbers, 3)); // -2 - System.out.println(Arrays.binarySearch(numbers, 10)); // -5 + // if not found, return negative sorted position(not index) where searched value would fit + // if not ordered ascendingly, returned value is unpredictable + System.out.println(Arrays.binarySearch(numbers, 2)); // 0, found at 0 + System.out.println(Arrays.binarySearch(numbers, 4)); // 1, found at 1 + System.out.println(Arrays.binarySearch(numbers, 1)); // -1, not found, potential position 1 + System.out.println(Arrays.binarySearch(numbers, 3)); // -2, not found, potential position 2 + System.out.println(Arrays.binarySearch(numbers, 9)); // -5, not found, potential position 5 } } From c9f0b8f741a06f87780609f7b3e1960e2000fc5b Mon Sep 17 00:00:00 2001 From: tugul Date: Sat, 21 Apr 2018 08:41:39 +0200 Subject: [PATCH 06/32] Updated vararg Readme --- varargs/ReadMe.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/varargs/ReadMe.md b/varargs/ReadMe.md index b33e3c6..86bf26d 100644 --- a/varargs/ReadMe.md +++ b/varargs/ReadMe.md @@ -1,3 +1,4 @@ -The characters ... are called varargs (variable argument lists). It is a little different than an array, though. -A vararg parameter must be the last element in parameter list. -Only one vararg parameter allowed per method. +### Varargs +The characters ... are called **varargs** (variable argument lists). It is a little different than an array, though. Quick facts: +- A vararg parameter in method must be the last element in parameter list. +- Only one vararg parameter allowed per method. From 2f9fcce35795516323d47519c7b61752968b54a8 Mon Sep 17 00:00:00 2001 From: tugul Date: Sat, 21 Apr 2018 09:59:00 +0200 Subject: [PATCH 07/32] Index used in varargs --- varargs/AccessVararg.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/varargs/AccessVararg.java b/varargs/AccessVararg.java index 31053af..49f9bab 100644 --- a/varargs/AccessVararg.java +++ b/varargs/AccessVararg.java @@ -1,15 +1,14 @@ package varargs; /** - * Accessing to varargs, same like array index + * Like an array, accessing to varargs goes with index */ public class AccessVararg { - public static void doIt(int ... nums){ + static void doIt(int ... nums){ System.out.println(nums[1]); } public static void main(String[] args) { - // Prints 5 - doIt(4,5,6); + doIt(4,5,6); // Prints 5 } } From a1fe3deb835eac77624b5dac115f89a8abd89166 Mon Sep 17 00:00:00 2001 From: tugul Date: Sat, 21 Apr 2018 16:55:42 +0200 Subject: [PATCH 08/32] Clarified vararg access --- varargs/AccessVararg.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/varargs/AccessVararg.java b/varargs/AccessVararg.java index 49f9bab..18d871d 100644 --- a/varargs/AccessVararg.java +++ b/varargs/AccessVararg.java @@ -1,14 +1,14 @@ package varargs; /** - * Like an array, accessing to varargs goes with index + * Like an array, varargs uses index */ public class AccessVararg { - static void doIt(int ... nums){ - System.out.println(nums[1]); + void printValue(int index, int ... numbers){ + System.out.println(numbers[index]); } public static void main(String[] args) { - doIt(4,5,6); // Prints 5 + new AccessVararg().printValue(1, 4, 5, 6); // Prints 5 which is at index 1 } } From b5e73c34ec7adc66162e1ab1bc0db36fbd2bc6b2 Mon Sep 17 00:00:00 2001 From: tugul Date: Sat, 21 Apr 2018 17:08:20 +0200 Subject: [PATCH 09/32] Vararg & array give same signature --- varargs/SimpleUsage.java | 8 ++++---- varargs/StringArgsInMain.java | 6 +++--- varargs/VarargVsArray.java | 11 ++++++----- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/varargs/SimpleUsage.java b/varargs/SimpleUsage.java index a8f39fc..101495a 100644 --- a/varargs/SimpleUsage.java +++ b/varargs/SimpleUsage.java @@ -2,8 +2,8 @@ /** * Vararg example - * Must be only one in parameter list - * Must be only last one + * - Must be once in parameter list + * - Must be the last one */ public class SimpleUsage { @@ -11,9 +11,9 @@ public void walk1(int... nums) { } public void walk2(int start, int... nums) { } // DOES NOT COMPILE - //public void walk3(int... nums, int start) { } + public void walk3(int... nums, int start) { } // DOES NOT COMPILE - //public void walk4(int... start, int... nums) { } + public void walk4(int... start, int... nums) { } } diff --git a/varargs/StringArgsInMain.java b/varargs/StringArgsInMain.java index 94ea48f..807b4b0 100644 --- a/varargs/StringArgsInMain.java +++ b/varargs/StringArgsInMain.java @@ -1,15 +1,15 @@ package varargs; /** - * args contains only user given arguments - * not class name or any java commands + * varargs to main method contains only user given arguments + * neither class name nor any options */ public class StringArgsInMain { public static void main(String... args) { System.out.println(args.length); for (int i = 0; i < args.length; i++) { - System.out.println(0 + " - " + args[i]); + System.out.println(i + " - " + args[i]); } } } diff --git a/varargs/VarargVsArray.java b/varargs/VarargVsArray.java index 7350d0a..7b594d5 100644 --- a/varargs/VarargVsArray.java +++ b/varargs/VarargVsArray.java @@ -1,18 +1,19 @@ package varargs; /** - * Although Java treats varargs as array, there is a small difference when calling: + * Although Java treats varargs as array, there is a small difference when calling */ public class VarargVsArray { - // Both method can't compiled together + // Both can't be compiled together + // compiler sees they have same signature static void fly(int[] params){ } static void fly(int... params){ } public static void main(String[] args) { - // calls Vararg + // calls only one with Vararg fly(1, 2, 3); - // can call both - fly(new int[] {1, 2, 2}); + // can call any of above two + fly(new int[] {1, 2, 3}); } } From 1decfe46ee7e8696e79fe934987d4e1c0b07df09 Mon Sep 17 00:00:00 2001 From: tugul Date: Sun, 22 Apr 2018 17:05:36 +0200 Subject: [PATCH 10/32] StringBuilder has capacity different than size --- strings/StringBuilderCapacity.java | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/strings/StringBuilderCapacity.java b/strings/StringBuilderCapacity.java index 7c7ed4e..fe1f65b 100644 --- a/strings/StringBuilderCapacity.java +++ b/strings/StringBuilderCapacity.java @@ -1,34 +1,36 @@ package strings; /** - * - StringBuilderCapacity is mutable while String is immutable - * - Capacity/size are same for String, but they can be different in StringBuilderCapacity object - * - Unless capacity is given, StringBuilder create object with capacity of 16 empty elements (plus given string param) + * Quick facts: + * - StringBuilder is mutable while String is immutable + * - Capacity/size are same for String, but they can be different in StringBuilder object + * - Unless capacity is given, StringBuilder create object with capacity of 16 empty elements (plus string size if string param is given) + * - String, StringBuilder both have length() method */ public class StringBuilderCapacity { public static void main(String[] args) { StringBuilder a = new StringBuilder("abc"); // 16 + 3 StringBuilder b = new StringBuilder(50); // 50 StringBuilder c = new StringBuilder(); // 16 - a.append("defg"); + a.append("def"); System.out.println(a); - System.out.println("Length: " + a.length()); // abcdefg = 7 - System.out.println("Capacity a: " + a.capacity()); // default(16) abc(3) = 19 + System.out.println("Capacity a: " + a.capacity()); // default(16) + abc(3) = 19 + System.out.println("Length a: " + a.length()); // abcdefg = 6 System.out.println("Capacity b: " + b.capacity()); // given size 50 - System.out.println("Capacity c: " + c.capacity()); // default(16) empty = 16 - - // String, StringBuilder both have length() method + System.out.println("Length b: " + b.length()); // empty content + System.out.println("Capacity c: " + c.capacity()); // default is 16, empty means capacity is 16 + System.out.println("Length c: " + c.length()); // empty content /* Below is output - abcdefg - Length: 7 Capacity a: 19 + Length a: 6 Capacity b: 50 + Length b: 0 Capacity c: 16 + Length c: 0 */ } - } From a10ccf65bf5002037b1795147d3614d2d2ee78aa Mon Sep 17 00:00:00 2001 From: tugul Date: Sun, 22 Apr 2018 17:18:31 +0200 Subject: [PATCH 11/32] Method chain works both String/StringBuilder --- strings/StringVsStringBuilder.java | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/strings/StringVsStringBuilder.java b/strings/StringVsStringBuilder.java index ac5c8e1..ff14890 100644 --- a/strings/StringVsStringBuilder.java +++ b/strings/StringVsStringBuilder.java @@ -7,29 +7,36 @@ */ public class StringVsStringBuilder { public static void main(String[] args) { - // 1. + ///////////////////////////////////////////// + // Difference 1: + ///////////////////////////////////////////// + // Immutable class, create 27 new objects, garbage collector works busy to clean them - // Mutable class, create only 1 object String str = ""; for (char c='a'; c <= 'z'; c++) str += c; + // Mutable class, create only 1 object StringBuilder sb = new StringBuilder(); for (char c='a'; c <= 'z'; c++) sb.append(c); - // 2. + ///////////////////////////////////////////// + // Difference 2: + ///////////////////////////////////////////// + // Immutable class method(i.e. concat) returns reference of newly concatenated - // while Mutable class method(i.e. append) returns reference of the same object changed String a = "ab"; a = a.concat("cd"); // abcd + // while Mutable class method(i.e. append) returns reference of the same object changed StringBuilder b = new StringBuilder("ab"); b.append("cd"); // abcd - b.append(true); - b.append(5); - b.append((String)null); - b.append((StringBuilder)null); + b.append(true); // abcdtrue + b.append(5); // abcdtrue5 + b.append((String)null); // requires explicit cast + b.append((StringBuilder)null); // requires explicit cast + // RESULT: abcdtrue5nullnull // Similarity is method chaining which can be done on both String st = " abc ".trim().toUpperCase().concat("D").substring(2); // CD From c570309f1e1d325bc7a37d8878cc5fecec6fcffa Mon Sep 17 00:00:00 2001 From: tugul Date: Sun, 22 Apr 2018 19:25:06 +0200 Subject: [PATCH 12/32] substring's end-index is exclusive --- strings/StringMethods.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/strings/StringMethods.java b/strings/StringMethods.java index 00456ba..52ecd43 100644 --- a/strings/StringMethods.java +++ b/strings/StringMethods.java @@ -2,21 +2,21 @@ /** * - * String substring(int start) - * String substring(int start, int end) - startindex is inclusive, endindex is exclusive + * String substring(int startIndex) + * String substring(int startIndex, int endIndex) * */ public class StringMethods { public static void main(String[] args) { - // substring // startIndex is always inclusive - // substring(int start) -> inclusive start index till end - // substring(int start, int end) -> inclusive start till exclusive end + // 1. substring(int startIndex) -> inclusive start index till end + // 2. substring(int startIndex, int endIndex) -> inclusive start till exclusive end String s = "hmm"; System.out.println(s.substring(1, 2)); // prints just 'm' System.out.println(s.substring(1)); // prints 'mm' System.out.println(s.substring(1, 3)); // prints 'mm' + System.out.println(s.substring(2, 1)); // Runtime exception : StringIndexOutOfBoundsException System.out.println(s.substring(1, 4)); // Runtime exception : StringIndexOutOfBoundsException // PS: substring on StringBuilder returns String, not StringBuilder object From 874832d750bde909af54892758b1c2bce6da2249 Mon Sep 17 00:00:00 2001 From: tugul Date: Sun, 22 Apr 2018 23:13:40 +0200 Subject: [PATCH 13/32] Method sign: param types and order --- methods/MethodOverload.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/methods/MethodOverload.java b/methods/MethodOverload.java index 3c7964c..cb2a8f3 100644 --- a/methods/MethodOverload.java +++ b/methods/MethodOverload.java @@ -9,7 +9,8 @@ * But return type, access modifier, optional specifier or exception list are irrelevant * * - In case of autoboxing - * Java call most specifically matching method. If can't find, it looks for next ONE level closer one + * Java calls most specifically matched one from overloaded methods + * If can't find, it looks for next one(only ONE level upper) * Generally, it follows below one of below step to match parameter: * : Exact match by parameter type * : Match with superclass type @@ -40,9 +41,11 @@ void jump(int ... meter) {} // DOES NOT COMPILE, both accepts single int array public static void main(String[] args) { fly(2); // 10 (int miles) + fly((byte)2); // 10 (int miles) byte --> int (larger primitive type) fly(new Integer(1)); // 30 (Integer miles) fly(2L); // 100 (Long miles) long --> Long fly(2f); // 600 (Number miles) float --> Float (extends Number) + fly(2.); // 600 (Number miles) double --> Double (extends Number) fly("2"); // 900 (Object miles) String --> Object fly(true); // 900 (Object miles) boolean --> Boolean (extends Object) fly(new int[]{}); // 900 (Object miles) Array --> Object From 6a35e6012718e5dad88d56081a1b794bd5876a9d Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 12:42:38 +0200 Subject: [PATCH 14/32] Fix: private method can't be overriden --- methods/MethodOverride.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/methods/MethodOverride.java b/methods/MethodOverride.java index bd67eaf..a1fe9c3 100644 --- a/methods/MethodOverride.java +++ b/methods/MethodOverride.java @@ -42,11 +42,12 @@ void instanceMethod() { System.out.println("Instance method in B"); } + // It is overriding void anotherInstanceMethod() { staticMethod(); } - // It is overriding + // Not override private method. so it is a new method int getIntValue(){ return 1; } @@ -60,11 +61,13 @@ public static void main(String[] args) { new B().instanceMethod(); // Instance method in B new B().staticMethod(); // Static method in B - System.out.println(new B().getIntValue()); // 1 new A().instanceMethod(); // Instance method in A new A().staticMethod(); // Static method in A + + System.out.println(new B().getIntValue()); // 1 //System.out.println(new A().getIntValue()); // DOES NOT COMPILE, inaccessible as it is private + //System.out.println(a.getIntValue()); // DOES NOT COMPILE, inaccessible as it is private System.out.println(); From 9cb0798ee2a42981ea5586a5eec51505ba7b9a40 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 14:38:50 +0200 Subject: [PATCH 15/32] Static method called on interface only --- interfaces/ConflictingMethods.java | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/interfaces/ConflictingMethods.java b/interfaces/ConflictingMethods.java index 7d65ade..0bf99c2 100644 --- a/interfaces/ConflictingMethods.java +++ b/interfaces/ConflictingMethods.java @@ -36,10 +36,10 @@ interface IDo { static int goFor() { return 0; } } -interface IGoDo1 extends IGo, IDo { - // DOES NOT COMPILE, default methods conflict - // static methods don't conflict -} +// interface IGoDo1 extends IGo, IDo { +// // DOES NOT COMPILE, default methods conflict +// // static methods don't conflict +// } interface IGoDo2 extends IGo, IDo { // Resolution is to override conflicting default method @@ -50,14 +50,17 @@ public class ConflictingMethods { public static void main(String[] args) { IMe aa = new Lost(); Lost ab = new Lost(); - IMe.me(); - ab.me(); + + aa.me(); // DOES NOT COMPILE, static method must be called on interface only + IMe.me(); // IME + ((Lost)aa).me(); // I am lost + ab.me(); // I am lost - Wondering.me(); - new Wondering().me(); - IMe x = new Wondering(); - ((Wondering)x).me(); - x.me(); // DOES NOT COMPILE + Wondering.me(); // I am wondering... + new Wondering().me(); // I am wondering... + IMe x = new Wondering(); + ((Wondering)x).me(); // I am wondering... + //x.me(); // DOES NOT COMPILE //aa.me(); } } From e2aedf83a3fb0781fd1d7975b9b361ab40c16c96 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 15:14:11 +0200 Subject: [PATCH 16/32] ReadMe update --- lambdas/README.md | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/lambdas/README.md b/lambdas/README.md index 08b2ec8..ec2a604 100644 --- a/lambdas/README.md +++ b/lambdas/README.md @@ -1,30 +1,31 @@ Lambda expression --- -One of the core features introduced in Java 8 to facilitate functional programming. It provides clear and succinct way to express one method aka functional interface using an expression. It also enhances use of Collection API making it simpler to iterate, filter and process data from collection. Its syntax is as below:
+It is one of the core features introduced in Java 8 to facilitate functional programming. It provides clear and succinct way to express one method interface (aka ***functional interface***) using an expression. It also enhances use of **Collection** API making it simpler to iterate, filter and process data from collection. Its syntax is as below:
+ ```parameter -> expression body``` -Lambda expression can access to static and instance variables, and local variables if they are explicitly final or effectively final (albeit not declared final, value is assigned only once in its scope) +Lambda expression can access to static and instance variables, as well as local variables if they are explicitly final or **effectively final** which means albeit not explicitly declared ```final```, its value is assigned only once in its scope. Method reference --- -New feature in Java 8 which makes a lambda expression even easier to write. Basically, it is a short syntax containing no parameter declaration or implementation logic which is inferred by compiler. The implementation is defined in somewhere else, so it promotes re-usability of code. +New feature in Java 8 which makes a lambda expression even easier to write. Basically, it is a short syntax containing no parameter declaration or implementation logic which is inferred by compiler. The implementation is defined in somewhere else, therefore it promotes re-usability of code. Functional interface --- -Functional interface is an interface that has only one abstract method while it can have any number of static or default methods. Below is commonly used functional interfaces built-in in Java 8. +Functional interface is an interface that has **only one abstract method** while it can have any number of static or default methods. Belows are commonly used functional interfaces built-in in Java 8. Interface | Returns | Method | Argument | Primitive Specialization --- | --- | --- | --- | --- -Supplier\ | T | get | . | BooleanSupplier, IntSupplier, LongSupplier, DoubleSupplier -Consumer\ | void | accept | T t | IntConsumer, LongConsumer, DoubleConsumer -BiConsumer\ | void | accept | T t, P p | -Predicate\ | boolean | test | T t | IntPredicate, LongPredicate, DoublePredicate -BiPredicate\ | boolean | test |T t, P p | -Function\ | R | apply |T t | IntFunction, IntToDoubleFunction, IntToLongFunction, LongFunction, LongToDoubleFunction, LongToIntFunction, DoubleFunction, ToIntFunction, ToDoubleFunction, ToLongFunction -BiFunction\ | R | apply | T t, P p | ToDoubleBiFunction, ToIntBiFunction, ToLongBiFunction -UnaryOperator\ | T | apply | T t | IntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator -BinaryOperator\ | T | apply | T t1, T t2 | IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator +```Supplier``` | T | get | . | ```BooleanSupplier```, ```IntSupplier```, ```LongSupplier```, ```DoubleSupplier``` +```Consumer``` | void | accept | T t | ```IntConsumer```, ```LongConsumer```, ```DoubleConsumer``` +```BiConsumer``` | void | accept | T t, P p | +```Predicate``` | boolean | test | T t | ```IntPredicate```, ```LongPredicate```, ```DoublePredicate``` +```BiPredicate``` | boolean | test |T t, P p | +```Function``` | R | apply |T t | ```IntFunction```, ```IntToDoubleFunction```, ```IntToLongFunction```, ```LongFunction```, ```LongToDoubleFunction LongToIntFunction```, ```DoubleFunction```, ```ToIntFunction```, ```ToDoubleFunction```, ```ToLongFunction``` +```BiFunction``` | R | apply | T t, P p | ```ToDoubleBiFunction```, ```ToIntBiFunction```, ```ToLongBiFunction``` +```UnaryOperator``` | T | apply | T t | ```IntUnaryOperator```, ```LongUnaryOperator```, ```DoubleUnaryOperator``` +```BinaryOperator``` | T | apply | T t1, T t2 | ```IntBinaryOperator```, ```LongBinaryOperator```, ```DoubleBinaryOperator``` From 9244699350c6c363ccd43d156bf61cbd357580a1 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 15:45:08 +0200 Subject: [PATCH 17/32] Single abstract method in fuctional interface --- lambdas/README.md | 2 +- lambdas/{Simple.java => SimpleLambda.java} | 32 ++++++++++++---------- 2 files changed, 19 insertions(+), 15 deletions(-) rename lambdas/{Simple.java => SimpleLambda.java} (55%) diff --git a/lambdas/README.md b/lambdas/README.md index ec2a604..fb677bf 100644 --- a/lambdas/README.md +++ b/lambdas/README.md @@ -14,7 +14,7 @@ New feature in Java 8 which makes a lambda expression even easier to write. Basi Functional interface --- -Functional interface is an interface that has **only one abstract method** while it can have any number of static or default methods. Belows are commonly used functional interfaces built-in in Java 8. +Functional interface is an interface that has **only one abstract method** while it can have any number of static or default methods. This single abstract method is called a **functional method**. Belows are commonly used functional interfaces built-in in Java 8. Interface | Returns | Method | Argument | Primitive Specialization diff --git a/lambdas/Simple.java b/lambdas/SimpleLambda.java similarity index 55% rename from lambdas/Simple.java rename to lambdas/SimpleLambda.java index 018af20..da179c9 100644 --- a/lambdas/Simple.java +++ b/lambdas/SimpleLambda.java @@ -10,27 +10,31 @@ interface Climb { boolean isTooHigh(int a, int b); } -public class Simple { - int value = 10; + +class Simple { + int value = 18; + + static void test(Simple s, Predicate predicate){ + if (predicate.test(s)) + System.out.println("Suits"); + else + System.out.println("Not"); + } +} + +public class SimpleLambda { public static void main(String[] args) { - check((h, p) -> h > p, 40); // Too high - check((h, p) -> h > 15, 10); // Ok + check((x, y) -> x > y, 7); // Too high (7 > 5) + check((x, y) -> x > 9, 7); // Ok (7 > 9) - test(new Simple(), simple -> simple.value > 20); // Not + Simple.test(new Simple(), s -> s.value > 10); // Suits + Simple.test(new Simple(), s -> s.value > 20); // Not } static void check(Climb climb, int c){ - if (climb.isTooHigh(c, 20)) + if (climb.isTooHigh(c, 5)) System.out.println("Too high"); else System.out.println("Ok"); } - - static void test(Simple s, Predicate predicate) - { - if (predicate.test(s)) - System.out.println("Suits"); - else - System.out.println("Not"); - } } From 2122cf90f2623c38272516e8ba56f1b7c5990ff3 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 19:01:12 +0200 Subject: [PATCH 18/32] Method refernce easifies lambda expression --- lambdas/MethodReference.java | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/lambdas/MethodReference.java b/lambdas/MethodReference.java index 3c639b9..6bd7055 100644 --- a/lambdas/MethodReference.java +++ b/lambdas/MethodReference.java @@ -8,6 +8,7 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import java.util.function.BiPredicate; import java.util.function.Supplier; /** @@ -61,10 +62,11 @@ public MethodReference(Integer i, String str){ } public static String getStr() { return "no argument";} public static String getStr(Integer i){ return i + " is argument"; } + public static String getStr(String st){ return st + " is argument"; } public static void main(String[] args) { // 1. Calling static method - Consumer> lambdaExp1 = list -> Collections.sort(list); + Consumer> lambdaExp1 = list -> Collections.sort(list); Consumer> methodRef1 = Collections::sort; runConsumer(methodRef1); @@ -77,10 +79,12 @@ public static void main(String[] args) { // 3. Calling instance method on instance to be determined at runtime Predicate lambdaExp3 = str -> str.isEmpty(); Predicate methodRef3 = String::isEmpty; + //Predicate methodRef = str::isEmpty; // DOES NOT COMPILE, 1 argument is missing, make it BiPredicate to compile runPredicate(methodRef3); // true BiPredicate lambdaExp31 = (s, prefix) -> s.startsWith(prefix); BiPredicate methodRef31 = String::startsWith; + //BiPredicate methodRef31 = strObj::startsWith; DOES NOT COMPILE, two arguments are required // 4. Calling constructor Supplier lambdaExp4 = () -> new LinkedList(); @@ -88,14 +92,20 @@ public static void main(String[] args) { runSupplier(methodRef4); // [] runSupplier(HashMap::new); // {} + // Tricky here runConsumer(MethodReference::new); // calls MethodReference(List list) runFunc(MethodReference::new); // calls MethodReference(Integer i, String str) + // Those constructors return nothing and take parameters which are respectively same as below methods requiring + Consumer> c1 = MethodReference::new; + MyFunctionalInteface mfi = MethodReference::new; // Referring to overloaded methods - Supplier supplier = MethodReference::getStr; - Function function = MethodReference::getStr; + Supplier supplier = MethodReference::getStr; // calls one without parameter + Function function = MethodReference::getStr; // calls one with Integer parameter + Function functionS = MethodReference::getStr; // calls one with String parameter System.out.println(supplier.get()); // no argument System.out.println(function.apply(5)); // 5 is argument + System.out.println(functionS.apply("A")); // A is argument } } @@ -110,5 +120,6 @@ public static void main(String[] args) { [3, 1, 12, 5, 4] no argument 5 is argument +A is argument */ From c7ad2291f3c7cfda6e33e0d4010650d178120afb Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 19:23:07 +0200 Subject: [PATCH 19/32] Specifying type in generic method call is optional --- generics/GenericMethod.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/generics/GenericMethod.java b/generics/GenericMethod.java index 1a6ef71..cf8817d 100644 --- a/generics/GenericMethod.java +++ b/generics/GenericMethod.java @@ -7,7 +7,7 @@ /** * Generic types not declared in class must be declared in method declaration * - Multiple types can be allowed - * - Any letter allowed upper or lower + * - Any letter with upper or lowercase is allowed * - Generic type declared in class can not be used in static method or field * but of course, static method can define generic type in its own level */ @@ -21,6 +21,7 @@ public void genericMethod2(G g) {} public static void genericMethod3(G g) {} // DOES NOT COMPILE public static G garag; // DOES NOT COMPILE, generic type can't be used in static context + // Here static method defines own generic type which must be different than Class's generic types public static void fillMe(List list, Q value) { for (int i = 0; i < list.size(); i++) list.set(i, value); @@ -35,7 +36,7 @@ public static void main(String[] args) { for (Integer each : ints) System.out.println(each); - // Optional syntax for specifying types in generic method call + // Specifying types in generic method call is optional GenericMethod gm = new GenericMethod(); gm.checkStat("string"); gm.checkStat("string"); // specifying types on method call From 5faa362a7ecbb976ab6a8bbeab9c301f37063ec6 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 19:23:50 +0200 Subject: [PATCH 20/32] Instantiation of generic type is not allowed --- generics/GenericClass.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/generics/GenericClass.java b/generics/GenericClass.java index 8275d65..e8aac66 100644 --- a/generics/GenericClass.java +++ b/generics/GenericClass.java @@ -7,12 +7,12 @@ * The letters representing types must match literally when used! (regardless of inherited types) * * Limitations on generic types: - * - can't call constructor of generic type: new T() - * - can't create array of static type: new T[] + * - can't instantiate object with generic type: new T() + * - can't instantiate arrays with generic type: new T[] * - can't call instanceof: obj instanceof T * - can't use primitive as generic type, instead use their wrapper classes - * - can't create static variable with generic type - * - can't create static method with generic type defined in generic class definition + * - can't create STATIC variable with generic type + * - can't create STATIC method with generic type defined in generic class definition */ class GeneralWithTwo { From a0b596b713a4fe035401abcb812a9a9005dd2ca3 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 19:40:46 +0200 Subject: [PATCH 21/32] Generic type converted to Object type on compile time --- generics/GenericWildcard.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generics/GenericWildcard.java b/generics/GenericWildcard.java index e4bc377..2995ee5 100644 --- a/generics/GenericWildcard.java +++ b/generics/GenericWildcard.java @@ -7,7 +7,7 @@ /** * - Wildcard (?) * used to represent any type - * converted by JVM into Object type on compile time + * like generic type, it is converted by JVM into Object type on compile time * Collection with generic type ? can't be changed, but can be accessed * * - Note on its usage From aae5feabb8786e4a5ad1361148d065618cf6b9f1 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 23 Apr 2018 20:22:42 +0200 Subject: [PATCH 22/32] Stream tiedly works with Optional --- streams/AboutStream.java | 4 ++-- streams/README.md | 28 ++++++++++++++-------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/streams/AboutStream.java b/streams/AboutStream.java index 8cad32f..43942a2 100644 --- a/streams/AboutStream.java +++ b/streams/AboutStream.java @@ -78,7 +78,7 @@ public static void main(String[] args) { // in other words, it always creates new value on iterating each element // T reduce(T t, BinaryOperator operator) Stream letters = Stream.of("a", "b", "c"); - System.out.println(letters.reduce("ABC: ", (s1, s2) -> s1 + s2)); // "ABC: abc", using lambda + System.out.println(letters.reduce("ABC: ", (s1, s2) -> s1 + s2)); // "ABC: abc", using lambda System.out.println(Stream.of("a", "b", "c").reduce("ABC: ", String::concat)); // "ABC: abc", using method reference // Optional reduce(BinaryOperator accumulator) @@ -101,7 +101,7 @@ public static void main(String[] args) { System.out.println(sortedSet1 + " " + sortedSet2 + ", " + set); // [aia, bia, cia] [aia, bia, cia], [aia, cia, bia] // ---------------------------- - // 2. Intermediate operations, take stream/return stream + // 3. Intermediate operations, take stream/return stream // ---------------------------- // filter diff --git a/streams/README.md b/streams/README.md index 5a07d73..d823596 100644 --- a/streams/README.md +++ b/streams/README.md @@ -1,12 +1,12 @@ Stream --- -Java 8 Stream API is a big step towards functional programming and leverages multi-core processors which are ubiquitous nowadays. Stream represents a series of objects sourced from collection and support data processing queries, SQL like operations. +Java 8 Stream API is a big step towards functional programming and leverages multi-core processors which are ubiquitous nowadays. Stream represents a series of objects sourced from collection and supports data processing queries, SQL like operations. -There are generic interface **Stream\** and three specific interfaces for primitives, **DoubleStream**, **IntStream** and **LongStream** +There are generic interface ```Stream``` and three specific interfaces for primitives, ```DoubleStream```, ```IntStream``` and ```LongStream``` -Difference between **Stream\** and **IntStream** is that: -**IntStream** is for primitives (int, short, byte and char) -**Stream\** is for Integer wrapper class +Difference between ```Stream``` and ```IntStream``` is that: +```IntStream``` is for primitives (int, short, byte and char) +```Stream``` is for Integer wrapper class ![Image of Yaktocat](streams.png) @@ -14,19 +14,19 @@ Methods to convert between different Streams Source | To create Stream | To create DoubleStream | To create IntStream | To create LongStream --- | --- |--- |--- |--- -**Stream** | map | mapToDouble | mapToInt | mapToLong -**DoubleStream** | mapToObj | map | mapToInt | mapToLong -**IntStream** | mapToObj | mapToDouble | map | mapToLong -**LongStream** | mapToObj | mapToDouble | mapToInt | map +```Stream``` | map | mapToDouble | mapToInt | mapToLong +```DoubleStream``` | mapToObj | map | mapToInt | mapToLong +```IntStream``` | mapToObj | mapToDouble | map | mapToLong +```LongStream``` | mapToObj | mapToDouble | mapToInt | map -Those **map*** methods take a single parameter Function, respectively. +Those all ```map```* methods take a single parameter Function as shown below respectively. Source | To create Stream | To create DoubleStream | To create IntStream | To create LongStream --- | --- |--- |--- |--- -**Stream** | Function | ToDoubleFunction | ToIntFunction | ToLongFunction -**DoubleStream** | DoubleFunction | DoubleUnaryOperator | DoubleToIntFunction | DoubleToLongFunction -**IntStream** | IntFunction | IntToDoubleFunction | IntUnaryOperator | IntToLongFunction -**LongStream** | LongFunction | LongToDoubleFunction | LongToIntFunction | LongUnaryOperator +```Stream``` | Function | ToDoubleFunction | ToIntFunction | ToLongFunction +```DoubleStream``` | DoubleFunction | DoubleUnaryOperator | DoubleToIntFunction | DoubleToLongFunction +```IntStream``` | IntFunction | IntToDoubleFunction | IntUnaryOperator | IntToLongFunction +```LongStream``` | LongFunction | LongToDoubleFunction | LongToIntFunction | LongUnaryOperator Parallel stream --- From 19a3b9d212d97ad9cbc9a76c49464fd1af451c43 Mon Sep 17 00:00:00 2001 From: tugul Date: Tue, 24 Apr 2018 08:38:12 +0200 Subject: [PATCH 23/32] ReadMe update --- concurrency/README.md | 60 ++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/concurrency/README.md b/concurrency/README.md index bb51203..2dd7190 100644 --- a/concurrency/README.md +++ b/concurrency/README.md @@ -1,45 +1,47 @@ -Concurrency API (java.util.concurrent package) was initially introduced in Java 5 to ease threads management. Since then till Java 8, it has been enriched so much with many classes and framework. +## Concurrency in Java 8 +Concurrency API (```java.util.concurrent``` package) was initially introduced in Java 5 to ease threads management. Since then till Java 8, it has been enriched so much with many classes and frameworks. Below its major classes, interfaces and concepts are explained. -Runnable +```Runnable``` ---- -A functional interface used to define a work/task that thread will execute. It has functional method void run() with no argument. +A functional interface used to define a work/task that thread will execute. It has functional method ```void run()``` with no argument. -Callable +```Callable``` ---- -A functional interface used to define a work/task that thread will execute. It has functional method call() with no argument and returns generic type. Unlike Runnable, it can throw checked Exception. +A functional interface used to define a work/task that thread will execute. It has functional method ```T call()``` with no argument and returns generic type. Unlike ```Runnable```, it can throw checked exceptions. -ExecutorService +```ExecutorService``` ---- An interface with methods to take/execute tasks. It provides many useful features (thread pooling, scheduling etc.) -and extends functional interface Executor which has void execute(Runnable) method +and extends functional interface ```Executor``` which has ```void execute(Runnable)``` method -Future class +```Future``` ---- -It represents a result of an asynchronous task completion and has below methods: -
    -
  • T get() infinitely waits for the task to complete and returns value resulted once the task is finished
  • -
  • T get(long, TimeUnit) waits for the result only for specified time period and throws TimeOutException if didn't get
  • -
  • boolean cancel(boolean) attempts to cancel running task and returns boolean
  • -
  • boolean isCancelled() returns true if the task is cancelled before completed
  • -
  • boolean isDone() returns true if the task is completed
  • -
+This class represents a result of an asynchronous task completion and has below methods: + +- ```T get()``` infinitely waits for the task to complete and returns value resulted once the task is finished +- ```T get(long, TimeUnit)``` waits for the result only for specified time period and throws ```TimeOutException``` if didn't get +- ```boolean cancel(boolean)``` attempts to cancel running task and returns boolean +- ```boolean isCancelled()``` returns true if the task is cancelled before completed +- ```boolean isDone()``` returns true if the task is completed + Shutting down thread ---- -It is necessary to shut down the service instance(call shutdown()), otherwise application will hang. -Once it is requested to shutdown, executor rejects new task requests and throws RejectedExecutionException and -continues executing pending/ongoing tasks till completed. During this period, isShutdown() returns true and isTerminated() returns false. When ongoing tasks are completed, isShutdown() and isTerminated() methods return true and won't receive new tasks.
-shutDownNow() terminates all running/pending tasks and returns List which are not executed tasks.
-awaitTermination(long, TimeUnit) waits for specified period to complete ongoing tasks after shutdown request and returns true if executor terminated or false if timeout elapsed before termination. It doesn't do anything except for waiting. +- It is necessary to shut down the service instance(call ```shutdown()```), otherwise application will hang. +- Once it is requested to shutdown, executor rejects new task requests and throws ```RejectedExecutionException``` and +continues executing pending/ongoing tasks till completed. During this period, ```isShutdown()``` returns true and ```isTerminated()``` returns false. +- When ongoing tasks are completed, ```isShutdown()``` and ```isTerminated()``` methods return true and won't receive new tasks.
+- ```shutDownNow()``` terminates all running/pending tasks and returns ```List``` which are not executed tasks.
+- ```awaitTermination(long, TimeUnit)``` waits for specified period to complete ongoing tasks after shutdown request and returns true if executor terminated or false if timeout elapsed before termination. It doesn't do anything except for waiting. Scheduling tasks --- -ScheduledExecutorService is used to schedule a task to execute after delay or repeatedly with time interval. It extends ExecutorService interface, and its instance is taken from factory method in Executors helper class +```ScheduledExecutorService``` is used to schedule a task to execute after delay or repeatedly with time interval. It extends ```ExecutorService``` interface, and its instance is taken from factory method in ```Executors``` helper class Pause execution ---- -Thread.sleep(long) pauses current thread to suspend its execution for certain period and throws checked exception InterruptedException if interrupt request is received while pausing +```Thread.sleep(long)``` pauses current thread to suspend its execution for certain period and throws checked exception ```InterruptedException``` if interrupt request is received while pausing CyclicBarrier class --- @@ -60,17 +62,17 @@ Threading problems Synchronization --- -synchronized key word is used for in method declaration or around code block. +```synchronized``` key word is used for in method declaration or around code block. When method is declared as synchronized, lock is created on the whole object, might be less efficient. On the other hand, synchronized block uses an object to create a lock. Static synchronized method orders thread access across all instances rather than single instance.
Alternative to synchronized block or method, concurrent collections or atomic primitive classes can be used Atomic classes
-java.util.concurrent.atomic package provides atomic classes which supports atomic access to single values, such as primitive value or object reference. They can be ideally used in scenarios where multiple threads read/write single counter. Increment/decrement operators ++/-- are not thread-safe meaning that while one thread is updating and taking new value, other thread can update it meantime. With atomic nature, atomic classes have methods to perform increment/decrement as a single unit of operation without interference by other threads.
-AtomicBoolean, --
-AtomicInteger, AtomicIntegerArray
-AtomicLong, AtomicLongArray
-AtomicReference, AtomicReferenceArray
+```java.util.concurrent.atomic``` package provides atomic classes which supports atomic access to single values, such as primitive value or object reference. They can be ideally used in scenarios where multiple threads read/write single counter. Increment/decrement operators ++/-- are not thread-safe meaning that while one thread is updating and taking new value, other thread can update it meantime. With atomic nature, atomic classes have methods to perform increment/decrement as a single unit of operation without interference by other threads.
+```AtomicBoolean, -- ```
+```AtomicInteger, AtomicIntegerArray```
+```AtomicLong, AtomicLongArray```
+```AtomicReference, AtomicReferenceArray```
Concurrent collections
Concurrent collections provide performance enhancements that prevent unnecessary synchronizations. Read/write accesses to collection are synchronized so that data consistency is kept during multi-thread execution outside synchronized method or block. Go to concurrent collections. From 22996ac57794df7a0a35cc1c4ac42e9fa7d52e10 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 14 May 2018 16:45:32 +0200 Subject: [PATCH 24/32] Enum converted to class by compiler --- enums/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 enums/README.md diff --git a/enums/README.md b/enums/README.md new file mode 100644 index 0000000..ec8198c --- /dev/null +++ b/enums/README.md @@ -0,0 +1,27 @@ +# Enum +Simply imagine java enum is a class which has only limited number of pre-defined instances. Those instances are its elements and they are initialized when the enum type is first referenced, i.e. lazy initialization. + +If it has a single element, it means it is Singleton as there is only one instance. + +## Quick facts +- Uses reserved word ``enum`` on declaration +- Implicitly inherits ``java.lang.Enum`` class +- At compile time, it is converted to a class and JVM instantiates its elements +- It is **public** or default package, static final + +### Declaration +- Its elements are declared always **at first** +- Can have **any member** like class (field, constructor or method) +- Its constructor is **private** by default. Can't compile if protected or public + +### Inherited Methods +Every enum type has below inherited methods: + ``values()``: returns an array of all elements + ``valueOf(String str)`` : parses String and converts to Enum element, case-sensitive + ``name()`` : returns a name of element in String + ``ordinal()`` : returns an index of element + +## Main usages +- When there is need for variable which can have **a limited set of possible values**. +- **Type checking** at compile can help to avoid mismiatching values. +- It is **descriptive** as it explains itself what it is for and what are possible values From ce860abe7c1bd3ccf30669212707bd2115742911 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 4 Jun 2018 12:38:58 +0200 Subject: [PATCH 25/32] Main ReadMe update --- README.md | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e422f73..6b5e0a6 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,36 @@ -# Core Java -Many developers, including original contributors of the project, prefer to more practical use of new knowledge rather than reading it in a textual form. This project attempts to illustrate core Java concepts in self-explanatory simple code examples. It particularly emphasizes on explaining new features and changes introduced in Java 8. +# Core Java 8 +Many developers, including original contributors of this project, prefer to more practical use of new knowledge rather than reading it in a textual form. This project attempts to illustrate core Java concepts in self-explanatory simple code examples. It explains not only core APIs of Java, but also emphasizes on explaining new features and changes introduced in Java 8. + +# Java 8 features +Java 8 unveils many new features to its core APIs and brings many improvements in its existing core libraries. Below is a quick summary: + +## Functional programming +Functional interfaces, lambda expressions, method references and more. Read [more](https://github.com/tugul/CoreJava/tree/master/lambdas) + +## Stream API for Collections +``java.util.stream`` is newly introduced and it provides sequential or parallel operations on collections. Read [more](https://github.com/tugul/CoreJava/tree/master/streams) + +## Default and static method in interface +Interface can have non-abstract concrete method if they are **default** or **static**. Read [more](https://github.com/tugul/CoreJava/tree/master/interfaces) + +## NIO improvement +Non-blocking io API. Read [more](https://github.com/tugul/CoreJava/tree/master/nio2) + +## Date Time API +Working with dates in older java version was hard and often had to use external libraries. However, new API introduced many more features and provides easy of use: For example ``LocalDate``, ``LocalTime``, ``LocalDateTime``, ``ZonedDateTime``. Read [more](https://github.com/tugul/CoreJava/tree/master/datetimes) + +## Collection API improvement +New method ``forEach()`` and more . Read [more](https://github.com/tugul/CoreJava/tree/master/collections) + +## Concurrency API Improvement +Read [more](https://github.com/tugul/CoreJava/tree/master/concurrency) + +## Many more +Improvements on security, tools, deployment, networking, jdbc and many more. Refer to its official [announcement](http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html) # Contribution -Anyone who finds if there is missing or incorrect information in code examples is welcome to send pull requests. As we know, Rome wasn't built in a day. +Anyone who finds if there is missing or incorrect information in code examples is welcome to send pull requests. As we know +> Rome wasn't built in a day. # License This project can be used under MIT License. Read about the license From 945cb9724452774327efb529529dcee4262ee347 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 4 Jun 2018 12:51:00 +0200 Subject: [PATCH 26/32] java.nio.file package supports system independent resources --- nio2/PathCreation.java | 12 ++++++------ nio2/README.md | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/nio2/PathCreation.java b/nio2/PathCreation.java index 1314098..ba41a52 100644 --- a/nio2/PathCreation.java +++ b/nio2/PathCreation.java @@ -11,20 +11,20 @@ * - java.nio.file.Path * primary entry point of java.nio package * representation of path(file/directory) in a file system - * Path is system dependent, can't compare path from DOS/Windows with one from Unix based systems - * - * Path object can be created various ways + * system dependent, can't compare path from DOS/Win with one from POSIX/Unix based systems * */ public class PathCreation { public static void main(String[] args) throws URISyntaxException { + // Path object can be created various ways + // 1. Create Path using Paths helper class Path path1 = Paths.get("README.md"); Path path2 = Paths.get("..", "nio2/README.md"); // constructing paths - System.out.println(path1.toAbsolutePath()); - System.out.println(path2.toAbsolutePath()); + System.out.println(path1.toAbsolutePath()); // /home/workspace/CoreJava/README.md + System.out.println(path2.toAbsolutePath()); // /home/workspace/CoreJava/../nio2/README.md // 2. Construct Path from URI resource Path path3 = Paths.get(new URI("file:/c:/user/google/docs")); // refer to URI based resource @@ -38,7 +38,7 @@ public static void main(String[] args) throws URISyntaxException { //Path path5 = fileSystem.getPath("README.md"); // 5. Create path from File object. File to Path, and vice versa - File file = new File("CoreJava/src/nio2/README.md"); + File file = new File("CoreJava/nio2/README.md"); Path path6 = file.toPath(); file = path6.toFile(); diff --git a/nio2/README.md b/nio2/README.md index 908f4a0..5e5a3be 100644 --- a/nio2/README.md +++ b/nio2/README.md @@ -1,15 +1,15 @@ +# NIO (Non-blocking IO) -**Java.nio** package is initially started to replace java.io package(Non-blocking io), but hasn't taken off until second version of nio API in Java 7 which is called nio2. -NIO2 actually intended to replace java.io.File class and its related interactions. +``java.nio`` package is initially started to replace ``java.io`` package(Non-blocking io), however it hasn't taken off until the second version of nio API in Java 7 which is called **nio2**. **NIO2** actually intended to replace ``java.io.File`` class and its related interactions. + +- ``java.nio.file.Path`` refers to resource on filesystem which doesn't have to exist. And most of its operations don't require it too. +- ``java.nio.file.Paths`` is a factory/helper class for ``Path`` -Paths - factory/helper class for Path -Path refers to resource on filesystem which doesn't have to exist. And most of its operations doesn't require too. -NIO2 API has following advantages over IO API: +**NIO2** API has following advantages over old **IO** API: * supports file-system dependent attributes (DOS, POSIX) -* allows you traverse directory hierarchy directly +* allows you directly traverse directory hierarchy * supports symbolic link in file system -* when reading multiple attributes of a file, it's faster - +* faster when reading multiple attributes of a file From 767b7051d292908bbb615d223d5a4b3bae568d81 Mon Sep 17 00:00:00 2001 From: tugul Date: Sat, 9 Jun 2018 10:24:50 +0200 Subject: [PATCH 27/32] New date time in java.time --- datetimes/README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 datetimes/README.md diff --git a/datetimes/README.md b/datetimes/README.md new file mode 100644 index 0000000..999ad09 --- /dev/null +++ b/datetimes/README.md @@ -0,0 +1,29 @@ +# Date and Time + +New package ``java.time`` addresses the shortcommings of old date and time in ``java.util`` package. + +## Features +``java.time`` package provides following features out of box, including but not limited to: +- Simpler and flexible creation of objects +- Thread-safety through its immutabile classes +- Method chaining in functional programming style for complex transformations +- Better representation of dates in time zones and chronologies +- Truncation of values in any field of dates and times +- Flexible parsing and formatting of dates and times +- Interoperability with old Java dates and times + +## Members +``java.time`` package encompasses versatile representations of use cases related with date and timing. Majority of them are listed below: + +- **LocalDate** – a simple date (year, month, day) +- **LocalTime** – time with nanosecond precision and without date info +- **LocalDateTime** – same as LocalDate, but includes time with nanosecond precision +- **ZonedDateTime** – same as OffsetDateTime, but includes a time zone ID +- **OffsetDateTime** – same as LocalDateTime, but with time zone offset +- **OffsetLocalTime** – same as LocalTime, but with time zone offset +- **Instant** – represents a point in time (timestamp) +- **MonthDay** – month and day, without year or time +- **YearMonth** – month and year, without day or time +- **Duration** – time period represented in seconds, minutes and hours with nanosecond precision +- **Period** – time period represented in days, months and years +- **ZoneId** – time-zone id and used to convert Instant and LocalDateTime From edb91585288331ca795e851fdec768dac9d917cd Mon Sep 17 00:00:00 2001 From: tugul Date: Sat, 9 Jun 2018 10:31:31 +0200 Subject: [PATCH 28/32] java.util.Arrays is helper class --- collections/ArrayVsArrayList.java | 4 +-- collections/README.md | 50 ++++++++++++++++++------------- 2 files changed, 31 insertions(+), 23 deletions(-) diff --git a/collections/ArrayVsArrayList.java b/collections/ArrayVsArrayList.java index df1769d..52c0d8e 100644 --- a/collections/ArrayVsArrayList.java +++ b/collections/ArrayVsArrayList.java @@ -8,8 +8,8 @@ * Dimension: Array can be multi-dimensional while ArrayList is only single dimensional * Primitive: ArrayList can't store primitives, instead can store their wrapper objects * Generics: ArrayList supports generics, so it is type-safe - * Adding an element: Array element is added through asignment operator, while ArrayList use add() method - * Length: Array has length variable while ArraList has size() method + * Adding an element: Array element is added through assignment operator, while ArrayList use add() method + * Length: Array has length variable while ArrayList has size() method * Performance: Array is faster while ArrayList is bit slower, especially when comparing * Sorting: * Array : Arrays.sort(T[] a); diff --git a/collections/README.md b/collections/README.md index 76bbc6d..2f707c2 100644 --- a/collections/README.md +++ b/collections/README.md @@ -1,26 +1,34 @@ -Collections framework has four main data structure types (list, set, queue and map). -List, set and queue interfaces extends Collection interface which extends Iterable interface. +# Collections framework +Collections framework has four main data structure types which are **list**, **set**, **queue** and **map**. +``List``, ``Set`` and ``Queue`` interfaces in ``java.util`` extends ``java.util.Collection`` interface which extends ``java.lang.Iterable`` interface. -##### 1. List — Ordered collection of elements that can duplicate -- ArrayList: Standard re-sizable list. -- LinkedList: implements both List and Deque. Can easily add/remove from beginning or end. -- Vector: Older version of ArrayList, thread-safe. -- Stack: Older last-in, first-out class, newer version ArrayDeque is more flexible +## Main data structure types +### 1. **List** — Ordered collection of elements that can duplicate +- ``ArrayList``: Standard re-sizable list. +- ``LinkedList``: implements both ``List`` and ``Deque``. Can easily add/remove from beginning or end. +- ``Vector``: Older version of ``ArrayList``, thread-safe. +- ``Stack``: Older last-in, first-out class, newer version ``ArrayDeque`` is more flexible -##### 2. Set —Does not allow duplicates -- HashSet: Uses hashcode() to find unordered elements. -- TreeSet: implements NavigableSet which extends SortedSet. Does not allow null values. +### 2. **Set** — Does not allow duplicates +- ``HashSet``: Uses ``hashcode()`` to find unordered elements. +- ``TreeSet``: implements ``NavigableSet`` which extends ``SortedSet``. Does not allow null values. -##### 3. Queue —Orders elements for processing -- LinkedList: Can easily add/remove from beginning or end. -- ArrayDeque: First-in, first-out or last-in, first-out. Does not allow null values. +### 3. **Queue** — Orders elements for processing +- ``LinkedList``: Can easily add/remove from beginning or end. +- ``ArrayDeque``: First-in, first-out or last-in, first-out. Does not allow null values. -##### 4. Map —Maps unique keys to values -- HashMap: Uses hashcode() to find keys, allows null key -- TreeMap: Sorted map. Does not allow null keys. -- HashTable: Older version of HashMap. Does not allow null keys or values. +### 4. **Map** — Maps unique keys to values +- ``HashMap``: Uses ``hashcode()`` to find keys, allows null key +- ``TreeMap``: Sorted map. Does not allow null keys. +- ``HashTable``: Older version of ``HashMap``. Does not allow null keys or values. -Sorting: - - Collections.sort(List\ list) - - Collections.sort(List\ list, Comparator comparator) - - Use TreeMap to sort Map by key or value \ No newline at end of file +## Sorting + - ``Collections.sort(List\ list)`` + - ``Collections.sort(List\ list, Comparator comparator)`` + - Use ``TreeMap`` to sort ``Map`` by key or value + + ## Helper classes + ### ``java.util.Arrays`` + It is a helper class for common unitility tasks on manipulating arrays such as _sorting_ and _searching_ in arrays + + \ No newline at end of file From 733f036768d9248dca9a8b99d7009d40dbca5a54 Mon Sep 17 00:00:00 2001 From: tugul Date: Thu, 6 Sep 2018 21:51:39 +0200 Subject: [PATCH 29/32] Improved explanations on concurrency --- README.md | 2 +- concurrency/README.md | 94 ++++++++++++++++++------------------------- 2 files changed, 41 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 6b5e0a6..83a527b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Interface can have non-abstract concrete method if they are **default** or **sta Non-blocking io API. Read [more](https://github.com/tugul/CoreJava/tree/master/nio2) ## Date Time API -Working with dates in older java version was hard and often had to use external libraries. However, new API introduced many more features and provides easy of use: For example ``LocalDate``, ``LocalTime``, ``LocalDateTime``, ``ZonedDateTime``. Read [more](https://github.com/tugul/CoreJava/tree/master/datetimes) +Working with dates in older JDK was painful and developers often had to use external libraries. However, new API addresses the issues and provides clarity and flexibility to its core through ``java.time`` package: For example ``LocalDate``, ``LocalTime``, ``LocalDateTime``, ``ZonedDateTime``. Read [more](https://github.com/tugul/CoreJava/tree/master/datetimes) ## Collection API improvement New method ``forEach()`` and more . Read [more](https://github.com/tugul/CoreJava/tree/master/collections) diff --git a/concurrency/README.md b/concurrency/README.md index 2dd7190..7752f6b 100644 --- a/concurrency/README.md +++ b/concurrency/README.md @@ -1,22 +1,19 @@ -## Concurrency in Java 8 +# Concurrency in Java 8 Concurrency API (```java.util.concurrent``` package) was initially introduced in Java 5 to ease threads management. Since then till Java 8, it has been enriched so much with many classes and frameworks. Below its major classes, interfaces and concepts are explained. -```Runnable``` ----- -A functional interface used to define a work/task that thread will execute. It has functional method ```void run()``` with no argument. +## Important types -```Callable``` ----- -A functional interface used to define a work/task that thread will execute. It has functional method ```T call()``` with no argument and returns generic type. Unlike ```Runnable```, it can throw checked exceptions. +### ```Runnable``` +```java.lang.Runnable``` is a _functional_ interface used to define a work/task that thread will execute. It has functional method ```void run()``` with no argument. -```ExecutorService``` ----- -An interface with methods to take/execute tasks. It provides many useful features (thread pooling, scheduling etc.) -and extends functional interface ```Executor``` which has ```void execute(Runnable)``` method +### ```Callable``` +```java.util.concurrent.Callable``` is a _functional_ interface used to define a work/task that thread will execute. It has functional method ```T call()``` with no argument and returns generic type. Unlike ```Runnable```, it can throw checked exceptions. -```Future``` ----- -This class represents a result of an asynchronous task completion and has below methods: +### ```ExecutorService``` +```java.util.concurrent.ExecutorService``` is an interface with methods to take/execute tasks. It provides many useful features such as thread pooling, scheduling etc. and extends functional interface ```java.uti.concurrent.Executor``` which has functional method ```void execute(Runnable task)``` + +### ```Future``` +An interface ```java.util.concurrent.Future``` represents a result of an asynchronous task completion and has below methods: - ```T get()``` infinitely waits for the task to complete and returns value resulted once the task is finished - ```T get(long, TimeUnit)``` waits for the result only for specified time period and throws ```TimeOutException``` if didn't get @@ -24,57 +21,46 @@ This class represents a result of an asynchronous task completion and has below - ```boolean isCancelled()``` returns true if the task is cancelled before completed - ```boolean isDone()``` returns true if the task is completed +### ``CyclicBarrier`` +A class ``java.util.concurrent.CyclicBarrier`` is used to force a set of threads to wait until they are at a certain stage of execution before continuing. + +## Thread manipulation +### Scheduling tasks +```ScheduledExecutorService``` is used to schedule a task to execute after delay or repeatedly with time interval. It extends ```ExecutorService``` interface, and its instance is taken from factory method in ```java.util.concurrent.Executors``` helper class + + +### Pause execution +Method ```Thread.sleep(long)``` pauses current thread to suspend its execution for certain period and throws checked exception ```InterruptedException``` if interrupt request is received while pausing -Shutting down thread ----- +### Shutting down a thread - It is necessary to shut down the service instance(call ```shutdown()```), otherwise application will hang. - Once it is requested to shutdown, executor rejects new task requests and throws ```RejectedExecutionException``` and -continues executing pending/ongoing tasks till completed. During this period, ```isShutdown()``` returns true and ```isTerminated()``` returns false. -- When ongoing tasks are completed, ```isShutdown()``` and ```isTerminated()``` methods return true and won't receive new tasks.
+continues executing pending/ongoing tasks till completed. During this period, ```isShutdown()``` returns ``true`` and ```isTerminated()``` returns ``false``. +- When ongoing tasks are completed, ```isShutdown()``` and ```isTerminated()``` methods return ``true`` and won't receive new tasks.
- ```shutDownNow()``` terminates all running/pending tasks and returns ```List``` which are not executed tasks.
-- ```awaitTermination(long, TimeUnit)``` waits for specified period to complete ongoing tasks after shutdown request and returns true if executor terminated or false if timeout elapsed before termination. It doesn't do anything except for waiting. - -Scheduling tasks ---- -```ScheduledExecutorService``` is used to schedule a task to execute after delay or repeatedly with time interval. It extends ```ExecutorService``` interface, and its instance is taken from factory method in ```Executors``` helper class - - -Pause execution ----- -```Thread.sleep(long)``` pauses current thread to suspend its execution for certain period and throws checked exception ```InterruptedException``` if interrupt request is received while pausing - -CyclicBarrier class ---- -used to force a set of threads to wait until they are at a certain stage of execution before continuing. - -Threading problems ---- -Deadlock - multiple processes are blocked forever, each waiting on the other
-Starvation - single thread is perpetually denied access to a shared resource or lock. - The thread is still active, but it is unable to complete its work as a result of other - threads constantly taking the resource that they trying to access.
-Livelock - occurs when two or more threads are conceptually blocked forever, although they - are each still active and trying to complete their task. Livelock is a special case of resource - starvation in which two or more threads actively try to acquire a set of locks, are unable to - do so, and restart part of the process.
-Race condition - occurs when several threads access one resource at the same time and mess its state. - - -Synchronization ---- -```synchronized``` key word is used for in method declaration or around code block. +- ```awaitTermination(long, TimeUnit)``` waits for specified period to complete ongoing tasks after shutdown request and returns ``true`` if executor terminated or false if timeout elapsed before termination. It doesn't do anything except for waiting. + + +## Threading problems +**Deadlock** - multiple processes are blocked forever, each waiting on the other. +**Starvation** - single thread is perpetually denied access to a shared resource or lock. The thread is still active, but it is unable to complete its work as a result of other threads constantly taking the resource that they trying to access. +**Livelock** - occurs when two or more threads are conceptually blocked forever, although they are each still active and trying to complete their task. Livelock is a special case of resource starvation in which two or more threads actively try to acquire a set of locks, are unable to do so, and restart part of the process. +**Race condition** - occurs when several threads access one resource at the same time and mess its state. + +## Synchronization +Keyword ```synchronized``` is used for in method declaration or around code block. When method is declared as synchronized, lock is created on the whole object, might be less efficient. -On the other hand, synchronized block uses an object to create a lock. Static synchronized method orders thread access across all instances rather than single instance.
-Alternative to synchronized block or method, concurrent collections or atomic primitive classes can be used +On the other hand, synchronized block uses an object to create a lock. Static synchronized method orders thread access across all instances rather than single instance. +> Alternative to synchronized block or method, **concurrent collections** or **atomic** primitive classes can be used -Atomic classes
-```java.util.concurrent.atomic``` package provides atomic classes which supports atomic access to single values, such as primitive value or object reference. They can be ideally used in scenarios where multiple threads read/write single counter. Increment/decrement operators ++/-- are not thread-safe meaning that while one thread is updating and taking new value, other thread can update it meantime. With atomic nature, atomic classes have methods to perform increment/decrement as a single unit of operation without interference by other threads.
+### Atomic classes +```java.util.concurrent.atomic``` package provides atomic classes which supports atomic access to single values, such as primitive value or object reference. They can be ideally used in scenarios where multiple threads read/write single counter. Increment/decrement operators ++/-- are not thread-safe meaning that while one thread is updating and taking new value, other thread can update it meantime. With atomic nature, atomic classes have methods to perform increment/decrement as a single unit of operation without interference by other threads. ```AtomicBoolean, -- ```
```AtomicInteger, AtomicIntegerArray```
```AtomicLong, AtomicLongArray```
```AtomicReference, AtomicReferenceArray```
-Concurrent collections
+### Concurrent collections Concurrent collections provide performance enhancements that prevent unnecessary synchronizations. Read/write accesses to collection are synchronized so that data consistency is kept during multi-thread execution outside synchronized method or block. Go to concurrent collections. \ No newline at end of file From 0149d40b4c0ff874abfd5ff4305311099b8f6a52 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 8 Oct 2018 20:23:15 +0200 Subject: [PATCH 30/32] Clarified some explanations --- classes/StaticMember.java | 8 ++++++-- concurrency/UsingExecutorService.java | 14 +++++++------- interfaces/DefaultMethod.java | 2 +- interfaces/StaticMethod.java | 6 ++++-- 4 files changed, 18 insertions(+), 12 deletions(-) diff --git a/classes/StaticMember.java b/classes/StaticMember.java index 1b8e488..229b8ea 100644 --- a/classes/StaticMember.java +++ b/classes/StaticMember.java @@ -3,9 +3,9 @@ /** * Static members can be accessed not only through class name, * but also through instance of the class. - * Even after reference of the instance points to NULL + * Even when reference of the instance points to NULL * - * But instance members can't be accessed if reference is points to NULL + * But instance members can't be accessed if reference points to NULL */ class A { @@ -27,5 +27,9 @@ public static void main(String[] args) { a = null; System.out.println(a.staticField); // 0 System.out.println(a.instanceField); // NullPointerException + + A b; + System.out.println(b.staticField); // 0 + System.out.println(A.staticField); // 0 } } diff --git a/concurrency/UsingExecutorService.java b/concurrency/UsingExecutorService.java index 784d371..ab90e1c 100644 --- a/concurrency/UsingExecutorService.java +++ b/concurrency/UsingExecutorService.java @@ -3,17 +3,17 @@ import java.util.concurrent.*; /** - * - ExecutorService - * interface with methods to take/execute tasks and provides many useful features (thread pooling, scheduling etc.) - * necessary to shut down the service instance, otherwise application will hang - * extends functional interface Executor (with void execute(Runnable)) + * ExecutorService + * - interface with methods to take/execute tasks and provides many useful features (thread pooling, scheduling etc.) + * - necessary to shut down the service instance, otherwise application will hang + * - extends functional interface Executor (with void execute(Runnable)) * - * - Methods to submit a task to a thread - * Asynchronous (doesn't wait for given task to finish) + * Methods to submit a task to a thread + * - Asynchronous (doesn't wait for given task to finish) * 1. execute(Runnable) - returns nothing * 2. submit(Runnable) - returns Future * 3. submit(Callable) - returns Future - * Synchronous (meaning that waits for given tasks to finish) + * - Synchronous (meaning that waits for given tasks to finish) * 4. invokeAll() takes a collection of Callable tasks and returns collection of Future objects once all are finished * 5. invokeAny() takes a collection of Callable tasks and returns single Future object once any of them is finished * diff --git a/interfaces/DefaultMethod.java b/interfaces/DefaultMethod.java index 67663e3..20deeb9 100644 --- a/interfaces/DefaultMethod.java +++ b/interfaces/DefaultMethod.java @@ -6,7 +6,7 @@ * - Default method may only be declared in interface, not any class * - Method marked default must have body/implementation * - Like other interface method, it is assumed to be public - * - Marking it abstract, static or final lead to compilation error + * - Marking it abstract, static or final leads to compilation error * - Optional to override default method in implementing class */ interface ICan { diff --git a/interfaces/StaticMethod.java b/interfaces/StaticMethod.java index c319f5f..e57047b 100644 --- a/interfaces/StaticMethod.java +++ b/interfaces/StaticMethod.java @@ -9,11 +9,13 @@ * - Reference to the interface name must be used to use */ interface IHaveStatic1 { - static void sayMyName() { System.out.println("Interface One"); } + String name = "Interface One" + static void sayMyName() { System.out.println(name); } } interface IHaveStatic2 { - static void sayMyName() { System.out.println("Interface Two"); } + String name = "Interface Two" + static void sayMyName() { System.out.println(name); } } public class StaticMethod implements IHaveStatic1, IHaveStatic2 { From 85cd51f8a57fe7f2ceb62d82d9526479395e0455 Mon Sep 17 00:00:00 2001 From: tugul Date: Mon, 8 Oct 2018 20:28:38 +0200 Subject: [PATCH 31/32] Generic and Wildcard are not exactly same --- generics/{GenericWildcard.java => Wildcard.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename generics/{GenericWildcard.java => Wildcard.java} (98%) diff --git a/generics/GenericWildcard.java b/generics/Wildcard.java similarity index 98% rename from generics/GenericWildcard.java rename to generics/Wildcard.java index 2995ee5..7823cc5 100644 --- a/generics/GenericWildcard.java +++ b/generics/Wildcard.java @@ -17,7 +17,7 @@ * * Read more: https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html */ -public class GenericWildcard { +public class Wildcard { public static void printCollection1(Collection col) { for (Object o : col) From fbcc39aaddcfa3f57d7f5222a94e6adc73f0e75a Mon Sep 17 00:00:00 2001 From: tugul Date: Fri, 12 Oct 2018 21:14:28 +0200 Subject: [PATCH 32/32] Minor update --- streams/AboutOptional.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/streams/AboutOptional.java b/streams/AboutOptional.java index db67a1f..2ce7855 100644 --- a/streams/AboutOptional.java +++ b/streams/AboutOptional.java @@ -21,7 +21,7 @@ * Optional empty() - creates optional object with empty value in it * * - Caller of a method returning Optional - * should use ifPresent to check value is present or not + * recommended to call isPresent to check value is present or not before accessing value * T get() - returns the wrapped value or throws NoSuchElementException if the value is empty/absent * boolean isPresent() - check if value is present or not * void ifPresent(Consumer) - call Consumer parameter if value is present