diff --git a/.classpath b/.classpath
new file mode 100644
index 0000000..fb565a5
--- /dev/null
+++ b/.classpath
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/.project b/.project
new file mode 100644
index 0000000..d5ef88e
--- /dev/null
+++ b/.project
@@ -0,0 +1,17 @@
+
+
+ Core_Java_Programs
+
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+
+ org.eclipse.jdt.core.javanature
+
+
diff --git a/README.md b/README.md
index 0951b0e..4ecb391 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,4 @@
# Core_Java_Programs
Sample Programs In Core Java
+
+## Content
diff --git a/resource/input.txt.txt b/resource/input.txt.txt
new file mode 100644
index 0000000..1e7c55f
--- /dev/null
+++ b/resource/input.txt.txt
@@ -0,0 +1 @@
+Hi, my name is java.
\ No newline at end of file
diff --git a/resource/output.txt.txt b/resource/output.txt.txt
new file mode 100644
index 0000000..e69de29
diff --git a/src/com/p2/DS/BinarySearch.java b/src/com/p2/DS/BinarySearch.java
new file mode 100644
index 0000000..6c1a635
--- /dev/null
+++ b/src/com/p2/DS/BinarySearch.java
@@ -0,0 +1,36 @@
+package com.p2.DS;
+
+class BinarySearch {
+ int binarySearch(int arr[], int l, int r, int x) {
+ if (r >= l) {
+ System.out.println("l:" + l + " r" + r + " ");
+ int mid = l + (r - l) / 2;
+ System.out.println("l:" + l + " r:" + r + " mid:" + mid);
+ // If the element is present at the middle itself
+ if (arr[mid] == x)
+ return mid;
+ // If element is smaller than mid, then it can only
+ // be present in left subarray
+ if (x < arr[mid]) {
+ return binarySearch(arr, l, mid - 1, x);
+ } else {// Else the element can only be present in right // subarray
+ return binarySearch(arr, mid + 1, r, x);
+ }
+ }
+ // We reach here when element is not present in array
+ return -1;
+ }
+
+ // Driver method to test above
+ public static void main(String args[]) {
+ BinarySearch ob = new BinarySearch();
+ int arr[] = { 1, 2, 3, 4, 10, 40 };
+ int length = arr.length;
+ int value = 10;
+ int result = ob.binarySearch(arr, 0, length - 1, value);
+ if (result == -1)
+ System.out.println("Element not present");
+ else
+ System.out.println("Element found at index " + result);
+ }
+}
diff --git a/src/com/p2/DS/BinarySearchUsingLoop.java b/src/com/p2/DS/BinarySearchUsingLoop.java
new file mode 100644
index 0000000..e14a41c
--- /dev/null
+++ b/src/com/p2/DS/BinarySearchUsingLoop.java
@@ -0,0 +1,35 @@
+package com.p2.DS;
+
+// This algorithm works on sorted array only
+public class BinarySearchUsingLoop {
+ // Returns index of x if it is present in arr[], else
+ // return -1
+ int binarySearch(int arr[], int x) {
+ int l = 0, r = arr.length - 1;
+ while (l <= r) {
+ int m = l + (r - l) / 2;
+ // Check if x is present at mid
+ if (arr[m] == x)
+ return m;
+ // If x greater, ignore left half
+ if (arr[m] < x)
+ l = m + 1;
+ // If x is smaller, ignore right half
+ else
+ r = m - 1;
+ }
+ // if we reach here, then element was not present
+ return -1;
+ }
+ public static void main(String args[]) {
+ BinarySearchUsingLoop ob = new BinarySearchUsingLoop();
+ int arr[] = { 2, 3, 4, 10, 40 };
+ int n = arr.length;
+ int x = 10;
+ int result = ob.binarySearch(arr, x);
+ if (result == -1)
+ System.out.println("Element not present");
+ else
+ System.out.println("Element found at index " + result);
+ }
+}
diff --git a/src/com/p2/DS/LenearSearch.java b/src/com/p2/DS/LenearSearch.java
new file mode 100644
index 0000000..48a4a9b
--- /dev/null
+++ b/src/com/p2/DS/LenearSearch.java
@@ -0,0 +1,15 @@
+package com.p2.DS;
+
+class LinearSearch {
+ // This function returns index of element x in arr[]
+ static int search(int arr[], int n, int x) {
+ for (int i = 0; i < n; i++) {
+ // Return the index of the element if the element
+ // is found
+ if (arr[i] == x)
+ return i;
+ }
+ // return -1 if the element is not found
+ return -1;
+ }
+}
\ No newline at end of file
diff --git a/src/com/p2/DS/LinkedList.java b/src/com/p2/DS/LinkedList.java
new file mode 100644
index 0000000..ca61a75
--- /dev/null
+++ b/src/com/p2/DS/LinkedList.java
@@ -0,0 +1,59 @@
+package com.p2.DS;
+
+//A simple Java program to introduce a linked list
+class LinkedList {
+ Node head; // head of list
+
+ /* Linked list Node. This inner class is made static so that
+ main() can access it */
+ static class Node {
+ int data;
+ Node next;
+ Node(int d) { data = d; next=null; } // Constructor
+ }
+
+ /* method to create a simple linked list with 3 nodes*/
+ public static void main(String[] args) {
+ /* Start with the empty list. */
+ LinkedList llist = new LinkedList();
+
+ llist.head = new Node(1);
+ Node second = new Node(2);
+ Node third = new Node(3);
+
+ /* Three nodes have been allocated dynamically.
+ We have refernces to these three blocks as first,
+ second and third
+
+ llist.head second third
+ | | |
+ | | |
+ +----+------+ +----+------+ +----+------+
+ | 1 | null | | 2 | null | | 3 | null |
+ +----+------+ +----+------+ +----+------+ */
+
+ llist.head.next = second; // Link first node with the second node
+
+ /* Now next of first Node refers to second. So they
+ both are linked.
+
+ llist.head second third
+ | | |
+ | | |
+ +----+------+ +----+------+ +----+------+
+ | 1 | o-------->| 2 | null | | 3 | null |
+ +----+------+ +----+------+ +----+------+ */
+
+ second.next = third; // Link second node with the third node
+
+ /* Now next of second Node refers to third. So all three
+ nodes are linked.
+
+ llist.head second third
+ | | |
+ | | |
+ +----+------+ +----+------+ +----+------+
+ | 1 | o-------->| 2 | o-------->| 3 | null |
+ +----+------+ +----+------+ +----+------+ */
+ }
+}
diff --git a/src/com/p2/DS/MergeSort.java b/src/com/p2/DS/MergeSort.java
new file mode 100644
index 0000000..3b940ae
--- /dev/null
+++ b/src/com/p2/DS/MergeSort.java
@@ -0,0 +1,96 @@
+package com.p2.DS;
+
+/* Java program for Merge Sort */
+class MergeSort {
+ // Merges two subarrays of arr[].
+ // First subarray is arr[l..m]
+ // Second subarray is arr[m+1..r]
+
+ void merge(int arr[], int l, int m, int r) {
+ System.out.println("Merge L:" + l + " M: " + m + "R " + r);
+ // Find sizes of two subarrays to be merged
+ // (middle - first) + 1
+ int n1 = m - l + 1;
+ // last -middle
+ int n2 = r - m;
+ /* Create temp arrays with given size*/
+ int L[] = new int[n1];
+ int R[] = new int[n2];
+ /* Copy data to temp arrays */
+ for (int i = 0; i < n1; ++i)
+ L[i] = arr[l + i];
+ for (int j = 0; j < n2; ++j)
+ R[j] = arr[m + 1 + j];
+ /* Merge the temp arrays */
+ // Initial indexes of first and second subarrays
+ int i = 0, j = 0;
+ // Initial index of merged subarry array
+ int k = l;
+ while (i < n1 && j < n2) {
+ if (L[i] <= R[j]) {
+ arr[k] = L[i];
+ i++;
+ } else {
+ arr[k] = R[j];
+ j++;
+ }
+ k++;
+ }
+ /* Copy remaining elements of L[] if any */
+ while (i < n1) {
+ arr[k] = L[i];
+ i++;
+ k++;
+ }
+ /* Copy remaining elements of R[] if any */
+ while (j < n2) {
+ arr[k] = R[j];
+ j++;
+ k++;
+ }
+ }
+
+ // Main function that sorts arr[l..r] using
+ // merge()
+ int i = 0;
+
+ void sort(int arr[], int l, int r) {
+ if (l < r) {
+ // Find the middle point
+ int m = (l + r) / 2;
+
+ // Sort first and second halves
+ // System.out.println(" Line 59 " + i++);
+ System.out.println("Sort L : " + l + ", M :" + m + ", R :" + r);
+ sort(arr, l, m);
+ // System.out.println("Line 61 " + i++);
+ sort(arr, m + 1, r);
+
+ // Merge the sorted halves
+ merge(arr, l, m, r);
+ }
+ }
+
+ /* A utility function to print array of size n */
+ static void printArray(int arr[]) {
+ int n = arr.length;
+ for (int i = 0; i < n; ++i)
+ System.out.print(arr[i] + " ");
+ System.out.println();
+ }
+
+ // Driver method
+ public static void main(String args[]) {
+ int arr[] = { 12, 11, 56 ,23};
+
+ System.out.println("Given Array");
+ printArray(arr);
+
+ MergeSort ob = new MergeSort();
+ ob.sort(arr, 0, arr.length - 1);
+
+ System.out.println("\nSorted array");
+ printArray(arr);
+ }
+}
+/* This code is contributed by Rajat Mishra */
diff --git a/src/com/p2/DS/StackEx.java b/src/com/p2/DS/StackEx.java
new file mode 100644
index 0000000..40ea2f4
--- /dev/null
+++ b/src/com/p2/DS/StackEx.java
@@ -0,0 +1,51 @@
+package com.p2.DS;
+
+//Java code for stack implementation
+
+import java.util.*;
+
+class StackEx {
+ // Pushing element on the top of the stack
+ static void stack_push(Stack stack) {
+ for (int i = 0; i < 5; i++) {
+ stack.push(i);
+ }
+ }
+
+ // Popping element from the top of the stack
+ static void stack_pop(Stack stack) {
+ System.out.println("Pop :");
+
+ for (int i = 0; i < 5; i++) {
+ Integer y = (Integer) stack.pop();
+ System.out.println(y);
+ }
+ }
+
+ // Displaying element on the top of the stack
+ static void stack_peek(Stack stack) {
+ Integer element = (Integer) stack.peek();
+ System.out.println("Element on stack top : " + element);
+ }
+
+ // Searching element in the stack
+ static void stack_search(Stack stack, int element) {
+ Integer pos = (Integer) stack.search(element);
+
+ if (pos == -1)
+ System.out.println("Element not found");
+ else
+ System.out.println("Element is found at position " + pos);
+ }
+
+ public static void main(String[] args) {
+ Stack stack = new Stack();
+
+ stack_push(stack);
+ stack_pop(stack);
+ stack_push(stack);
+ stack_peek(stack);
+ stack_search(stack, 2);
+ stack_search(stack, 6);
+ }
+}
\ No newline at end of file
diff --git a/src/com/p2/DS/StackImpl.java b/src/com/p2/DS/StackImpl.java
new file mode 100644
index 0000000..6c5e8ed
--- /dev/null
+++ b/src/com/p2/DS/StackImpl.java
@@ -0,0 +1,137 @@
+package com.p2.DS;
+
+/*
+ * Java Program to Implement Stack
+ */
+
+import java.util.*;
+
+/* Class arrayStack */
+class arrayStack {
+ protected int arr[];
+ protected int top, size, len;
+
+ /* Constructor for arrayStack */
+ public arrayStack(int n) {
+ size = n;
+ len = 0;
+ arr = new int[size];
+ top = -1;
+ }
+
+ /* Function to check if stack is empty */
+ public boolean isEmpty() {
+ return top == -1;
+ }
+
+ /* Function to check if stack is full */
+ public boolean isFull() {
+ return top == size - 1;
+ }
+
+ /* Function to get the size of the stack */
+ public int getSize() {
+ return len;
+ }
+
+ /* Function to check the top element of the stack */
+ public int peek() {
+ if (isEmpty())
+ throw new NoSuchElementException("Underflow Exception");
+ return arr[top];
+ }
+
+ /* Function to add an element to the stack */
+ public void push(int i) {
+ if (top + 1 >= size)
+ throw new IndexOutOfBoundsException("Overflow Exception");
+ if (top + 1 < size)
+ arr[++top] = i;
+ len++;
+ }
+
+ /* Function to delete an element from the stack */
+ public int pop() {
+ if (isEmpty())
+ throw new NoSuchElementException("Underflow Exception");
+ len--;
+ return arr[top--];
+ }
+
+ /* Function to display the status of the stack */
+ public void display() {
+ System.out.print("\nStack = ");
+ if (len == 0) {
+ System.out.print("Empty\n");
+ return;
+ }
+ for (int i = top; i >= 0; i--)
+ System.out.print(arr[i] + " ");
+ System.out.println();
+ }
+}
+
+/* Class StackImplement */
+public class StackImpl {
+ public static void main(String[] args) {
+ Scanner scan = new Scanner(System.in);
+ System.out.println("Stack Test\n");
+ System.out.println("Enter Size of Integer Stack ");
+ int n = scan.nextInt();
+ /* Creating object of class arrayStack */
+ arrayStack stk = new arrayStack(n);
+ /* Perform Stack Operations */
+ char ch;
+ do {
+ System.out.println("\nStack Operations");
+ System.out.println("1. push");
+ System.out.println("2. pop");
+ System.out.println("3. peek");
+ System.out.println("4. check empty");
+ System.out.println("5. check full");
+ System.out.println("6. size");
+ int choice = scan.nextInt();
+ switch (choice) {
+ case 1:
+ System.out.println("Enter integer element to push");
+ try {
+ stk.push(scan.nextInt());
+ } catch (Exception e) {
+ System.out.println("Error : " + e.getMessage());
+ }
+ break;
+ case 2:
+ try {
+ System.out.println("Popped Element = " + stk.pop());
+ } catch (Exception e) {
+ System.out.println("Error : " + e.getMessage());
+ }
+ break;
+ case 3:
+ try {
+ System.out.println("Peek Element = " + stk.peek());
+ } catch (Exception e) {
+ System.out.println("Error : " + e.getMessage());
+ }
+ break;
+ case 4:
+ System.out.println("Empty status = " + stk.isEmpty());
+ break;
+ case 5:
+ System.out.println("Full status = " + stk.isFull());
+ break;
+ case 6:
+ System.out.println("Size = " + stk.getSize());
+ break;
+ default:
+ System.out.println("Wrong Entry \n ");
+ break;
+ }
+ /* display stack */
+ stk.display();
+ System.out.println("\nDo you want to continue (Type y or n) \n");
+ ch = scan.next().charAt(0);
+
+ } while (ch == 'Y' || ch == 'y');
+ }
+}
diff --git a/src/com/p2/DS/package-info.java b/src/com/p2/DS/package-info.java
new file mode 100644
index 0000000..1337f4b
--- /dev/null
+++ b/src/com/p2/DS/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.DS;
\ No newline at end of file
diff --git a/src/com/p2/Oops/AbstractionEx.java b/src/com/p2/Oops/AbstractionEx.java
new file mode 100644
index 0000000..3a4d02b
--- /dev/null
+++ b/src/com/p2/Oops/AbstractionEx.java
@@ -0,0 +1,28 @@
+package com.p2.Oops;
+// Examples of Abstraction
+abstract class Shape {
+ abstract void draw();
+}
+
+// In real scenario, implementation is provided by others i.e. unknown by end
+// user
+class Rectangle extends Shape {
+ void draw() {
+ System.out.println("drawing rectangle");
+ }
+}
+
+class Circle1 extends Shape {
+ void draw() {
+ System.out.println("drawing circle");
+ }
+}
+
+// In real scenario, method is called by programmer or user
+class AbstractionEx {
+ public static void main(String args[]) {
+ Shape s = new Circle1();// In real scenario, object is provided through
+ // method e.g. getShape() method
+ s.draw();
+ }
+}
diff --git a/src/com/p2/Oops/package-info.java b/src/com/p2/Oops/package-info.java
new file mode 100644
index 0000000..48359a6
--- /dev/null
+++ b/src/com/p2/Oops/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.Oops;
\ No newline at end of file
diff --git a/src/com/p2/PassByValue/PassByValueEx.java b/src/com/p2/PassByValue/PassByValueEx.java
new file mode 100644
index 0000000..a25be12
--- /dev/null
+++ b/src/com/p2/PassByValue/PassByValueEx.java
@@ -0,0 +1,39 @@
+package com.p2.PassByValue;
+
+public class PassByValueEx {
+
+ public void badSwap(Integer var1, Integer var2) {
+ int temp = var1;
+ var1 = var2;
+ var2 = temp;
+ }
+
+ public void tricky(Point arg1, Point arg2) {
+ // reasign
+ arg1.x = 100;
+ arg1.y = 100;
+ // swaping ...
+ Point temp = arg1;
+ arg1 = arg2;
+ arg2 = temp;
+ }
+
+ public static void main(String[] args) {
+ Integer var1 = 8;
+ Integer var2 = 10;
+ PassByValueEx er = new PassByValueEx();
+ er.badSwap(var1, var2);
+ System.out.println("var1 " + var1);
+
+ Point pnt1 = new Point(0, 0);
+ Point pnt2 = new Point(0, 0);
+ System.out.println("X: " + pnt1.x + " Y: " + pnt1.y);
+ System.out.println("X: " + pnt2.x + " Y: " + pnt2.y);
+ System.out.println(" ");
+ er.tricky(pnt1, pnt2);
+ System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
+ System.out.println("X: " + pnt2.x + " Y: " + pnt2.y);
+
+ // reassign worked, but swapping failed
+ }
+}
diff --git a/src/com/p2/PassByValue/Point.java b/src/com/p2/PassByValue/Point.java
new file mode 100644
index 0000000..0adf191
--- /dev/null
+++ b/src/com/p2/PassByValue/Point.java
@@ -0,0 +1,14 @@
+package com.p2.PassByValue;
+
+public class Point {
+
+ Integer x;
+ Integer y;
+
+ public Point(Integer x, Integer y) {
+ super();
+ this.x = x;
+ this.y = y;
+ }
+
+}
diff --git a/src/com/p2/PassByValue/package-info.java b/src/com/p2/PassByValue/package-info.java
new file mode 100644
index 0000000..aaf9be6
--- /dev/null
+++ b/src/com/p2/PassByValue/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.PassByValue;
\ No newline at end of file
diff --git a/src/com/p2/abstractC/Main.java b/src/com/p2/abstractC/Main.java
new file mode 100644
index 0000000..5797d4f
--- /dev/null
+++ b/src/com/p2/abstractC/Main.java
@@ -0,0 +1,16 @@
+package com.p2.abstractC;
+
+public abstract class Main {
+
+ /*
+ * Note Main is abstract. Since we can’t create object of abstract classes in
+ * Java, it is guaranteed that object of class with main() is not created by
+ * JVM.
+ * You can define main in an abstract class and run
+ */
+ public static void main(String[] args) {
+ System.out.println("Hi This is Pradeep");
+
+ }
+
+}
diff --git a/src/com/p2/abstractC/Main02.java b/src/com/p2/abstractC/Main02.java
new file mode 100644
index 0000000..2f87453
--- /dev/null
+++ b/src/com/p2/abstractC/Main02.java
@@ -0,0 +1,15 @@
+package com.p2.abstractC;
+
+public abstract class Main02 {
+
+ /*
+ * Note Main is abstract. Since we can’t create object of abstract classes in
+ * Java, it is guaranteed that object of class with main() is not created by
+ * JVM.
+ */
+ public static void main() {
+ System.out.println("Hi This is Pradeep");
+
+ }
+
+}
diff --git a/src/com/p2/abstractC/Main03.java b/src/com/p2/abstractC/Main03.java
new file mode 100644
index 0000000..20ae82a
--- /dev/null
+++ b/src/com/p2/abstractC/Main03.java
@@ -0,0 +1,10 @@
+package com.p2.abstractC;
+
+public class Main03 {
+
+ public static void main(String[] args) {
+ // TODO Auto-generated method stub
+ Main02.main();
+ }
+
+}
diff --git a/src/com/p2/abstractC/package-info.java b/src/com/p2/abstractC/package-info.java
new file mode 100644
index 0000000..63f617f
--- /dev/null
+++ b/src/com/p2/abstractC/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.abstractC;
\ No newline at end of file
diff --git a/src/com/p2/classMembers/MainC.java b/src/com/p2/classMembers/MainC.java
new file mode 100644
index 0000000..36e7be4
--- /dev/null
+++ b/src/com/p2/classMembers/MainC.java
@@ -0,0 +1,23 @@
+package com.p2.classMembers;
+
+public class MainC {
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ // Instantiating the outer class
+ Outer_Demo outer = new Outer_Demo();
+ // Instantiating the inner class
+ Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
+ System.out.println(inner.getNum());
+
+ Outer_Demo demo_2 = new Outer_Demo();
+ demo_2.my_Method();
+
+ Outer_Demo.Nested_Demo nested = new Outer_Demo.Nested_Demo();
+ // my_method() is a instance variable
+ nested.my_method();
+
+ }
+}
diff --git a/src/com/p2/classMembers/Outer_Demo.java b/src/com/p2/classMembers/Outer_Demo.java
new file mode 100644
index 0000000..fec955b
--- /dev/null
+++ b/src/com/p2/classMembers/Outer_Demo.java
@@ -0,0 +1,36 @@
+package com.p2.classMembers;
+
+class Outer_Demo {
+ // private variable of the outer class
+ private int num = 175;
+
+ // inner global class
+ public class Inner_Demo {
+ public int getNum() {
+ System.out.println("This is the getnum method of the inner class");
+ return num;
+ }
+ }
+
+ // static inner global class
+ static class Nested_Demo {
+ public void my_method() {
+ System.out.println("This is my nested class");
+ }
+ }
+
+ void my_Method() {
+ final int num = 23;
+ // method-local inner class
+
+ class MethodInner_Demo {
+ public void print() {
+ System.out.println("This is method inner class " + num);
+ }
+ } // end of inner class
+ // Accessing the inner class
+ MethodInner_Demo inner = new MethodInner_Demo();
+ inner.print();
+ }
+
+}
diff --git a/src/com/p2/client/CassandraClient.java b/src/com/p2/client/CassandraClient.java
new file mode 100644
index 0000000..a3cd715
--- /dev/null
+++ b/src/com/p2/client/CassandraClient.java
@@ -0,0 +1,48 @@
+package com.p2.client;
+
+public class CassandraClient {
+
+ public static void main(String[] args) {
+
+ }
+
+}
+
+class CassandraConnector {
+
+ private Cluster cluster;
+
+ private Session session;
+
+ public static void connect(String node, Integer port) {
+ Builder b = Cluster.builder().addContactPoint(node);
+ if (port != null) {
+ b.withPort(port);
+ }
+ cluster = b.build();
+
+ session = cluster.connect();
+ }
+
+ public static Session getSession() {
+ return this.session;
+ }
+
+ public static void close() {
+ session.close();
+ cluster.close();
+ }
+
+ public void createKeyspace(String keyspaceName, String replicationStrategy,
+ int replicationFactor) {
+ StringBuilder sb = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ")
+ .append(keyspaceName).append(" WITH replication = {")
+ .append("'class':'").append(replicationStrategy)
+ .append("','replication_factor':").append(replicationFactor)
+ .append("};");
+
+ String query = sb.toString();
+ session.execute(query);
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/p2/client/NetClientGet.java b/src/com/p2/client/NetClientGet.java
new file mode 100644
index 0000000..bec6902
--- /dev/null
+++ b/src/com/p2/client/NetClientGet.java
@@ -0,0 +1,53 @@
+package com.p2.client;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+public class NetClientGet {
+
+ public static void main(String[] args) {
+ String url = "http://localhost:8080/RESTfulExample/json/product/get";
+ // How to convert json payload into JavaObject
+ }
+
+}
+
+class JavaRestClient {
+
+ public static void httpGet(String url, String method) {
+
+ try {
+
+ URL finalUrl = new URL(url);
+ HttpURLConnection conn = (HttpURLConnection) finalUrl
+ .openConnection();
+ conn.setRequestMethod("GET");
+ conn.setRequestProperty("Accept", "application/json");
+
+ if (conn.getResponseCode() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + conn.getResponseCode());
+ }
+
+ BufferedReader br = new BufferedReader(new InputStreamReader(
+ (conn.getInputStream())));
+
+ String output;
+ System.out.println("Output from Server .... \n");
+ while ((output = br.readLine()) != null) {
+ System.out.println(output);
+ }
+
+ conn.disconnect();
+
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/p2/client/package-info.java b/src/com/p2/client/package-info.java
new file mode 100644
index 0000000..01fa0ed
--- /dev/null
+++ b/src/com/p2/client/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.client;
\ No newline at end of file
diff --git a/src/com/p2/collections/ArraysEx.java b/src/com/p2/collections/ArraysEx.java
new file mode 100644
index 0000000..2b1ddcb
--- /dev/null
+++ b/src/com/p2/collections/ArraysEx.java
@@ -0,0 +1,45 @@
+package com.p2.collections;
+
+import java.util.Arrays;
+
+public class ArraysEx {
+
+ public static void main(String[] args) {
+ int arr1[] = { 1, 2, 3 };
+ int arr2[] = { 1, 2, 3 };
+ // The constructor Arrays(int) is undefined that means its constructor
+ // is private for non-instantiation
+ // Arrays arrays = new Arrays();
+ // arrays = {1,2,3,4,5,6};
+ int a[] = new int[4];
+ a[0] = 2;
+ a[1] = 2;
+ a[2] = 2;
+ a[3] = 2;
+ // gives array out of bound exception
+ // a[4]=7;
+
+ int b[] = new int[4];
+ b[0] = 2;
+ b[1] = 2;
+ b[2] = 2;
+ b[3] = 2;
+
+ System.out.println(a[3]);
+ // Arrays equality comparison
+ System.out.println(Arrays.equals(a, b));
+ System.out.println(Arrays.equals(arr1, arr2));
+ System.out.println(3 << 2);
+
+ }
+
+}
+
+
+
+
+
+
+
+
+
diff --git a/src/com/p2/collections/CollectionEx.java b/src/com/p2/collections/CollectionEx.java
new file mode 100644
index 0000000..022865a
--- /dev/null
+++ b/src/com/p2/collections/CollectionEx.java
@@ -0,0 +1,31 @@
+package com.p2.collections;
+
+//Java program to show whey collection framework was needed
+import java.io.*;
+import java.util.*;
+
+class CollectionEx {
+ public static void main(String[] args) {
+ // Creating instances of array, vector and hashtable
+ int arr[] = new int[] { 1, 2, 3, 4 };
+ Vector v = new Vector();
+ Hashtable h = new Hashtable();
+ v.addElement(1);
+ v.addElement(2);
+ h.put(1, "geeks");
+ h.put(2, "4geeks");
+
+ // Array instance creation requires [], while Vector
+ // and hastable require ()
+ // Vector element insertion requires addElement(), but
+ // hashtable element insertion requires put()
+
+ // Accessing first element of array, vector and hashtable
+ System.out.println(arr[0]);
+ System.out.println(v.elementAt(0));
+ System.out.println(h.get(1));
+
+ // Array elements are accessed using [], vector elements
+ // using elementAt() and hashtable elements using get()
+ }
+}
diff --git a/src/com/p2/collections/CollectionsClassExample.java b/src/com/p2/collections/CollectionsClassExample.java
new file mode 100644
index 0000000..c306eed
--- /dev/null
+++ b/src/com/p2/collections/CollectionsClassExample.java
@@ -0,0 +1,78 @@
+package com.p2.collections;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+public class CollectionsClassExample {
+
+ public static void main(String[] args) {
+
+ try {
+ UseOfCollections.addAll();
+ UseOfCollections.max();
+ } catch (Exception e) {
+ System.out.println(e.getClass());
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+class UseOfCollections {
+
+ static Integer[] intArray = { 78, 45, 23, 69, 85, 21, 47, 86 };
+ static List l0, l1, l2, l3;
+
+ static void addAll() {
+ try {
+ l0 = (List) Arrays.asList(intArray);
+ // Addition of new element will throw class
+ // java.lang.UnsupportedOperationException
+ Collections.addAll(l0, 78, 12);
+
+ } catch (Exception e) {
+ print(e, "Add All");
+ l1 = new ArrayList();
+ Collections.copy(l1, l0);
+ print(l1, "Copy");
+ }
+ }
+
+ static void copy() {
+
+ try {
+
+ } catch (Exception e) {
+
+ }
+ }
+
+ static void max() {
+ l2 = (List) Arrays.asList(intArray);
+ print(Collections.max(l2), "Max");
+ }
+
+ static void synchronizationInCollection() {
+
+ l3 = (List) Arrays.asList(intArray);
+ List cwa = new CopyOnWriteArrayList();
+
+ Collections.synchronizedCollection(l3);
+ Collections.frequency(l3, 4);
+
+ }
+
+ static void print(T obj, String methodName) {
+ System.out.println("Method Name: " + methodName);
+ if (obj instanceof List) {
+ List ll = (List) obj;
+ for (T integer : ll) {
+ System.out.println(integer);
+ }
+ } else {
+ System.out.println(obj);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/p2/collections/ComparableEx.java b/src/com/p2/collections/ComparableEx.java
new file mode 100644
index 0000000..30be5d8
--- /dev/null
+++ b/src/com/p2/collections/ComparableEx.java
@@ -0,0 +1,60 @@
+package com.p2.collections;
+
+// An example demonstrating use of comparable
+//A Java program to demonstrate use of Comparable
+/* step -1 , make your class implements Comparable
+ * Step -2, Provide implementation to compareTo method
+ * Only single implementation is possible in this case */
+
+import java.util.*;
+
+// Driver class
+public class ComparableEx extends Object {
+ public static void main(String[] args) {
+ ArrayList list = new ArrayList();
+ list.add(new Movie("Force Awakens", 8.3, 2015));
+ list.add(new Movie("Star Wars", 8.7, 1977));
+ list.add(new Movie("Empire Strikes Back", 8.8, 1980));
+ list.add(new Movie("Return of the Jedi", 8.4, 1983));
+
+ Collections.sort(list);
+
+ System.out.println("Movies after sorting : ");
+ for (Movie movie : list) {
+ System.out.println(movie.getName() + " " + movie.getRating() + " "
+ + movie.getYear());
+ }
+ }
+}
+
+// A class 'Movie' that implements Comparable
+class Movie implements Comparable {
+ private double rating;
+ private String name;
+ private int year;
+
+ // Used to sort movies by year
+ public int compareTo(Movie m) {
+ return this.year - m.year;
+ }
+
+ // Constructor
+ public Movie(String nm, double rt, int yr) {
+ this.name = nm;
+ this.rating = rt;
+ this.year = yr;
+ }
+
+ // Getter methods for accessing private data
+ public double getRating() {
+ return rating;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getYear() {
+ return year;
+ }
+}
\ No newline at end of file
diff --git a/src/com/p2/collections/ComparatorEx.java b/src/com/p2/collections/ComparatorEx.java
new file mode 100644
index 0000000..37d383c
--- /dev/null
+++ b/src/com/p2/collections/ComparatorEx.java
@@ -0,0 +1,70 @@
+package com.p2.collections;
+
+/**
+ * Java program to demonstrate working of Comparator interface
+ * override compare
+ * an extra class is required for sorting
+ */
+
+import java.util.*;
+
+// A class to represent a student.
+class Student {
+ int rollno;
+ String name, address;
+
+ // Constructor
+ public Student(int rollno, String name, String address) {
+ this.rollno = rollno;
+ this.name = name;
+ this.address = address;
+ }
+
+ // Used to print student details in main()
+ public String toString() {
+ return this.rollno + " " + this.name + " " + this.address;
+ }
+}
+
+class Sortbyroll implements Comparator {
+ // Used for sorting in ascending order of
+ // roll number
+ public int compare(Student a, Student b) {
+ return a.rollno - b.rollno;
+ }
+}
+
+class Sortbyname implements Comparator {
+ // Used for sorting in ascending order of
+ // roll name
+ public int compare(Student a, Student b) {
+ // use compareTo on string
+ return a.name.compareTo(b.name);
+ }
+}
+
+// Driver class
+public class ComparatorEx {
+ public static void main(String[] args) {
+ ArrayList ar = new ArrayList();
+ ar.add(new Student(111, "bbbb", "london"));
+ ar.add(new Student(131, "aaaa", "nyc"));
+ ar.add(new Student(121, "cccc", "jaipur"));
+
+ System.out.println("Unsorted");
+ for (int i = 0; i < ar.size(); i++)
+ System.out.println(ar.get(i));
+
+ // Sorting By roll Number
+ Collections.sort(ar, new Sortbyroll());
+ System.out.println("\nSorted by rollno");
+ for (int i = 0; i < ar.size(); i++)
+ System.out.println(ar.get(i));
+
+ // Sorting By name
+ Collections.sort(ar, new Sortbyname());
+ System.out.println("\nSorted by name");
+ for (int i = 0; i < ar.size(); i++)
+ System.out.println(ar.get(i));
+ }
+}
diff --git a/src/com/p2/collections/InnerClassInInterface.java b/src/com/p2/collections/InnerClassInInterface.java
new file mode 100644
index 0000000..67bbaf2
--- /dev/null
+++ b/src/com/p2/collections/InnerClassInInterface.java
@@ -0,0 +1,10 @@
+package com.p2.collections;
+
+public interface InnerClassInInterface {
+
+
+ public class TestClass{}
+
+
+
+}
diff --git a/src/com/p2/collections/ListIteratorEx.java b/src/com/p2/collections/ListIteratorEx.java
new file mode 100644
index 0000000..4dc95e9
--- /dev/null
+++ b/src/com/p2/collections/ListIteratorEx.java
@@ -0,0 +1,40 @@
+package com.p2.collections;
+
+//Java program to demonstrate ListIterator
+import java.util.ArrayList;
+import java.util.ListIterator;
+
+public class ListIteratorEx {
+ public static void main(String[] args) {
+ ArrayList al = new ArrayList();
+ for (int i = 0; i < 10; i++)
+ al.add(i);
+ System.out.println(al);
+
+ // at beginning ltr(cursor) will point to
+ // index just before the first element in al
+ ListIterator ltr = al.listIterator();
+
+ al.forEach (e -> System.out.println(e + "------18") );
+
+ // checking the next element availabilty
+ while (ltr.hasNext()) {
+ // moving cursor to next element
+ int i = (Integer) ltr.next();
+
+ // getting even elements one by one
+ System.out.print(i + " ");
+
+ // Changing even numbers to odd and
+ // adding modified number again in
+ // iterator
+ if (i % 2 == 0) {
+ i++; // Change to odd
+ ltr.set(i); // set method to change value
+ ltr.add(i); // to add
+ }
+ }
+ System.out.println();
+ System.out.println(al);
+ }
+}
diff --git a/src/com/p2/collections/SetExample.java b/src/com/p2/collections/SetExample.java
new file mode 100644
index 0000000..f2bca53
--- /dev/null
+++ b/src/com/p2/collections/SetExample.java
@@ -0,0 +1,25 @@
+package com.p2.collections;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+public class SetExample {
+
+ public static void main(String[] args) {
+
+ Set set = new TreeSet();
+ //Set set = new HashSet();
+ set.add(23);
+ set.add(35);
+ set.add(56);
+ set.add(78);
+ // null can not be stored in sorted set
+ set.add(null);
+
+ for (Integer integer : set) {
+ System.out.println(integer);
+ }
+
+ }
+
+}
diff --git a/src/com/p2/collections/generics/BaseDao.java b/src/com/p2/collections/generics/BaseDao.java
new file mode 100644
index 0000000..7bf3505
--- /dev/null
+++ b/src/com/p2/collections/generics/BaseDao.java
@@ -0,0 +1,64 @@
+package com.p2.collections.generics;
+
+import java.io.Serializable;
+import java.lang.reflect.ParameterizedType;
+
+
+
+/**
+ *
+ * @author pradeep_patel
+ *
+ * @param
+ * @param
+ * Performs Generic CRUD that do not need specialized handling. All
+ * Dao should extend this class and at the same time implement
+ * Interfaces
+ * Generic are being used here
+ */
+public abstract class BaseDao {
+
+ public final Class persistentClass;
+
+ @SuppressWarnings("unchecked")
+ public BaseDao() {
+ this.persistentClass = (Class) ((ParameterizedType) this.getClass()
+ .getGenericSuperclass()).getActualTypeArguments()[1];
+ }
+
+ //@Autowired
+ //private SessionFactory sessionFactory;
+
+ /*public Session getSession() throws Exception {
+ try {
+ return sessionFactory.getCurrentSession();
+ } catch (Exception e) {
+ throw e;
+ }
+
+ }*/
+
+ @SuppressWarnings("unchecked")
+ public T getByKey(PK key) throws Exception {
+ return null; //(T) getSession().get(persistentClass, key);
+ }
+
+ public void persist(T entity) throws Exception {
+ //getSession().persist(entity);
+
+ }
+
+ public void update(T entity) throws Exception {
+ //getSession().update(entity);
+
+ }
+
+ public void delete(T entity) throws Exception {
+ //getSession().delete(entity);
+ }
+
+ /*protected Criteria createEntityCriteria() throws Exception {
+ return null; //getSession().createCriteria(persistentClass);
+ }*/
+
+}
diff --git a/src/com/p2/collections/generics/BoundedClass.java b/src/com/p2/collections/generics/BoundedClass.java
new file mode 100644
index 0000000..facd569
--- /dev/null
+++ b/src/com/p2/collections/generics/BoundedClass.java
@@ -0,0 +1,68 @@
+package com.p2.collections.generics;
+
+
+public class BoundedClass {
+ public static void main(String a[]) {
+
+ // Creating object of sub class C and
+ // passing it to Bound as a type parameter.
+ Bound bec = new Bound(new C());
+ bec.doRunTest();
+
+ // Creating object of sub class B and
+ // passing it to Bound as a type parameter.
+ Bound beb = new Bound(new B());
+ beb.doRunTest();
+
+ // similarly passing super class A
+ Bound bea = new Bound(new A());
+ bea.doRunTest();
+
+ }
+}
+/**
+ * This class only accepts type parametes as any class
+ * which extends class A or class A itself.
+ * Passing any other type will cause compiler time error
+ * @author pradeep_patel
+ *
+ * @param
+ */
+
+/**
+ * There may be times when you want to restrict the types that can be used as type arguments
+ * in a parameterized type. For example, a method that operates on numbers might only want to
+ * accept instances of Number or its subclasses. This is what bounded type parameters are for.
+ */
+
+class Bound {
+
+ private T objRef;
+
+ public Bound(T obj) {
+ this.objRef = obj;
+ }
+
+ public void doRunTest() {
+ this.objRef.displayClass();
+ }
+}
+
+class A {
+ public void displayClass() {
+ System.out.println("Inside super class A");
+ }
+}
+
+class B extends A {
+ public void displayClass() {
+ System.out.println("Inside sub class B");
+ }
+}
+
+class C extends A {
+ public void displayClass() {
+ System.out.println("Inside sub class C");
+ }
+}
+
diff --git a/src/com/p2/collections/generics/GenericsEx.java b/src/com/p2/collections/generics/GenericsEx.java
new file mode 100644
index 0000000..9bd8af8
--- /dev/null
+++ b/src/com/p2/collections/generics/GenericsEx.java
@@ -0,0 +1,166 @@
+package com.p2.collections.generics;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * https://docs.oracle.com/javase/tutorial/java/generics/
+ * @author pradeep_patel
+ *
+ */
+public class GenericsEx {
+
+ public static void main(String[] args) {
+
+ // instance of Integer type
+ Test iObj = new Test(15);
+ System.out.println(iObj.getObject());
+
+ // instance of String type
+ Test sObj = new Test("GeeksForGeeks");
+ System.out.println(sObj.getObject());
+ // Calling generic method with Integer argument
+ Test00.genericDisplay(11);
+
+ // Calling generic method with String argument
+ Test00.genericDisplay("GeeksForGeeks");
+
+ // Calling generic method with double argument
+ Test00.genericDisplay(1.0);
+
+ ArrayList< Integer> al = new ArrayList();
+ al.add(89);
+ Test000 tt = new Test000(al);
+ }
+}
+
+// A Simple Java program to show working of user defined
+// Generic classes
+// We use < > to specify Parameter type
+
+/**
+ * To create an instance of generic class BaseType obj = new BaseType ()
+ Note: In Parameter type we can not use primitives like 'int','char' or 'double'.*
+ *
+ * @author pradeep_patel
+ *
+ * @param
+ */
+
+
+
+class Test {
+ // An object of type T is declared
+ T obj;
+
+ Test(T obj) {
+ this.obj = obj;
+ } // constructor
+
+ public T getObject() {
+ return this.obj;
+ }
+
+ // We use < > to specify Parameter type
+ class Testt {
+ T obj1; // An object of type T
+ U obj2; // An object of type U
+
+ // constructor
+ Testt(T obj1, U obj2) {
+ this.obj1 = obj1;
+ this.obj2 = obj2;
+ }
+ // To print objects of T and U
+ public void print() {
+ System.out.println(obj1);
+ System.out.println(obj2);
+ }
+ }
+}
+
+class Test000 {
+
+ List l;
+
+ Test000(List obj) {
+ this.l = obj;
+ }
+
+ List getList() {
+ return this.l;
+ }
+}
+
+/**
+ *
+ * @author pradeep_patel
+ *Either mention generic at class level or at method level as shown below
+ */
+
+class Test00 {
+ // A Generic method example either or any Letter like
+ public T genericPrint(T element) {
+ System.out.println(element.getClass().getName() + " = " + element);
+ return element;
+ }
+
+ public static void genericDisplay(T element){
+ System.out.println(element.getClass().getName() + " = " + element);
+ }
+}
+
+/**
+Advantages of Generics:
+
+1. Programs that uses Generics has got many benefits over non-generic code.
+
+2. Code Reuse: We can write a method/class/interface once and use for any type we want.
+
+Type Safety : Generics make errors to appear compile time than at run time
+(It’s always better to know problems in your code at compile time rather than making your code fail at run time).
+Suppose you want to create an ArrayList that store name of students and if by mistake programmer adds an integer
+object instead of string, compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime.
+
+* We generally use generics while writing AbstractDao
+*
+*
+3. Individual Type Casting is not needed: If we do not use generics, then, in the above example every-time we
+ retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache.
+ If we already know that our list only holds string data then we need not to typecast it every time.
+*/
+
+class TestWithoutGenerics {
+ @SuppressWarnings("unchecked")
+ public static void main(String[] args) {
+ // Creatinga an ArrayList without any type specified
+ List al = new ArrayList();
+
+ al.add("Sachin");
+ al.add("Rahul");
+ al.add(10); // Compiler allows this
+
+ String s1 = (String) al.get(0);
+ String s2 = (String) al.get(1);
+
+ // Causes Runtime Exception
+ String s3 = (String) al.get(2);
+ }
+}
+
+class TestWithGenerics {
+ public static void main(String[] args) {
+ // Creating a an ArrayList with String specified
+ ArrayList al = new ArrayList();
+
+ al.add("Sachin");
+ al.add("Rahul");
+
+ // Now Compiler doesn't allow this
+ //al.add(10);
+
+ String s1 = (String) al.get(0);
+ String s2 = (String) al.get(1);
+ String s3 = (String) al.get(2);
+ }
+}
diff --git a/src/com/p2/collections/generics/MaximumTest.java b/src/com/p2/collections/generics/MaximumTest.java
new file mode 100644
index 0000000..ea507e7
--- /dev/null
+++ b/src/com/p2/collections/generics/MaximumTest.java
@@ -0,0 +1,29 @@
+package com.p2.collections.generics;
+
+public class MaximumTest {
+ // determines the largest of three Comparable objects
+
+ public static > T maximum(T x, T y, T z) {
+ T max = x; // assume x is initially the largest
+
+ if (y.compareTo(max) > 0) {
+ max = y; // y is the largest so far
+ }
+
+ if (z.compareTo(max) > 0) {
+ max = z; // z is the largest now
+ }
+ return max; // returns the largest object
+ }
+
+ public static void main(String args[]) {
+ System.out.printf("Max of %d, %d and %d is %d\n\n", 3, 4, 5,
+ maximum(3, 4, 5));
+
+ System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8,
+ 7.7, maximum(6.6, 8.8, 7.7));
+
+ System.out.printf("Max of %s, %s and %s is %s\n", "pear", "apple",
+ "orange", maximum("pear", "apple", "orange"));
+ }
+}
diff --git a/src/com/p2/collections/generics/package-info.java b/src/com/p2/collections/generics/package-info.java
new file mode 100644
index 0000000..5915300
--- /dev/null
+++ b/src/com/p2/collections/generics/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.collections.generics;
\ No newline at end of file
diff --git a/src/com/p2/collections/hashmap/HashCodeAndEquals.java b/src/com/p2/collections/hashmap/HashCodeAndEquals.java
new file mode 100644
index 0000000..48defdb
--- /dev/null
+++ b/src/com/p2/collections/hashmap/HashCodeAndEquals.java
@@ -0,0 +1,121 @@
+package com.p2.collections.hashmap;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+// Demonstrates how to override Hascode() and equals()
+// what happens when storing equal objects in HashMap
+class Students {
+
+ private Integer rollNumber;
+ private String schoolName;
+ private Integer standard;
+
+ public Integer getRollNumber() {
+ return rollNumber;
+ }
+
+ public void setRollNumber(Integer rollNumber) {
+ this.rollNumber = rollNumber;
+ }
+
+ public String getSchoolName() {
+ return schoolName;
+ }
+
+ public void setSchoolName(String schoolName) {
+ this.schoolName = schoolName;
+ }
+
+ public Integer getStandard() {
+ return standard;
+ }
+
+ public void setStandard(Integer standard) {
+ this.standard = standard;
+ }
+
+ public Students(Integer rollNumber, String schoolName, Integer standard) {
+ super();
+ this.rollNumber = rollNumber;
+ this.schoolName = schoolName;
+ this.standard = standard;
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 * this.rollNumber + 7;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) { // checking references
+ return true;
+ } else if (obj == null) { // checking null
+ return false;
+ } else if (obj instanceof Students) {
+ Students stu = (Students) obj;
+ if ((stu.getRollNumber() == null && this.getRollNumber() == null)
+ || (stu.getRollNumber().equals(this.getRollNumber()) && ((stu
+ .getSchoolName() == null && this.schoolName == null) || stu
+ .getSchoolName().equals(this.schoolName)))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+
+ return this.getSchoolName();
+ }
+
+}
+
+public class HashCodeAndEquals {
+
+ public static void main(String[] args) {
+
+ Students stu0 = new Students(123, "Saint Xaviour", 1);
+ Students stu1 = new Students(123, "XLRI", 2);
+ // this will override the the value for previous key since the objects
+ // are equal based on roll number and and school name
+ Students stu2 = new Students(123, "XLRI", 3);
+
+ Map map = new HashMap();
+ map.put(stu0, 1);
+ map.put(stu1, 2);
+ map.put(stu2, 3);
+ map.put(null, 4);
+
+ // Map.Entry e = (Entry)
+ // map.entrySet();
+
+ Set stus = (Set) map.keySet();
+
+ for (Students students : stus) {
+ // System.out.println(students.hashCode());
+ System.out.println(map.get(students));
+ }
+
+ System.out.println("\nUsing Entry set");
+ for (Map.Entry e : map.entrySet()) {
+ System.out.print(e.getKey() + " : " + e.getValue());
+ System.out.println(" ");
+ }
+
+
+ System.out.println("\nUsing Iterator ");
+ Iterator> it = map.entrySet().iterator();
+ while (it.hasNext()) {
+ // it.next returns entry
+ Map.Entry entry = it.next();
+ System.out.print(entry.getKey() + " : " + entry.getValue());
+ System.out.println(" ");
+ }
+ }
+}
diff --git a/src/com/p2/collections/hashmap/MapExIteration.java b/src/com/p2/collections/hashmap/MapExIteration.java
new file mode 100644
index 0000000..fe9c933
--- /dev/null
+++ b/src/com/p2/collections/hashmap/MapExIteration.java
@@ -0,0 +1,75 @@
+package com.p2.collections.hashmap;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+public class MapExIteration {
+
+ // various ways of iterationg over Map
+ //https://stackoverflow.com/questions/46898/how-to-efficiently-iterate-over-each-entry-in-a-map
+
+ public static void main(String[] args) {
+
+ Map map0 = new HashMap();
+ map0.put(1, "Harsih");
+ map0.put(2, "Suresh");
+ map0.put(3, "Mahesh");
+ map0.put(4, "Jignesh");
+
+ // For Each with Entry Set
+ for (Map.Entry e : map0.entrySet()) {
+ System.out.print(e.getKey() + ":");
+ System.out.println(e.getValue());
+ }
+
+ // For Each with Key Set
+ System.out.println("--------------------------------------------- 25");
+ String i = "0";
+ for (Integer key : map0.keySet()) {
+ i += key + map0.get(key);
+ System.out.println(i);
+ }
+
+ // Iterator
+ System.out.println("--------------------------------------------- 32");
+ Iterator> it = map0.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry pair = it.next();
+ System.out.println(pair.getKey() + ":" + pair.getValue());
+ }
+
+ final String[] j = { "0" };
+ StringBuffer b = new StringBuffer();
+ System.out.println("--------------------------------------------- 42");
+ map0.forEach((k, v) -> b.append(k + v));
+ System.out.println(b);
+
+ /*long i = 0;
+ MapIterator it = iterableMap.mapIterator();
+ while (it.hasNext()) {
+ i += it.next() + it.getValue();
+ }*/
+
+ // Without Generics
+ Map map = new HashMap();
+ Iterator entries = map.entrySet().iterator();
+ while (entries.hasNext()) {
+ Map.Entry entry = (Map.Entry) entries.next();
+ Integer key = (Integer)entry.getKey();
+ Integer value = (Integer)entry.getValue();
+ System.out.println("Key = " + key + ", Value = " + value);
+ }
+
+ //iterating over keys only
+ for (Integer key : map0.keySet()) {
+ System.out.println("Key = " + key);
+ }
+
+ //iterating over values only
+ for (String value : map0.values()) {
+ System.out.println("Value = " + value);
+ }
+
+ }
+}
diff --git a/src/com/p2/collections/hashmap/package-info.java b/src/com/p2/collections/hashmap/package-info.java
new file mode 100644
index 0000000..6eea2ba
--- /dev/null
+++ b/src/com/p2/collections/hashmap/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.collections.hashmap;
\ No newline at end of file
diff --git a/src/com/p2/collections/list/CollectionExamples.java b/src/com/p2/collections/list/CollectionExamples.java
new file mode 100644
index 0000000..ada14bd
--- /dev/null
+++ b/src/com/p2/collections/list/CollectionExamples.java
@@ -0,0 +1,76 @@
+package com.p2.collections.list;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+
+public class CollectionExamples {
+
+ public static void main(String[] args) {
+ VectorEx.iterateVector();
+ }
+}
+
+/**
+ * http://javaconceptoftheday.com/differences-between-enumeration-vs-iterator-in-java/
+ * @author pradeep_patel The Vector class provides the capability to implement a
+ * growable array of objects
+ * Mind the difference between Vector and List
+ * When using List you will see only list interface methods See use of
+ * enumeration
+ * to use vector enumeration use reference of Vector type and not List type
+ */
+class VectorEx {
+
+ static Integer ints[] = {1,2,3,4,6,9,5};
+ static void iterateVector() {
+ List listVal = Arrays.asList(ints);
+ // -----------------------------List with Vector as implementation
+ // ----------------------
+ List vector = new Vector();
+ vector.addAll(listVal);
+ vector.add(23);
+ vector.add(45);
+
+ for (Integer integer : vector) {
+ System.out.println(integer);
+ }
+
+ System.out.println("Using Iterator --------->");
+ Iterator it = vector.iterator();
+
+ while (it.hasNext()) {
+ System.out.println(it.next());
+ }
+
+
+ List list = new Vector(vector);
+ Iterator its = list.iterator();
+ System.out.println("Remove Example using iterator --------->");
+ while (its.hasNext()) {
+ System.out.println(its.next());
+ its.remove();
+
+ }
+
+ // -----------------------------using vector class
+ // ----------------------
+ Vector tvsvector = new Vector();
+ tvsvector.addAll(vector);
+
+ System.out.println("Using Enumeration --------->");
+ Enumeration en = tvsvector.elements();
+
+ while (en.hasMoreElements()) {
+ System.out.println(en.nextElement());
+ }
+
+ System.out.println("Using for each in vector --------->");
+ for (Integer integer : tvsvector) {
+ System.out.println(integer);
+ }
+ }
+}
diff --git a/src/com/p2/collections/list/package-info.java b/src/com/p2/collections/list/package-info.java
new file mode 100644
index 0000000..b7b5bef
--- /dev/null
+++ b/src/com/p2/collections/list/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.collections.list;
\ No newline at end of file
diff --git a/src/com/p2/collections/package-info.java b/src/com/p2/collections/package-info.java
new file mode 100644
index 0000000..28d6171
--- /dev/null
+++ b/src/com/p2/collections/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.collections;
\ No newline at end of file
diff --git a/src/com/p2/constructors/Box.java b/src/com/p2/constructors/Box.java
new file mode 100644
index 0000000..ec21b2c
--- /dev/null
+++ b/src/com/p2/constructors/Box.java
@@ -0,0 +1,37 @@
+package com.p2.constructors;
+
+//Java program to illustrate role of this() in
+//Constructor Overloading
+class Box {
+ double width, height, depth;
+ int boxNo;
+ // constructor used when all dimensions and
+ // boxNo specified
+ Box(double w, double h, double d, int num) {
+ width = w;
+ height = h;
+ depth = d;
+ boxNo = num;
+ }
+
+ // constructor used when no dimensions specified
+ Box() {
+ // an empty box
+ width = height = depth = 0;
+ System.out.println("Line 21------------------------->");
+ }
+
+ // constructor used when only boxNo specified
+ Box(int num) {
+ // this() is used for calling the default constructor from parameterized constructor
+ this();
+ boxNo = num;
+ }
+
+ public static void main(String[] args) {
+ // create box using only boxNo
+ Box box1 = new Box(1);
+ // getting initial width of box1
+ System.out.println(box1.width);
+ }
+}
diff --git a/src/com/p2/constructors/package-info.java b/src/com/p2/constructors/package-info.java
new file mode 100644
index 0000000..9934cf4
--- /dev/null
+++ b/src/com/p2/constructors/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.constructors;
\ No newline at end of file
diff --git a/src/com/p2/designpatterns/BillPughSingleton.java b/src/com/p2/designpatterns/BillPughSingleton.java
new file mode 100644
index 0000000..7822646
--- /dev/null
+++ b/src/com/p2/designpatterns/BillPughSingleton.java
@@ -0,0 +1,31 @@
+package com.p2.designpatterns;
+
+//Java code for Bill Pugh Singleton Implementaion;
+class SingletonClass {
+
+ private SingletonClass() {
+ System.out.println("I am inside constructor ----------------------- > ");
+ }
+
+ // Inner class to provide instance of class
+ private static class BillPughSingleton {
+ private static final SingletonClass INSTANCE = new SingletonClass();
+ }
+
+ public static SingletonClass getInstance() {
+ return BillPughSingleton.INSTANCE;
+ }
+}
+
+public class BillPughSingleton {
+ public static void main(String[] args) {
+ SingletonClass singleton = SingletonClass.getInstance();
+ }
+}
+
+
+/*When the singleton class is loaded, inner class is not loaded and hence doesn’t create object when loading the class.
+ * Inner class is created only when getInstance() method is called. So it may seem like eager initialization but
+ * it is lazy initialization. This is the most widely used approach as it doesn’t use synchronization.
+ *
+ * */
diff --git a/src/com/p2/designpatterns/JDBCSingletonDemo.java b/src/com/p2/designpatterns/JDBCSingletonDemo.java
new file mode 100644
index 0000000..26f74e1
--- /dev/null
+++ b/src/com/p2/designpatterns/JDBCSingletonDemo.java
@@ -0,0 +1,292 @@
+package com.p2.designpatterns;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+class JDBCSingleton {
+ // Step 1
+ // create a JDBCSingleton class.
+ // static member holds only one instance of the JDBCSingleton class.
+
+ private static JDBCSingleton jdbc;
+
+ // JDBCSingleton prevents the instantiation from any other class.
+ private JDBCSingleton() {}
+
+ // Now we are providing gloabal point of access to create an instance.
+ // We will call this method on Class name to create an instance of JDBC
+ public static JDBCSingleton getInstance() {
+ if (jdbc == null) {
+ jdbc = new JDBCSingleton();
+ }
+ return jdbc;
+ }
+
+ // To get the connection from methods like insert, view etc.
+ private static Connection getConnection() throws ClassNotFoundException, SQLException {
+ Connection con = null;
+ Class.forName("com.mysql.jdbc.Driver");
+ con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
+ return con;
+ }
+
+ // To insert the record into the database
+ public int insert(String name, String pass) throws SQLException {
+ Connection c = null;
+ PreparedStatement ps = null;
+ int recordCounter = 0;
+
+ try {
+ c = this.getConnection();
+ ps = c.prepareStatement("insert into userdata(uname,upassword)values(?,?)");
+ ps.setString(1, name);
+ ps.setString(2, pass);
+ recordCounter = ps.executeUpdate();
+
+ } catch (Exception e) {
+ e.printStackTrace();
+
+ } finally {
+ if (ps != null) {
+ ps.close();
+ }
+ if (c != null) {
+ c.close();
+ }
+
+ }
+ return recordCounter;
+ }
+
+ // to view the data from the database
+ public void view(String name) throws SQLException {
+ Connection con = null;
+ PreparedStatement ps = null;
+ ResultSet rs = null;
+
+ try {
+
+ con = this.getConnection();
+ ps = con.prepareStatement("select * from userdata where uname=?");
+ ps.setString(1, name);
+ rs = ps.executeQuery();
+ while (rs.next()) {
+ System.out.println("Name= " + rs.getString(2) + "\t"
+ + "Paasword= " + rs.getString(3));
+
+ }
+
+ } catch (Exception e) {
+ System.out.println(e);
+
+ } finally {
+ if (rs != null) {
+ rs.close();
+ }
+ if (ps != null) {
+ ps.close();
+ }
+ if (con != null) {
+ con.close();
+ }
+
+ }
+ }
+
+ // to update the password for the given username
+ public int update(String name, String password) throws SQLException {
+ Connection c = null;
+
+ PreparedStatement ps = null;
+
+ int recordCounter = 0;
+
+ try {
+
+ c = this.getConnection();
+ ps = c.prepareStatement(" update userdata set upassword=? where uname='"
+ + name + "' ");
+ ps.setString(1, password);
+ recordCounter = ps.executeUpdate();
+
+ } catch (Exception e) {
+
+ e.printStackTrace();
+
+ } finally {
+
+ if (ps != null) {
+ ps.close();
+ }
+ if (c != null) {
+ c.close();
+ }
+
+ }
+
+ return recordCounter;
+ }
+
+ // to delete the data from the database
+ public int delete(int userid) throws SQLException {
+ Connection c = null;
+
+ PreparedStatement ps = null;
+
+ int recordCounter = 0;
+
+ try {
+
+ c = this.getConnection();
+ ps = c.prepareStatement(" delete from userdata where uid='"
+ + userid + "' ");
+
+ recordCounter = ps.executeUpdate();
+
+ } catch (Exception e) {
+
+ e.printStackTrace();
+
+ } finally {
+
+ if (ps != null) {
+ ps.close();
+ }
+ if (c != null) {
+ c.close();
+ }
+
+ }
+
+ return recordCounter;
+ }
+
+}// End of JDBCSingleton class
+
+public class JDBCSingletonDemo {
+ static int count = 1;
+ static int choice;
+
+ public static void main(String[] args) throws IOException {
+
+ JDBCSingleton jdbc = JDBCSingleton.getInstance();
+
+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
+ do {
+ System.out.println("DATABASE OPERATIONS");
+ System.out.println(" --------------------- ");
+ System.out.println(" 1. Insertion ");
+ System.out.println(" 2. View ");
+ System.out.println(" 3. Delete ");
+ System.out.println(" 4. Update ");
+ System.out.println(" 5. Exit ");
+
+ System.out.print("\n");
+
+ System.out
+ .print("Please enter the choice what you want to perform in the database: ");
+
+ choice = Integer.parseInt(br.readLine());
+
+ switch (choice) {
+
+ case 1: {
+ System.out
+ .print("Enter the username you want to insert data into the database: ");
+ String username = br.readLine();
+ System.out
+ .print("Enter the password you want to insert data into the database: ");
+ String password = br.readLine();
+
+ try {
+ int i = jdbc.insert(username, password);
+ if (i > 0) {
+ System.out.println((count++)
+ + " Data has been inserted successfully");
+ } else {
+ System.out.println("Data has not been inserted ");
+ }
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ }// End of case 1
+ break;
+ case 2: {
+ System.out
+ .print("Enter the username you want to view the entire data from the database: ");
+ String username = br.readLine();
+
+ try {
+ jdbc.view(username);
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ }// End of case 2
+ break;
+ case 3: {
+ System.out
+ .print("Enter the userid for which you want to delete the entire data from the database: ");
+ int userid = Integer.parseInt(br.readLine());
+
+ try {
+ int i = jdbc.delete(userid);
+ if (i > 0) {
+ System.out.println((count++)
+ + " Data has been deleted successfully");
+ } else {
+ System.out.println("Data has not been deleted");
+ }
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ }// End of case 3
+ break;
+ case 4: {
+ System.out
+ .print("Enter the username for which you want to update the data into the database: ");
+ String username = br.readLine();
+ System.out.print("Enter the new password ");
+ String password = br.readLine();
+
+ try {
+ int i = jdbc.update(username, password);
+ if (i > 0) {
+ System.out.println((count++)
+ + " Data has been updated successfully");
+ }
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ }// end of case 4
+ break;
+
+ default:
+ return;
+ }
+
+ } while (choice != 4);
+
+ }
+}
diff --git a/src/com/p2/designpatterns/Main.java b/src/com/p2/designpatterns/Main.java
new file mode 100644
index 0000000..fe20261
--- /dev/null
+++ b/src/com/p2/designpatterns/Main.java
@@ -0,0 +1,113 @@
+package com.p2.designpatterns;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+public class Main {
+ static int count = 1;
+ static int choice;
+
+ public static void main(String[] args) throws IOException {
+
+ JDBCSingleton jdbc = JDBCSingleton.getInstance();
+
+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
+ do {
+ System.out.println("DATABASE OPERATIONS");
+ System.out.println(" --------------------- ");
+ System.out.println(" 1. Insertion ");
+ System.out.println(" 2. View ");
+ System.out.println(" 3. Delete ");
+ System.out.println(" 4. Update ");
+ System.out.println(" 5. Exit ");
+
+ System.out.print("\n");
+ System.out.print("Please enter the choice what you want to perform in the database: ");
+ choice = Integer.parseInt(br.readLine());
+ switch (choice) {
+
+ case 1: {
+ System.out.print("Enter the username you want to insert data into the database: ");
+ String username = br.readLine();
+ System.out.print("Enter the password you want to insert data into the database: ");
+ String password = br.readLine();
+
+ try {
+ int i = jdbc.insert(username, password);
+ if (i > 0) {
+ System.out.println((count++)+ " Data has been inserted successfully");
+ } else {
+ System.out.println("Data has not been inserted ");
+ }
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ } break;
+ case 2: {
+ System.out.print("Enter the username you want to view the entire data from the database: ");
+ String username = br.readLine();
+
+ try {
+ jdbc.view(username);
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ } break;
+ case 3: {
+ System.out.print("Enter the userid for which you want to delete the entire data from the database: ");
+ int userid = Integer.parseInt(br.readLine());
+ try {
+ int i = jdbc.delete(userid);
+ if (i > 0) {
+ System.out.println((count++) + " Data has been deleted successfully");
+ } else {
+ System.out.println("Data has not been deleted");
+ }
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ } break;
+ case 4: {
+ System.out
+ .print("Enter the username for which you want to update the data into the database: ");
+ String username = br.readLine();
+ System.out.print("Enter the new password ");
+ String password = br.readLine();
+
+ try {
+ int i = jdbc.update(username, password);
+ if (i > 0) {
+ System.out.println((count++)+ " Data has been updated successfully");
+ }
+
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ System.out.println("Press Enter key to continue...");
+ System.in.read();
+
+ }// end of case 4
+ break;
+
+ default:
+ return;
+ }
+
+ } while (choice != 4);
+
+ }
+
+}
diff --git a/src/com/p2/designpatterns/MainSingletonEx.java b/src/com/p2/designpatterns/MainSingletonEx.java
new file mode 100644
index 0000000..922afad
--- /dev/null
+++ b/src/com/p2/designpatterns/MainSingletonEx.java
@@ -0,0 +1,34 @@
+package com.p2.designpatterns;
+
+/**
+Eager Initailization
+object is created at the time of class loading.
+May lead to resource wastage. Because instance of class is created always, whether it is required or not.
+CPU time is also wasted in creation of instance if it is not required.
+Exception handling is not possible.
+*/
+class SingletonWithEagerInitialization {
+
+ // Java code to create singleton class by
+ // Eager Initialization
+
+ // public instance initialized when loading the class
+ public static SingletonWithEagerInitialization instance = new SingletonWithEagerInitialization();
+
+ private SingletonWithEagerInitialization() {
+ System.out.println("In line 12 ----------------- >");
+ }
+
+}
+
+public class MainSingletonEx {
+
+ public static void main(String[] args) {
+
+ // constructor is called only once hence a single instance is available.
+ SingletonWithEagerInitialization instance0 = SingletonWithEagerInitialization.instance;
+ SingletonWithEagerInitialization instance1 = SingletonWithEagerInitialization.instance;
+
+ }
+
+}
diff --git a/src/com/p2/designpatterns/ServiceLocator.java b/src/com/p2/designpatterns/ServiceLocator.java
new file mode 100644
index 0000000..1c409b5
--- /dev/null
+++ b/src/com/p2/designpatterns/ServiceLocator.java
@@ -0,0 +1,126 @@
+package com.p2.designpatterns;
+
+//Java program to
+//illustrate Service Design Service
+//Locator Pattern
+
+import java.util.ArrayList;
+import java.util.List;
+
+//Service interface
+//for getting name and
+//Executing it.
+
+interface Service {
+ public String getName();
+ public void execute();
+}
+
+// Service one implementing Locator
+class ServiceOne implements Service {
+ public void execute() {
+ System.out.println("Executing ServiceOne");
+ }
+
+ @Override
+ public String getName() {
+ return "ServiceOne";
+ }
+}
+
+// Service two implementing Locator
+class ServiceTwo implements Service {
+ public void execute() {
+ System.out.println("Executing ServiceTwo");
+ }
+
+ @Override
+ public String getName() {
+ return "ServiceTwo";
+ }
+}
+
+// Checking the context
+// for ServiceOne and ServiceTwo
+class InitialContext {
+ public Object lookup(String name) {
+ if (name.equalsIgnoreCase("ServiceOne")) {
+ System.out.println("Creating a new ServiceOne object");
+ return new ServiceOne();
+ } else if (name.equalsIgnoreCase("ServiceTwo")) {
+ System.out.println("Creating a new ServiceTwo object");
+ return new ServiceTwo();
+ }
+ return null;
+ }
+}
+
+class Cache {
+ private List services;
+
+ public Cache() {
+ services = new ArrayList();
+ }
+
+ public Service getService(String serviceName) {
+ for (Service service : services) {
+ if (service.getName().equalsIgnoreCase(serviceName)) {
+ System.out.println("Returning cached " + serviceName
+ + " object");
+ return service;
+ }
+ }
+ return null;
+ }
+
+ public void addService(Service newService) {
+ boolean exists = false;
+ for (Service service : services) {
+ if (service.getName().equalsIgnoreCase(newService.getName())) {
+ exists = true;
+ }
+ }
+ if (!exists) {
+ services.add(newService);
+ }
+ }
+}
+
+// Locator class
+class ServiceLocator {
+ private static Cache cache;
+
+ static {
+ cache = new Cache();
+ }
+
+ public static Service getService(String name) {
+ Service service = cache.getService(name);
+
+ if (service != null) {
+ return service;
+ }
+
+ InitialContext context = new InitialContext();
+ Service ServiceOne = (Service) context.lookup(name);
+ cache.addService(ServiceOne);
+ return ServiceOne;
+ }
+}
+
+// Driver class
+class ServiceLocatorPatternDemo {
+ public static void main(String[] args) {
+ Service service = ServiceLocator.getService("ServiceOne");
+ service.execute();
+
+ service = ServiceLocator.getService("ServiceTwo");
+ service.execute();
+
+ service = ServiceLocator.getService("ServiceOne");
+ service.execute();
+
+ service = ServiceLocator.getService("ServiceTwo");
+ service.execute();
+ }
+}
diff --git a/src/com/p2/designpatterns/SigletonUsingStaticBlock.java b/src/com/p2/designpatterns/SigletonUsingStaticBlock.java
new file mode 100644
index 0000000..c27023d
--- /dev/null
+++ b/src/com/p2/designpatterns/SigletonUsingStaticBlock.java
@@ -0,0 +1,37 @@
+package com.p2.designpatterns;
+
+
+/**class is created when it is loaded to the memory by JVM. It is done by assigning the reference an instance directly.
+It can be used when program will always use instance of this class, or the cost of creating the instance is not too
+large in terms of resources and time.
+ *
+ * @author pradeep_patel
+ *
+ */
+
+class Singleton {
+
+ private Singleton() {
+ System.out.println("Creating Singleton Instance --------------------- >");
+ };
+
+ public static Singleton instance;
+ static {
+ instance = new Singleton();
+ }
+
+ public void printMe() {
+ System.out.println("I am in printMe Method --------------------------- >");
+ }
+
+}
+
+public class SigletonUsingStaticBlock {
+
+ public static void main(String[] args) {
+ Singleton singleton = Singleton.instance;
+ singleton.printMe();
+
+ }
+
+}
diff --git a/src/com/p2/designpatterns/SingleTonWithLazyInitialization.java b/src/com/p2/designpatterns/SingleTonWithLazyInitialization.java
new file mode 100644
index 0000000..df5ff34
--- /dev/null
+++ b/src/com/p2/designpatterns/SingleTonWithLazyInitialization.java
@@ -0,0 +1,64 @@
+package com.p2.designpatterns;
+
+/**
+ * Java Code to create singleton class With Lazy initialization, Only when you call
+ * getInstance the object is created , instance is created on demand and not by default.
+ * @author pradeep_patel
+ *
+ */
+class LazySingleton {
+ // private instance, so that it can be
+ // accessed by only by getInstance() method
+ private static LazySingleton instance;
+
+ private LazySingleton() {
+ System.out.println("Creating Singleton Instance --------------------- >");
+ }
+
+ /**
+ * method to return instance of class
+ * @return LazySingleton;
+ */
+ public static LazySingleton getInstance() {
+ // if instance is null, initialize
+ if (instance == null) {
+ instance = new LazySingleton();
+ }
+ return instance;
+ }
+
+
+ /**
+ * Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception
+ * from clone method that is CloneNotSupportedException. Now whenever user will try to create
+ * clone of singleton object, it will throw exception and hence our class remains singleton.
+ *
+ * Another way is to return the same instance
+ */
+
+ @Override
+ protected Object clone() throws CloneNotSupportedException {
+ // throw new CloneNotSupportedException();
+ return getInstance();
+ }
+}
+
+public class SingleTonWithLazyInitialization {
+
+ @SuppressWarnings("unused")
+ public static void main(String[] args) {
+ LazySingleton singleton = LazySingleton.getInstance();
+ }
+}
+
+/*
+Pros:
+
+ Object is created only if it is needed. It may overcome resource overcome and wastage of CPU time.
+ Exception handling is also possible in method.
+
+Cons:
+ Every time a condition of null has to be checked.
+ instance can’t be accessed directly.
+ In multithreaded environment, it may break singleton property.
+*/
\ No newline at end of file
diff --git a/src/com/p2/designpatterns/ThreadSafeSingleton.java b/src/com/p2/designpatterns/ThreadSafeSingleton.java
new file mode 100644
index 0000000..9453d61
--- /dev/null
+++ b/src/com/p2/designpatterns/ThreadSafeSingleton.java
@@ -0,0 +1,43 @@
+package com.p2.designpatterns;
+
+import java.io.Serializable;
+
+/**
+ * A thread safe singleton is created so that singleton property is maintained
+ * even in multithreaded environment. To make a singleton class thread-safe,
+ * getInstance() method is made synchronized so that multiple threads can’t
+ * access it simultaneously.
+ *
+ * @author pradeep_patel
+ *
+ */
+class ThreadSafeSingletonClass implements Serializable{
+
+ private static ThreadSafeSingletonClass instance;
+ private ThreadSafeSingletonClass() {
+ System.out.println("I am in constructor --------------- > ");
+ }
+
+ synchronized public static ThreadSafeSingletonClass getInstance() {
+ if (instance == null) {
+ return new ThreadSafeSingletonClass();
+ } else {
+ return instance;
+ }
+ }
+
+}
+
+public class ThreadSafeSingleton {
+ public static void main(String[] args) {
+ ThreadSafeSingletonClass instance = ThreadSafeSingletonClass.getInstance();
+ }
+}
+
+/*
+ * Pros: Lazy initialization is possible. It is also thread safe.
+ *
+ * Cons:
+ * getInstance() method is synchronized so it causes slow performance as
+ * multiple threads can’t access it simultaneously.
+ */
diff --git a/src/com/p2/designpatterns/ThreadSafeSingletonWithBlockSynchronized.java b/src/com/p2/designpatterns/ThreadSafeSingletonWithBlockSynchronized.java
new file mode 100644
index 0000000..0e38614
--- /dev/null
+++ b/src/com/p2/designpatterns/ThreadSafeSingletonWithBlockSynchronized.java
@@ -0,0 +1,34 @@
+package com.p2.designpatterns;
+
+//Java code to explain double check locking
+class SingletonWithBlockSync {
+ // private instance, so that it can be
+ // accessed by only by getInstance() method
+ private static SingletonWithBlockSync instance;
+
+ private SingletonWithBlockSync() {
+ // private constructor
+ }
+
+ public static SingletonWithBlockSync getInstance() {
+ if (instance == null) {
+ // synchronized block to remove overhead
+ synchronized (SingletonWithBlockSync.class) {
+ if (instance == null) {
+ // if instance is null, initialize
+ instance = new SingletonWithBlockSync();
+ }
+ }
+ }
+ return instance;
+ }
+}
+
+public class ThreadSafeSingletonWithBlockSynchronized {
+
+ public static void main(String[] args) {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/src/com/p2/designpatterns/package-info.java b/src/com/p2/designpatterns/package-info.java
new file mode 100644
index 0000000..91f4953
--- /dev/null
+++ b/src/com/p2/designpatterns/package-info.java
@@ -0,0 +1,22 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.designpatterns;
+
+
+/**
+
+Singleton Design Pattern : When to use What
+
+Eager initialization is easy to implement but it may cause resource and CPU time wastage.
+Use it only if cost of initializing a class is less in terms of resources or your program will always need the instance of class.
+By using Static block in Eager initialization we can provide exception handling and also can control over instance.
+Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance,
+so we can use Double check locking mechanism.
+Bill Pugh implementation is most widely used approach for singleton classes.
+Most developers prefer it because of its simplicity and advantages.
+ */
\ No newline at end of file
diff --git a/src/com/p2/designproblems/ParkingSpot.java b/src/com/p2/designproblems/ParkingSpot.java
new file mode 100644
index 0000000..da59a35
--- /dev/null
+++ b/src/com/p2/designproblems/ParkingSpot.java
@@ -0,0 +1,42 @@
+package com.p2.designproblems;
+
+//http://www.geeksforgeeks.org/design-parking-lot-using-object-oriented-principles/
+
+
+public class ParkingSpot
+{
+ private Vehicle vehicle;
+ private VehicleSize spotSize;
+ private int row;
+ private int spotNumber;
+ private Level level;
+
+ public ParkingSpot(Level lvl, int r, int n,
+ VehicleSize s)
+ { ... }
+
+ public boolean isAvailable()
+ {
+ return vehicle == null;
+ }
+
+ /* Check if the spot is big enough and is available */
+ public boolean canFitVehicle(Vehicle vehicle) { ... }
+
+ /* Park vehicle in this spot. */
+ public boolean park(Vehicle v) {..}
+
+ public int getRow()
+ {
+ return row;
+ }
+ public int getSpotNumber()
+ {
+ return spotNumber;
+ }
+
+ /* Remove vehicle from spot, and notify
+ level that a new spot is available */
+ public void removeVehicle() { ... }
+}
+
diff --git a/src/com/p2/designproblems/Vehicle.java b/src/com/p2/designproblems/Vehicle.java
new file mode 100644
index 0000000..44ecbf2
--- /dev/null
+++ b/src/com/p2/designproblems/Vehicle.java
@@ -0,0 +1,81 @@
+package com.p2.designproblems;
+
+import java.util.ArrayList;
+
+//Vehicle and its inherited classes.
+enum VehicleSize {
+ Motorcycle, Compact, Large
+}
+
+public abstract class Vehicle {
+ protected ArrayList parkingSpots = new ArrayList();
+ protected String licensePlate;
+ protected int spotsNeeded;
+ protected VehicleSize size;
+
+ public int getSpotsNeeded() {
+ return spotsNeeded;
+ }
+
+ public VehicleSize getSize() {
+ return size;
+ }
+
+ /*
+ * Park vehicle in this spot (among others, potentially)
+ */
+ public void parkinSpot(ParkingSpot s) {
+ parkingSpots.add(s);
+ }
+
+ /*
+ * Remove vehicle from spot, and notify spot that it's gone
+ */
+ public void clearSpots() {
+ }
+
+ /*
+ * Checks if the spot is big enough for the vehicle (and is available). This
+ * * compares the SIZE only.It does not check if it has enough spots.
+ */
+ public abstract boolean canFitinSpot(ParkingSpot spot);
+}
+
+class Bus extends Vehicle {
+ public Bus() {
+ spotsNeeded = 5;
+ size = VehicleSize.Large;
+ }
+
+ /*
+ * Checks if the spot is a Large. Doesn't check num of spots
+ */
+ public boolean canFitinSpot(ParkingSpot spot) {
+ return false;
+ }
+}
+
+class Car extends Vehicle {
+ public Car() {
+ spotsNeeded = 1;
+ size = VehicleSize.Compact;
+ }
+
+ /* Checks if the spot is a Compact or a Large. */
+ public boolean canFitinSpot(ParkingSpot spot) {
+
+ // write logic here and retuen accordingly
+ return false;
+ }
+}
+
+class Motorcycle extends Vehicle {
+ public Motorcycle() {
+ spotsNeeded = 1;
+ size = VehicleSize.Motorcycle;
+ }
+
+ public boolean canFitinSpot(ParkingSpot spot) {
+ return false;
+ }
+}
diff --git a/src/com/p2/designproblems/package-info.java b/src/com/p2/designproblems/package-info.java
new file mode 100644
index 0000000..c9e2988
--- /dev/null
+++ b/src/com/p2/designproblems/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.designproblems;
\ No newline at end of file
diff --git a/src/com/p2/enums/Colors.java b/src/com/p2/enums/Colors.java
new file mode 100644
index 0000000..7a63c13
--- /dev/null
+++ b/src/com/p2/enums/Colors.java
@@ -0,0 +1,12 @@
+package com.p2.enums;
+
+//A Java program to demonstrate that we can have
+//main() inside enum class.
+public enum Colors {
+ RED, GREEN, BLUE;
+ // Driver method
+ public static void main(String[] args) {
+ Colors c1 = Colors.RED;
+ System.out.println(c1);
+ }
+}
diff --git a/src/com/p2/enums/EnumConstr.java b/src/com/p2/enums/EnumConstr.java
new file mode 100644
index 0000000..3f8b572
--- /dev/null
+++ b/src/com/p2/enums/EnumConstr.java
@@ -0,0 +1,28 @@
+package com.p2.enums;
+
+//Java program to demonstrate that enums can have constructor
+//and concrete methods.
+
+//An enum (Note enum keyword inplace of class keyword)
+enum Menu {
+ RED, GREEN, BLUE;
+
+ // enum constructor called separately for each
+ // constant
+ private Menu() {
+ System.out.println("Constructor called for : " + this.toString());
+ }
+ // Only concrete (not abstract) methods allowed
+ public void colorInfo() {
+ System.out.println("Universal Color");
+ }
+}
+
+public class EnumConstr {
+ // Driver method
+ public static void main(String[] args) {
+ Menu c1 = Menu.RED;
+ System.out.println(c1);
+ c1.colorInfo();
+ }
+}
diff --git a/src/com/p2/enums/EnumEx.java b/src/com/p2/enums/EnumEx.java
new file mode 100644
index 0000000..2adffdb
--- /dev/null
+++ b/src/com/p2/enums/EnumEx.java
@@ -0,0 +1,25 @@
+package com.p2.enums;
+
+//A simple enum example where enum is declared
+//outside any class (Note enum keyword instead of
+//class keyword)
+enum Color {
+ RED, GREEN, BLUE;
+}
+
+public class EnumEx {
+ // Driver method
+ public static void main(String[] args) {
+ Color c1 = Color.RED;
+ System.out.println(c1.toString());
+ System.out.println(c1);
+ // values method
+ Color arr[] = Color.values();
+ // enum with loop
+ for (Color col : arr) {
+ // Calling ordinal() to find index
+ // of color.
+ System.out.println(col + " at index " + col.ordinal());
+ }
+ }
+}
diff --git a/src/com/p2/enums/EnumEx03.java b/src/com/p2/enums/EnumEx03.java
new file mode 100644
index 0000000..f36dac6
--- /dev/null
+++ b/src/com/p2/enums/EnumEx03.java
@@ -0,0 +1,44 @@
+package com.p2.enums;
+//A Java program to demonstrate working on enum
+//in switch case (Filename Test. Java)
+//An Enum class
+enum Day {
+ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
+}
+
+// Driver class that contains an object of "day" and
+// main().
+public class EnumEx03 {
+ Day day;
+
+ // Constructor
+ public EnumEx03(Day day) {
+ this.day = day;
+ }
+
+ // Prints a line about Day using switch
+ public void dayIsLike() {
+ switch (day) {
+ case MONDAY:
+ System.out.println("Mondays are bad.");
+ break;
+ case FRIDAY:
+ System.out.println("Fridays are better.");
+ break;
+ case SATURDAY:
+ case SUNDAY:
+ System.out.println("Weekends are best.");
+ break;
+ default:
+ System.out.println("Midweek days are so-so.");
+ break;
+ }
+ }
+
+ // Driver method
+ public static void main(String[] args) {
+ String str = "MONDAY";
+ EnumEx03 t1 = new EnumEx03(Day.valueOf(str));
+ t1.dayIsLike();
+ }
+}
diff --git a/src/com/p2/enums/EnumExInsideClass.java b/src/com/p2/enums/EnumExInsideClass.java
new file mode 100644
index 0000000..7129c0f
--- /dev/null
+++ b/src/com/p2/enums/EnumExInsideClass.java
@@ -0,0 +1,14 @@
+package com.p2.enums;
+
+//enum declaration inside a class.
+public class EnumExInsideClass {
+ enum Color {
+ RED, GREEN, BLUE;
+ }
+
+ public static void main(String[] args) {
+ Color c1 = Color.RED;
+ Color c2 = Color.valueOf("GREEN");
+ System.out.println(c1);
+ }
+}
diff --git a/src/com/p2/enums/package-info.java b/src/com/p2/enums/package-info.java
new file mode 100644
index 0000000..f6c6c9e
--- /dev/null
+++ b/src/com/p2/enums/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.enums;
\ No newline at end of file
diff --git a/src/com/p2/exception/FilenotFound_Demo.java b/src/com/p2/exception/FilenotFound_Demo.java
new file mode 100644
index 0000000..7557cd0
--- /dev/null
+++ b/src/com/p2/exception/FilenotFound_Demo.java
@@ -0,0 +1,27 @@
+package com.p2.exception;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+
+// sample code to show checked or compile time exception exception .
+public class FilenotFound_Demo {
+
+ public static void main(String args[]) {
+ File file = new File("E://file.txt");
+ // if you you remove try-catch block here you will not be able to compile.
+ // other way is to declare your method to thorws Exception
+ try {
+ FileReader fr = new FileReader(file);
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ public void demo_throws () throws FileNotFoundException{
+ File file = new File("E://file.txt");
+ FileReader fr = new FileReader(file);
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/p2/exception/OverridingAndExceptionThrownBySubClass.java b/src/com/p2/exception/OverridingAndExceptionThrownBySubClass.java
new file mode 100644
index 0000000..1173c53
--- /dev/null
+++ b/src/com/p2/exception/OverridingAndExceptionThrownBySubClass.java
@@ -0,0 +1,126 @@
+package com.p2.exception;
+
+import java.sql.BatchUpdateException;
+import java.sql.SQLException;
+
+
+/**
+ *
+ * @author pradeep_patel
+ *
+ *This sample of code demonstrates exception and overriding concept put together
+ */
+
+public class OverridingAndExceptionThrownBySubClass {
+
+ public static void main(String[] args) {
+
+ }
+
+}
+
+/** Case - 01
+ *
+ * @author pradeep_patel
+ *
+ * If super class method is not throwing any exceptions, then it can be overrided with any
+ * unchecked type of exceptions, but can not be overrided with checked type of exceptions.
+ *
+ *
+ */
+
+class SuperClass {
+ // Case -01
+ void methodOfSuperClass() {
+ System.out.println("Super class method is not throwing any exceptions");
+ }
+
+ // case -02
+ void methodOfSuperClassThrowingRuntimeException() throws ArrayIndexOutOfBoundsException {
+ System.out.println("Super class method is throwing Unchecked exception");
+ }
+
+ // case -03
+ void methodOfSuperClassThrowingCheckedException() throws SQLException {
+ System.out.println("Super class method is throwing Unchecked exception");
+ }
+}
+
+class SubClass extends SuperClass {
+
+ /** Case -01
+ * Overriden method can throw unchecked exception even when parent method is not throwing any exception
+ */
+ @Override
+ void methodOfSuperClass() throws ArrayIndexOutOfBoundsException {
+ System.out.println("can be overrided with any unchecked Exception");
+ }
+
+
+ /**
+ * Case -02 Overriden method can throw other runtime exceptions
+ */
+ @Override
+ void methodOfSuperClassThrowingRuntimeException() throws NumberFormatException, NullPointerException, RuntimeException {
+ System.out.println("Super class method is throwing Unchecked exception");
+ }
+
+ /**
+ * Case -03 Overriden method can throw the same or subtype of checked exception + any runtime Exception
+ */
+ @Override
+ void methodOfSuperClassThrowingCheckedException() throws SQLException, NullPointerException {
+ System.out.println("Super class method is throwing Unchecked exception");
+ }
+
+}
+
+class SubClassOne extends SuperClass {
+ /**
+ * Case -03 Overriden method can throw the same or subtype of checked exception + any runtime Exception
+ *
+ * Exception ClassNotFoundException is not compatible with throws clause.
+ */
+ @Override
+ void methodOfSuperClassThrowingCheckedException() throws ClassNotFoundException, NullPointerException {
+ System.out.println("Super class method is throwing Unchecked exception");
+ }
+}
+
+class SubClassTwo extends SuperClass {
+
+ /**
+ * Overriden method should not throw any checked exception until parent is throwing.
+ */
+ @Override
+ void methodOfSuperClass() throws SQLException {
+ // Compile time error
+ // Can not be overrided with checked exception
+ }
+
+ /**
+ * case -03
+ * Here method is throwing checked exception of sub-type
+ */
+ void methodOfSuperClassThrowingCheckedException()
+ throws BatchUpdateException {
+ System.out.println("Super class method is throwing Unchecked exception");
+ }
+}
+
+
+/**
+ * Case -02
+ * If a super class method is throwing unchecked exception, then it can be overrided in the sub class with same
+ * exception or any other unchecked exceptions but can not be overrided with checked exceptions.
+ *
+ */
+
+
+/**
+ * Overriding methods can throw any runtime exception there is no constraint
+ *
+ * Overriding methods can only throw same or subtype exception when method in parent class is throwing checked exception
+ */
+
+
diff --git a/src/com/p2/exception/UserDefinedExceptionExample.java b/src/com/p2/exception/UserDefinedExceptionExample.java
new file mode 100644
index 0000000..b92a84c
--- /dev/null
+++ b/src/com/p2/exception/UserDefinedExceptionExample.java
@@ -0,0 +1,43 @@
+package com.p2.exception;
+
+public class UserDefinedExceptionExample {
+
+ public static void main(String[] args) {
+
+ }
+
+}
+
+class UserDefinedCheckedException extends Exception {
+
+ public UserDefinedCheckedException() {
+ super();
+ }
+
+ public UserDefinedCheckedException(String message, Throwable cause,
+ boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+ public UserDefinedCheckedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public UserDefinedCheckedException(String message) {
+ super(message);
+ }
+
+ public UserDefinedCheckedException(Throwable cause) {
+ super(cause);
+ }
+
+}
+
+
+class UserDefinedUnCheckedException extends RuntimeException {
+
+
+
+
+}
+
diff --git a/src/com/p2/fileHandling/FileHandlingEx.java b/src/com/p2/fileHandling/FileHandlingEx.java
new file mode 100644
index 0000000..e6365d9
--- /dev/null
+++ b/src/com/p2/fileHandling/FileHandlingEx.java
@@ -0,0 +1,106 @@
+package com.p2.fileHandling;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+
+/**
+ *
+ * @author pradeep_patel
+ *Following program depicts how to create/Read/Write a text file using FileInputStream/FileOutputStream
+ */
+public class FileHandlingEx {
+ public static void main(String[] args) throws Exception{
+ //FileOperations.createFile(null);
+ //FileOperations.deleteFile();
+ FileOperations.readAndWriteToAFile();
+ }
+}
+
+/**
+ * The java.io package contains nearly every class you might ever need to
+ * perform input and output (I/O) in Java.
+ *
+ * @author pradeep_patel sample code on File Operation--
+ */
+
+class FileOperations {
+
+ static File file = null;
+ static String sepertor = "\\";
+ static String path0 = "D:" + sepertor + "Technical Tutorial";
+
+ /**
+ *
+ * @param path
+ * @return File Create file at specified path
+ */
+ public static File createFile(String path) {
+
+ try {
+ if (null == path || path.isEmpty())
+ path = path0;
+ System.out.println("File Created at:" + path);
+ file = new File(path + sepertor + "p.txt");
+ boolean createNewFile = file.createNewFile();
+ System.out.println("File Created = " + createNewFile);
+ } catch (Exception e) {
+ System.out.println(e.getClass());
+ }
+
+ return file;
+ }
+
+ /**
+ * Delete the given file
+ */
+ public static void deleteFile() {
+ if (null == file)
+ createFile(path0);
+ boolean isDeleted = file.delete();
+ System.err.println("File Deleted :" + isDeleted);
+ }
+
+ /**
+ * Read from a file and write to another file
+ * @throws IOException
+ */
+ public static void readAndWriteToAFile() throws IOException {
+
+ FileInputStream in = null;
+ FileOutputStream out = null;
+
+ try {
+ in = new FileInputStream("input.txt");
+ out = new FileOutputStream("output.txt");
+ int c;
+ while ((c = in.read()) != -1) {
+ out.write(c);
+ }
+ } catch (Exception e) {
+ System.out.println("Exception Thrown By Read And Write Method :"+ e.getClass());
+ } finally {
+
+ if (in != null) {
+ in.close();
+ }
+ if (out != null) {
+ out.close();
+ }
+ }
+
+ }
+
+ /*
+ * public static void readFile() { if (null == file) createFile(path0);
+ *
+ * FileInputStream fis = new FileInputStream(file); // InputStreamReader isr
+ * = new InputStreamReader(fis, cs); // BufferedReader br = new
+ * BufferedReader(isr);
+ *
+ * String line; while ((line = br.readLine()) != null) { // process the line
+ * System.out.println(line); } br.close(); }
+ */
+}
\ No newline at end of file
diff --git a/src/com/p2/fileHandling/ReaderAndWriterClassExample.java b/src/com/p2/fileHandling/ReaderAndWriterClassExample.java
new file mode 100644
index 0000000..c4c5c94
--- /dev/null
+++ b/src/com/p2/fileHandling/ReaderAndWriterClassExample.java
@@ -0,0 +1,134 @@
+package com.p2.fileHandling;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+
+public class ReaderAndWriterClassExample {
+ static FileWriter fw;
+ static String sepertor = "\\";
+ static String path = "D:" + sepertor + "Technical Tutorial" + sepertor
+ + "demo.txt";
+ static String SAMPLE_STRING = "Hello Pradeip, watsapp , What is going on";
+
+ public static void main(String[] args) throws IOException {
+
+ fw = FileWriterDemo.createFile(path, SAMPLE_STRING);
+
+ if (fw != null)
+ WordCountInFile.countWord(path);
+ else
+ System.out.println("File was Not found ");
+ //Reading File using FileReader
+ FileReaders.FileReader(path);
+ }
+}
+
+/**
+ *
+ * @author pradeep_patel
+ *
+ */
+
+class FileWriterDemo {
+ static String sepertor = "\\";
+
+ static T createFile(String path, String sampleString)
+ throws IOException {
+
+ File file = new File(path);
+ // attach a file to FileWriter
+ // this will also work
+ // new FileWriter(file);
+ FileWriter fw = new FileWriter(path);
+ // read character wise from string and write
+ // into FileWriter
+ for (int i = 0; i < sampleString.length(); i++)
+ fw.write(sampleString.charAt(i));
+ // close the file
+ System.out.println("Closing File Writer ---- >");
+ fw.close();
+ return (T) fw;
+ }
+}
+
+/**
+ * Read more on File handling at
+ * http://www.geeksforgeeks.org/file-handling-java-using-filewriter-filereader/
+ *
+ *
+ */
+
+/**
+ *
+ * @author pradeep_patel
+ *
+ */
+class WordCountInFile {
+
+ public static void countWord(String path) {
+ BufferedReader reader = null;
+ // Initializing charCount, wordCount and lineCount to 0
+ int charCount = 0;
+ int wordCount = 0;
+ int lineCount = 0;
+
+ try {
+ // Creating BufferedReader object
+ reader = new BufferedReader(new FileReader(path));
+ // Reading the first line into currentLine
+ String currentLine = reader.readLine();
+ while (currentLine != null) {
+ // Updating the lineCount
+ lineCount++;
+ // Getting number of words in currentLine
+ String[] words = currentLine.split(" ");
+ // Updating the wordCount
+ wordCount = wordCount + words.length;
+ // Iterating each word
+ for (String word : words) {
+ // Updating the charCount
+ charCount += word.length();
+ }
+ // Reading next line into currentLine
+ currentLine = reader.readLine();
+ }
+
+ // Printing charCount, wordCount and lineCount
+
+ System.out.println("Number Of Chars In A File : " + charCount);
+ System.out.println("Number Of Words In A File : " + wordCount);
+ System.out.println("Number Of Lines In A File : " + lineCount);
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ reader.close(); // Closing the reader
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}
+
+class FileReaders {
+ static FileReader fr;
+
+ static void FileReader(String path) throws IOException {
+ System.out.println("Reading file using File Reader Line - Code@124");
+ int ch;
+ try {
+ fr = new FileReader(path);
+ } catch (FileNotFoundException fe) {
+ System.out.println("File not found");
+ }
+ // read from FileReader till the end of file
+ while ((ch = fr.read()) != -1)
+ System.out.print((char) ch);
+ // close the file
+ fr.close();
+ }
+}
diff --git a/src/com/p2/fileHandling/package-info.java b/src/com/p2/fileHandling/package-info.java
new file mode 100644
index 0000000..5e725a8
--- /dev/null
+++ b/src/com/p2/fileHandling/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.fileHandling;
\ No newline at end of file
diff --git a/src/com/p2/finals/ChildOfFinal.java b/src/com/p2/finals/ChildOfFinal.java
new file mode 100644
index 0000000..186eb91
--- /dev/null
+++ b/src/com/p2/finals/ChildOfFinal.java
@@ -0,0 +1,32 @@
+package com.p2.finals;
+
+
+/**
+ *
+ * @author pradeep_patel
+ * Demonstrate Final variable, final method and final class
+ */
+
+class Final {
+
+ final Integer fInt = 23;
+ public final void makeSound() {
+ FinalEx finalex = new FinalEx();
+ // The final field FinalEx.fInt cannot be assigned
+ finalex.fInt = 34;
+ }
+}
+
+final class FinalEx extends Final{
+ final Integer fInt = 23;
+// Cannot override the final method from Final
+ public void makeSound() {
+ System.out.println("Make Sound:");
+ }
+}
+
+//Remove final Modifer for finalEx class
+//Compilation error when extending the final class
+public class ChildOfFinal extends FinalEx {
+
+}
diff --git a/src/com/p2/finals/package-info.java b/src/com/p2/finals/package-info.java
new file mode 100644
index 0000000..4f3604d
--- /dev/null
+++ b/src/com/p2/finals/package-info.java
@@ -0,0 +1,8 @@
+/**
+ *
+ */
+/**
+ * @author pradeep_patel
+ *
+ */
+package com.p2.finals;
\ No newline at end of file
diff --git a/src/com/p2/inheritance/Animal.java b/src/com/p2/inheritance/Animal.java
new file mode 100644
index 0000000..949effb
--- /dev/null
+++ b/src/com/p2/inheritance/Animal.java
@@ -0,0 +1,7 @@
+package com.p2.inheritance;
+
+class Animal {
+ public void move() {
+ System.out.println("Animals can move");
+ }
+}
diff --git a/src/com/p2/inheritance/Dog.java b/src/com/p2/inheritance/Dog.java
new file mode 100644
index 0000000..3b009d7
--- /dev/null
+++ b/src/com/p2/inheritance/Dog.java
@@ -0,0 +1,11 @@
+package com.p2.inheritance;
+
+class Dog extends Animal {
+ public void move() {
+ System.out.println("Dogs can walk and run");
+ }
+
+ public void bark() {
+ System.out.println("Dogs can bark");
+ }
+}
\ No newline at end of file
diff --git a/src/com/p2/inheritance/Employee.java b/src/com/p2/inheritance/Employee.java
new file mode 100644
index 0000000..849b7fe
--- /dev/null
+++ b/src/com/p2/inheritance/Employee.java
@@ -0,0 +1,40 @@
+package com.p2.inheritance;
+
+/* File name : Employee.java */
+public class Employee {
+ private String name;
+ private String address;
+ private int number;
+
+ public Employee(String name, String address, int number) {
+ System.out.println("Constructing an Employee");
+ this.name = name;
+ this.address = address;
+ this.number = number;
+ }
+
+ public void mailCheck() {
+ System.out.println("Mailing a check to " + this.name + " "
+ + this.address);
+ }
+
+ public String toString() {
+ return name + " " + address + " " + number;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String newAddress) {
+ address = newAddress;
+ }
+
+ public int getNumber() {
+ return number;
+ }
+}
diff --git a/src/com/p2/inheritance/Main.java b/src/com/p2/inheritance/Main.java
new file mode 100644
index 0000000..031db38
--- /dev/null
+++ b/src/com/p2/inheritance/Main.java
@@ -0,0 +1,27 @@
+package com.p2.inheritance;
+
+public class Main {
+
+ public static void main(String args[]) {
+
+ Animal a = new Animal(); // Animal reference and object
+ Animal b = (Animal)new Dog(); // Animal reference but Dog object vice versa will not work
+ //Dog d = (Dog) new Animal(); // java.lang.ClassCastException:
+ // Dog d = new Animal(); this will give casting error
+ a.move(); // runs the method in Animal class
+ b.move(); // runs the method in Dog class
+ // b.bark(); this will give an error
+ ((Dog) b).bark();
+
+ // -----------------------
+
+ Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
+ Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
+ System.out.println("Call mailCheck using Salary reference --");
+ s.mailCheck();
+ System.out.println("\n Call mailCheck using Employee reference--");
+ e.mailCheck();
+
+ }
+
+}
diff --git a/src/com/p2/inheritance/Salary.java b/src/com/p2/inheritance/Salary.java
new file mode 100644
index 0000000..66b7eb2
--- /dev/null
+++ b/src/com/p2/inheritance/Salary.java
@@ -0,0 +1,32 @@
+package com.p2.inheritance;
+
+/* File name : Salary.java */
+public class Salary extends Employee {
+ private double salary; // Annual salary
+
+ public Salary(String name, String address, int number, double salary) {
+ super(name, address, number);
+ setSalary(salary);
+ }
+
+ public void mailCheck() {
+ System.out.println("Within mailCheck of Salary class ");
+ System.out.println("Mailing check to " + getName() + " with salary "
+ + salary);
+ }
+
+ public double getSalary() {
+ return salary;
+ }
+
+ public void setSalary(double newSalary) {
+ if (newSalary >= 0.0) {
+ salary = newSalary;
+ }
+ }
+
+ public double computePay() {
+ System.out.println("Computing salary pay for " + getName());
+ return salary / 52;
+ }
+}
diff --git a/src/com/p2/io/CopyFile.class b/src/com/p2/io/CopyFile.class
new file mode 100644
index 0000000..bdbc824
Binary files /dev/null and b/src/com/p2/io/CopyFile.class differ
diff --git a/src/com/p2/io/CopyFile.java b/src/com/p2/io/CopyFile.java
new file mode 100644
index 0000000..e9d3da1
--- /dev/null
+++ b/src/com/p2/io/CopyFile.java
@@ -0,0 +1,36 @@
+package com.p2.io;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class CopyFile {
+
+ public static void main(String args[]) throws IOException {
+ FileInputStream in = null;
+ FileOutputStream out = null;
+ File file = null;
+ try {
+
+ file = new File(".");
+ for(String fileNames : file.list()) System.out.println(fileNames);
+ file = new File("D://JavaPracticeWorkSpace//resource//input.txt");
+ System.out.println(file.getAbsolutePath());
+ in = new FileInputStream(file.getAbsolutePath());
+ //out = new FileOutputStream("D:\\JavaPracticeWorkSpace\\SamplePractise\\resource\\output.txt");
+
+ /*int c;
+ while ((c = in.read()) != -1) {
+ out.write(c);
+ }*/
+ } finally {
+ if (in != null) {
+ in.close();
+ }
+ if (out != null) {
+ out.close();
+ }
+ }
+ }
+}
diff --git a/src/com/p2/io/CurrentDirectoryAndPath.java b/src/com/p2/io/CurrentDirectoryAndPath.java
new file mode 100644
index 0000000..d17e677
--- /dev/null
+++ b/src/com/p2/io/CurrentDirectoryAndPath.java
@@ -0,0 +1,30 @@
+package com.p2.io;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.Properties;
+
+public class CurrentDirectoryAndPath {
+
+ public static void main(String[] args) throws IOException {
+ File currentDirFile = new File(".");
+ String path = currentDirFile.getAbsolutePath();
+
+ System.out.println(path);
+
+ Properties properties = System.getProperties();
+ System.out.println(properties.get("user.dir"));
+ File f = new File(properties.get("user.dir")+"\\map1.json" );
+ System.out.println(f.getAbsolutePath());
+
+ /*properties.get("user.dir");
+ Enumeration