diff --git a/README.md b/README.md
index e422f73..83a527b 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 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)
+
+## 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
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/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
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
}
}
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
diff --git a/concurrency/README.md b/concurrency/README.md
index bb51203..7752f6b 100644
--- a/concurrency/README.md
+++ b/concurrency/README.md
@@ -1,78 +1,66 @@
-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.
-
-Runnable
-----
-A functional interface used to define a work/task that thread will execute. It has functional method void run() with no argument.
-
-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.
-
-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
-
-Future class
-----
-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
-
-
-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.
-
-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.
+# 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.
+
+## Important types
+
+### ```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.
+
+### ```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.
+
+### ```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
+- ```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
+
+### ``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 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.
+- ```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.
+
+
+## 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.
-AtomicBoolean, --
-AtomicInteger, AtomicIntegerArray
-AtomicLong, AtomicLongArray
-AtomicReference, AtomicReferenceArray
+### 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
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/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
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
}
}
}
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
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 {
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
diff --git a/generics/GenericWildcard.java b/generics/Wildcard.java
similarity index 93%
rename from generics/GenericWildcard.java
rename to generics/Wildcard.java
index e4bc377..7823cc5 100644
--- a/generics/GenericWildcard.java
+++ b/generics/Wildcard.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
@@ -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