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 enumeration = properties.keys(); + for (int i = 0; i < properties.size(); i++) { + Object obj = enumeration.nextElement(); + System.out.println("Key: " + obj + "\tOutPut= " + + System.getProperty(obj.toString())); + }*/ + + } +} diff --git a/src/com/p2/io/Example.java b/src/com/p2/io/Example.java new file mode 100644 index 0000000..32ed1a5 --- /dev/null +++ b/src/com/p2/io/Example.java @@ -0,0 +1,17 @@ +package com.p2.io; + +import java.io.*; +class Example { + public static void main(String args[]) throws IOException + { + FileInputStream fis = null; + fis = new FileInputStream("D:/myFile.txt"); + int k; + + while(( k = fis.read() ) != -1) + { + System.out.print((char)k); + } + fis.close(); + } +} diff --git a/src/com/p2/json/JsonParserExample.java b/src/com/p2/json/JsonParserExample.java new file mode 100644 index 0000000..1a3d8f0 --- /dev/null +++ b/src/com/p2/json/JsonParserExample.java @@ -0,0 +1,105 @@ +package com.p2.json; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.json.JSONObject; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonParserExample { + + public static void main(String[] args) throws JsonParseException,JsonMappingException, IOException { + String file01 = "d:\\temp\\" + "map1.json"; + String file02 = "d:\\temp\\" + "map2.json"; + String[] pathList = { file01, file02 }; + List> list = ReadFile.readJSON(Arrays + .asList(pathList)); + List> nestedKeys = new ArrayList>(); + ReadFile.printAllKeys(list,nestedKeys); + + System.out.println(nestedKeys.toString()); + //ReadFile.mergeMaps(list); + + } +} + +class ReadFile { + + static List> readJSON(List pathList) { + ObjectMapper mapper = new ObjectMapper(); + Map map; + List> jsonFileList = new ArrayList>(); + + for (String path : pathList) { + try { + map = mapper.readValue(new File(path), + new TypeReference>() { + }); + + jsonFileList.add(map); + } catch (JsonParseException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return jsonFileList; + } + + static void printAllKeys(List> listOfJsonFiles,List> list) { + int i = 0; + for (Map json : listOfJsonFiles) { + System.out.println(i + + " Map :----------------------------------------->"); + printKeys(json,list); + } + } + + static Map mergeMaps(List> listOfJsonFiles) { + System.out.println("Inside merge maps"); + for (Map json : listOfJsonFiles) { + Set keys = json.keySet(); + for (String string : keys) { + System.out.println("Printing Key :" + string); + json.get(string); + if (json.get(string) instanceof Map) { + } else { + } + } + } + return null; + } + + static void printKeys(Object value,List> list) { + + List innerList = new ArrayList(); + if (value instanceof Map) { + Set keys = ((Map) value).keySet(); + + for (String string : keys) { + System.out.println("Printing Key :" + string); + innerList.add(string); + printKeys(((Map) value).get(string),list); + } + list.add(innerList); + } else { + + //System.out.println("Printing Values :" + value); + } + } +} diff --git a/src/com/p2/json/package-info.java b/src/com/p2/json/package-info.java new file mode 100644 index 0000000..b351242 --- /dev/null +++ b/src/com/p2/json/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.json; \ No newline at end of file diff --git a/src/com/p2/jvm/NewInstanceExample.java b/src/com/p2/jvm/NewInstanceExample.java new file mode 100644 index 0000000..d29048f --- /dev/null +++ b/src/com/p2/jvm/NewInstanceExample.java @@ -0,0 +1,19 @@ +package com.p2.jvm; + +public class NewInstanceExample { + java.lang.String name = "GeeksForGeeks"; + + public static void main(String[] args) { + try { + Class cls = Class.forName("NewInstanceExample"); + NewInstanceExample obj = (NewInstanceExample) cls.newInstance(); + System.out.println(obj.name); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/com/p2/jvm/String.java b/src/com/p2/jvm/String.java new file mode 100644 index 0000000..f0d2cb9 --- /dev/null +++ b/src/com/p2/jvm/String.java @@ -0,0 +1,9 @@ +package com.p2.jvm; + +//String is predefined class name in java.lang package +//Note : java.lang package is included in every java program by default +public class String { + public static void main(java.lang.String[] args) { + System.out.println("I got confused"); + } +} \ No newline at end of file diff --git a/src/com/p2/jvm/Test.java b/src/com/p2/jvm/Test.java new file mode 100644 index 0000000..b5d4d02 --- /dev/null +++ b/src/com/p2/jvm/Test.java @@ -0,0 +1,54 @@ +package com.p2.jvm; + +//A Java program to demonstrate working of a Class type +//object created by JVM to represent .class file in +//memory. +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +//Java code to demonstrate use of Class object +//created by JVM +public class Test { + public static void main(String[] args) { + Student s1 = new Student(); + + // Getting hold of Class object created + // by JVM. + @SuppressWarnings("rawtypes") + Class c1 = s1.getClass(); + // Printing type of object using c1. + System.out.println(c1.getName()); + // getting all methods in an array + Method m[] = c1.getDeclaredMethods(); + for (Method method : m) + System.out.println(method.getName()); + + // getting all fields in an array + Field f[] = c1.getDeclaredFields(); + for (Field field : f) + System.out.println(field.getName()); + } +} + +// A sample class whose information is fetched above using +// its Class object. +class Student { + private String name; + private int roll_No; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getRoll_no() { + return roll_No; + } + + public void setRoll_no(int roll_no) { + this.roll_No = roll_no; + } +} \ No newline at end of file diff --git a/src/com/p2/jvm/TestMain.java b/src/com/p2/jvm/TestMain.java new file mode 100644 index 0000000..56fa173 --- /dev/null +++ b/src/com/p2/jvm/TestMain.java @@ -0,0 +1,10 @@ +package com.p2.jvm; + +public class TestMain +{ + // static block + static + { + System.out.println("program is running without main() method"); + } +} diff --git a/src/com/p2/jvm/package-info.java b/src/com/p2/jvm/package-info.java new file mode 100644 index 0000000..6390f68 --- /dev/null +++ b/src/com/p2/jvm/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.jvm; \ No newline at end of file diff --git a/src/com/p2/loops/DoWhile.java b/src/com/p2/loops/DoWhile.java new file mode 100644 index 0000000..a57a9fe --- /dev/null +++ b/src/com/p2/loops/DoWhile.java @@ -0,0 +1,11 @@ +package com.p2.loops; + +public class DoWhile { + + + public static void main(){ + + + } + +} diff --git a/src/com/p2/loops/Loop.java b/src/com/p2/loops/Loop.java new file mode 100644 index 0000000..2db53b7 --- /dev/null +++ b/src/com/p2/loops/Loop.java @@ -0,0 +1,5 @@ +package com.p2.loops; + +public class Loop { + +} diff --git a/src/com/p2/loops/SwitchStmt.java b/src/com/p2/loops/SwitchStmt.java new file mode 100644 index 0000000..68db8be --- /dev/null +++ b/src/com/p2/loops/SwitchStmt.java @@ -0,0 +1,5 @@ +package com.p2.loops; + +public class SwitchStmt { + +} diff --git a/src/com/p2/loops/package-info.java b/src/com/p2/loops/package-info.java new file mode 100644 index 0000000..0ebf387 --- /dev/null +++ b/src/com/p2/loops/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.loops; \ No newline at end of file diff --git a/src/com/p2/marshalling/package-info.java b/src/com/p2/marshalling/package-info.java new file mode 100644 index 0000000..835d897 --- /dev/null +++ b/src/com/p2/marshalling/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + *http://www.javarticles.com/2016/09/jaxb-binding-and-unmarshalling-example.html + */ +package com.p2.marshalling; \ No newline at end of file diff --git a/src/com/p2/multithreading/Main.java b/src/com/p2/multithreading/Main.java new file mode 100644 index 0000000..2bf8a31 --- /dev/null +++ b/src/com/p2/multithreading/Main.java @@ -0,0 +1,26 @@ +package com.p2.multithreading; + +public class Main { + + public static void multiThreadUsingRunnanbleInterface() { + + for (int i = 0; i < 8; i++) { + MultithreadingRunnable object = new MultithreadingRunnable(); + new Thread(object).start(); + } + } + + public static void multiThreadExByExtendingThread() { + + for (int i = 0; i < 8; i++) { + MultithreadingDemo object = new MultithreadingDemo(); + object.start(); + } + } + + public static void main(String[] args) { + int n = 8; // Number of threads + multiThreadUsingRunnanbleInterface(); + multiThreadExByExtendingThread(); + } +} diff --git a/src/com/p2/multithreading/MultithreadingDemo.java b/src/com/p2/multithreading/MultithreadingDemo.java new file mode 100644 index 0000000..9ae93aa --- /dev/null +++ b/src/com/p2/multithreading/MultithreadingDemo.java @@ -0,0 +1,15 @@ +package com.p2.multithreading; + +//Java code for thread creation by extending +//the Thread class + public class MultithreadingDemo extends Thread{ + public void run() { + try { + // Displaying the thread that is running + System.out.println("Thread " + Thread.currentThread().getId() + " is running"); + } catch (Exception e) { + // Throwing an exception + System.out.println("Exception is caught"); + } + } +} diff --git a/src/com/p2/multithreading/MultithreadingRunnable.java b/src/com/p2/multithreading/MultithreadingRunnable.java new file mode 100644 index 0000000..b9d78f8 --- /dev/null +++ b/src/com/p2/multithreading/MultithreadingRunnable.java @@ -0,0 +1,17 @@ +package com.p2.multithreading; + +//Java code for thread creation by implementing +//the Runnable Interface +class MultithreadingRunnable implements Runnable { + public void run() { + try { + // Displaying the thread that is running + System.out.println("Thread " + Thread.currentThread().getId() + + " is running"); + + } catch (Exception e) { + // Throwing an exception + System.out.println("Exception is caught"); + } + } +} \ No newline at end of file diff --git a/src/com/p2/multithreading/SyncDemo.java b/src/com/p2/multithreading/SyncDemo.java new file mode 100644 index 0000000..6f801f0 --- /dev/null +++ b/src/com/p2/multithreading/SyncDemo.java @@ -0,0 +1,63 @@ +package com.p2.multithreading; + +//A Java program to demonstrate working of +//synchronized. +import java.io.*; +import java.util.*; + +//A Class used to send a message +class Sender { + public void send(String msg) { + System.out.println("Sending\t" + msg); + try { + Thread.sleep(1000); + } catch (Exception e) { + System.out.println("Thread interrupted."); + } + System.out.println("\n" + msg + "Sent"); + } +} + +// Class for send a message using Threads +class ThreadedSend extends Thread { + private String msg; + private Thread t; + Sender sender; + + // Recieves a message object and a string + // message to be sent + ThreadedSend(String m, Sender obj) { + msg = m; + sender = obj; + } + + public void run() { + // Only one thread can send a message + // at a time. + synchronized (sender) { + // synchronizing the snd object + sender.send(msg); + } + } +} + +// Driver class +class SyncDemo { + public static void main(String args[]) { + Sender snd = new Sender(); + ThreadedSend S1 = new ThreadedSend(" Hi ", snd); + ThreadedSend S2 = new ThreadedSend(" Bye ", snd); + + // Start two threads of ThreadedSend type + S1.start(); + S2.start(); + + // wait for threads to end + try { + S1.join(); + S2.join(); + } catch (Exception e) { + System.out.println("Interrupted"); + } + } +} diff --git a/src/com/p2/multithreading/Test.java b/src/com/p2/multithreading/Test.java new file mode 100644 index 0000000..ce4e6db --- /dev/null +++ b/src/com/p2/multithreading/Test.java @@ -0,0 +1,82 @@ +package com.p2.multithreading; + +//Java program to demonstrate thread states +class thread implements Runnable { + public void run() { + // moving thread2 to timed waiting state + try { + Thread.sleep(1500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + try { + Thread.sleep(1500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out + .println("State of thread1 while it called join() method on thread2 -" + + Test.thread1.getState()); + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} + +public class Test implements Runnable { + public static Thread thread1; + public static Test obj; + + public static void main(String[] args) { + obj = new Test(); + thread1 = new Thread(obj); + + // thread1 created and is currently in the NEW state. + System.out.println("State of thread1 after creating it - " + + thread1.getState() +"Line 39"); + thread1.start(); + + // thread1 moved to Runnable state + System.out + .println("State of thread1 after calling .start() method on it - " + + thread1.getState() + "Line 44"); + } + + public void run() { + thread myThread = new thread(); + Thread thread2 = new Thread(myThread); + // thread1 created and is currently in the NEW state. + System.out.println("State of thread2 after creating it - " + + thread2.getState()+ "Line 53"); + thread2.start(); + // thread2 moved to Runnable state + System.out + .println("State of thread2 after calling .start() method on it - " + + thread2.getState()+ "Line 58"); + + // moving thread1 to timed waiting state + try { + // moving thread2 to timed waiting state + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out + .println("State of thread2 after calling .sleep() method on it - " + + thread2.getState()+ "Line 69"); + + try { + // waiting for thread2 to die + thread2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out + .println("State of thread2 when it has finished it's execution - " + + thread2.getState()+ "Line 79"); + } + +} diff --git a/src/com/p2/multithreading/TestSleepMethod1.java b/src/com/p2/multithreading/TestSleepMethod1.java new file mode 100644 index 0000000..d942a90 --- /dev/null +++ b/src/com/p2/multithreading/TestSleepMethod1.java @@ -0,0 +1,22 @@ +package com.p2.multithreading; + +// Class and the main method in it +class TestSleepMethod1 extends Thread { + public void run() { + for (int i = 1; i < 5; i++) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + System.out.println(e); + } + System.out.println(i); + } + } + + public static void main(String args[]) { + TestSleepMethod1 t1 = new TestSleepMethod1(); + TestSleepMethod1 t2 = new TestSleepMethod1(); + t1.start(); + t2.start(); + } +} diff --git a/src/com/p2/multithreading/noname.js b/src/com/p2/multithreading/noname.js new file mode 100644 index 0000000..6230621 --- /dev/null +++ b/src/com/p2/multithreading/noname.js @@ -0,0 +1,27 @@ +after(function (done) { + // post coverage info + driver.switchTo().defaultContent(); + driver.executeScript("return window.__coverage__;").then(function (obj) { + var str = JSON.stringify(obj); + var options = { + port: 8888, + host: "localhost", + path: "/coverage/client", + method: "POST", + headers: { + "Content-Type": "application/json", + } + }; + var req = http.request(options, function (res) { + console.log("\nFinished sending coverage data."); + done(); + }); + req.write(str); + req.end(); + }); +}) +test.after(function () { + // at the end of the *whole* test run, download all coverage data and place it somewhere + console.log("Closing browser."); + driver.quit(); +}) \ No newline at end of file diff --git a/src/com/p2/multithreading/package-info.java b/src/com/p2/multithreading/package-info.java new file mode 100644 index 0000000..7ed107b --- /dev/null +++ b/src/com/p2/multithreading/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.multithreading; \ No newline at end of file diff --git a/src/com/p2/objectsandclasses/Finalize.java b/src/com/p2/objectsandclasses/Finalize.java new file mode 100644 index 0000000..44c6011 --- /dev/null +++ b/src/com/p2/objectsandclasses/Finalize.java @@ -0,0 +1,27 @@ +package com.p2.objectsandclasses; + +/** + * To demonstrate the use finalize method + * @author pradeep_patel + * + */ +class TestFinalize { + Integer int0 = 9; + // Override this method to release resource + @Override + protected void finalize() { + System.out.println("finalize method called"); + } +} + +public class Finalize { + + public static void main(String[] args) { + TestFinalize tf = new TestFinalize(); + tf = null; + System.gc(); + System.out.println("end ------------ >"); + + } + +} diff --git a/src/com/p2/objectsandclasses/package-info.java b/src/com/p2/objectsandclasses/package-info.java new file mode 100644 index 0000000..df0b7ad --- /dev/null +++ b/src/com/p2/objectsandclasses/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.objectsandclasses; \ No newline at end of file diff --git a/src/com/p2/operatorsAndDatatypes/Bitwise.java b/src/com/p2/operatorsAndDatatypes/Bitwise.java new file mode 100644 index 0000000..7878f27 --- /dev/null +++ b/src/com/p2/operatorsAndDatatypes/Bitwise.java @@ -0,0 +1,13 @@ +package com.p2.operatorsAndDatatypes; + + +// Java supports following two Bitwise right shift operators. +public class Bitwise { + public static void main(String args[]) { + int x = -4; + System.out.println(x >> 1); + int y = 4; + System.out.println(y >> 1); + } + +} diff --git a/src/com/p2/operatorsAndDatatypes/package-info.java b/src/com/p2/operatorsAndDatatypes/package-info.java new file mode 100644 index 0000000..fa84c3a --- /dev/null +++ b/src/com/p2/operatorsAndDatatypes/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.operatorsAndDatatypes; \ No newline at end of file diff --git a/src/com/p2/play/CreatePyramid.java b/src/com/p2/play/CreatePyramid.java new file mode 100644 index 0000000..c756617 --- /dev/null +++ b/src/com/p2/play/CreatePyramid.java @@ -0,0 +1,56 @@ +package com.p2.play; + +import java.util.Collections; + +public class CreatePyramid { + + public static void main(String[] args) { + + int rows = 5; + + System.out.println("\n1. Half Pyramid\n"); + for (int i = 0; i < rows; i++) { + + for (int j = 0; j <= i; j++) { + System.out.print("*"); + } + + System.out.println(""); + } + + System.out.println("\n2. Full Pyramid\n"); + for (int i = 0; i < rows; i++) { + + for (int j = 0; j < rows - i; j++) { + System.out.print(" "); + } + + for (int k = 0; k <= i; k++) { + System.out.print("* "); + } + + System.out.println(""); + } + + // java 8 , one line + System.out.println("\n3. Full Pyramid (Compact)\n"); + for (int i = 0; i < rows; i++) { + + System.out.println(String.join("", + Collections.nCopies(5 - i - 1, " ")) + + String.join("", Collections.nCopies(2 * i + 1, "*"))); + + } + + // java 8 + System.out.println("\n4. Inverted Pyramid\n"); + for (int i = rows; i > 0; i--) { + + System.out.println(String.join("", Collections.nCopies(5 - i, " ")) + + String.join("", Collections.nCopies(2 * i - 1, "*"))); + + } + + } + +} diff --git a/src/com/p2/play/package-info.java b/src/com/p2/play/package-info.java new file mode 100644 index 0000000..b1f90fa --- /dev/null +++ b/src/com/p2/play/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.play; \ No newline at end of file diff --git a/src/com/p2/polymorphism/OverridingAndOverloadingExample.java b/src/com/p2/polymorphism/OverridingAndOverloadingExample.java new file mode 100644 index 0000000..eed5b38 --- /dev/null +++ b/src/com/p2/polymorphism/OverridingAndOverloadingExample.java @@ -0,0 +1,135 @@ +package com.p2.polymorphism; + +/** + * + * @author pradeep_patel + * Demonstrate the concept and rule for overloading. + * Demonstrate the concept and rule for overriding. + * Demonstrate Duplicate method in a class + */ +public class OverridingAndOverloadingExample { + + public static void main(String[] args) { + + /**If a Parent type reference refers to a Parent object, then Parent's show is called*/ + Parent obj1 = new Parent(); + obj1.show(); + + /** If a Parent type reference refers to a Child object Child's show() is called. This is called RUN TIME POLYMORPHISM. */ + Parent obj2 = new Child(); + obj2.show(); + } +} + +/** + * A Simple Java program to demonstrate method overriding in java + * @author pradeep_patel + * BaseClass + */ +class Parent { + + protected void show() { + System.out.println("Parent's show()"); + } + + public Parent print(Parent p){ + return p; + } + + /** overloading is the ability to write methods that have the same name but accept different parameters. + either the type is different or argument list is different + return type does not matters at all in overloading. + */ + public int myMethod(int param) { + return 3; + } + // argument count is different (2 in this case) + public char myMethod(int param, int parms) { + return 'c'; + } + // argument type is different (char) + public int myMethod(char param) { + return 3; + } + + /** Having name and signature same both at the same time is not allowed , gives compile time error + /*public String myMethod(char param) { + return "Pradeip"; + }*/ + +} + +/** Child class for Parent + * + * @author pradeep_patel + * + */ +class Child extends Parent { + // This method overrides show() of Parent + // You can make public from protected + /** + * Child class can increase the visibilty + * Child class can not reduce the visibilty + */ + + @Override + public void show() { + System.out.println("Child's show()"); + } + + /**This is not overriding since signature has changed. + * + * @param p + * @param c + * @return + */ + public Child print(Parent p,String c){ + System.out.println(); + return (Child)p; + + } + + /** + * Along with argument type and count,there is a rule for return type as well in overriding. + * return type can be of parent type or its sub-type. + */ + @Override + public Child print(Parent p){ + System.out.println(); + return (Child)p; + } + + // overloading + public String print(Parent p,Integer h){ + System.out.println(); + return null; + } + +} + + +/** + * Overriding is also called as run time polymorphism since the instance is resolved at runtime + * If method name , argument type and argument list is same then it is a case of duplicate method + * + * + * + * + * + * + * + */ + + + + + + + + + + + + + + diff --git a/src/com/p2/polymorphism/package-info.java b/src/com/p2/polymorphism/package-info.java new file mode 100644 index 0000000..acc96c2 --- /dev/null +++ b/src/com/p2/polymorphism/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.polymorphism; \ No newline at end of file diff --git a/src/com/p2/programs/SinglyLinkedListImpl.java b/src/com/p2/programs/SinglyLinkedListImpl.java new file mode 100644 index 0000000..d701938 --- /dev/null +++ b/src/com/p2/programs/SinglyLinkedListImpl.java @@ -0,0 +1,103 @@ +package com.p2.programs; +/** + * sample code to reverse Singly Linked List by iterating through it only once. + * @author pradeep_patel + * + * @param + */ +public class SinglyLinkedListImpl { + + private Node head; + + public void add(T element) { + + Node nd = new Node(); + nd.setValue(element); + System.out.println("Adding: " + element); + Node tmp = head; + while (true) { + if (tmp == null) { + // since there is only one element, both head and + // tail points to the same object. + head = nd; + break; + } else if (tmp.getNextRef() == null) { + tmp.setNextRef(nd); + break; + } else { + tmp = tmp.getNextRef(); + } + } + } + + public void traverse() { + + Node tmp = head; + while (true) { + if (tmp == null) { + break; + } + System.out.print(tmp.getValue() + "\t"); + tmp = tmp.getNextRef(); + } + } + + public void reverse() { + + System.out.println("\nreversing the linked list\n"); + Node prev = null; + Node current = head; + Node next = null; + while (current != null) { + next = current.getNextRef(); + current.setNextRef(prev); + prev = current; + current = next; + } + head = prev; + } + + public static void main(String a[]) { + SinglyLinkedListImpl sl = new SinglyLinkedListImpl(); + sl.add(3); + sl.add(32); + sl.add(54); + sl.add(89); + System.out.println(); + sl.traverse(); + System.out.println(); + sl.reverse(); + sl.traverse(); + } +} + +class Node implements Comparable { + + private T value; + private Node nextRef; + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } + + public Node getNextRef() { + return nextRef; + } + + public void setNextRef(Node ref) { + this.nextRef = ref; + } + + @Override + public int compareTo(T arg) { + if (arg == this.value) { + return 0; + } else { + return 1; + } + } +} \ No newline at end of file diff --git a/src/com/p2/programs/package-info.java b/src/com/p2/programs/package-info.java new file mode 100644 index 0000000..fc59251 --- /dev/null +++ b/src/com/p2/programs/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.programs; \ No newline at end of file diff --git a/src/com/p2/regex/PatternExample.java b/src/com/p2/regex/PatternExample.java new file mode 100644 index 0000000..6c3ed6d --- /dev/null +++ b/src/com/p2/regex/PatternExample.java @@ -0,0 +1,29 @@ +package com.p2.regex; + +import java.util.regex.Pattern; + +public class PatternExample { + + public static void main(String[] args) { + + //Regular Expression Character classes Example + String [] lsit = {"[abc]","[^abc]","[a-zA-Z]","[a-d[m-p]]","[a-z&&[def]]","[a-z&&[^bc]]","[a-z&&[^m-p]]"}; + + Regex.checkMatch("....s.", "Mahesh"); + // + Regex.checkMatch(lsit[2], "adfewtwetryre"); + + + + } +} + +class Regex { + + static void checkMatch(String matcher, String matches) { + boolean b = Pattern.matches(matcher, matches); + System.out.println(b); + + } + +} \ No newline at end of file diff --git a/src/com/p2/regex/RegexExample.java b/src/com/p2/regex/RegexExample.java new file mode 100644 index 0000000..e3e0efb --- /dev/null +++ b/src/com/p2/regex/RegexExample.java @@ -0,0 +1,27 @@ +package com.p2.regex; + +import java.util.regex.Pattern; +import java.util.Scanner; +import java.util.regex.Matcher; + +public class RegexExample { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + while (true) { + System.out.println("Enter regex pattern:"); + Pattern pattern = Pattern.compile(sc.nextLine()); + System.out.println("Enter text:"); + Matcher matcher = pattern.matcher(sc.nextLine()); + boolean found = false; + while (matcher.find()) { + System.out.println("I found the text " + matcher.group() + + " starting at index " + matcher.start() + + " and ending at index " + matcher.end()); + found = true; + } + if (!found) { + System.out.println("No match found."); + } + } + } +} \ No newline at end of file diff --git a/src/com/p2/regex/package-info.java b/src/com/p2/regex/package-info.java new file mode 100644 index 0000000..8db9483 --- /dev/null +++ b/src/com/p2/regex/package-info.java @@ -0,0 +1,39 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.regex; + +/** + +java.util.regex package + +It provides following classes and interface for regular expressions. The Matcher and Pattern classes are +widely used in java regular expression. + + MatchResult interface + Matcher class + Pattern class + PatternSyntaxException class + + +*/ + + +/** +No. Method Description +1 boolean matches() test whether the regular expression matches the pattern. +2 boolean find() finds the next expression that matches the pattern. +3 boolean find(int start) finds the next expression that matches the pattern from the given start number. +4 String group() returns the matched subsequence. +5 int start() returns the starting index of the matched subsequence. +6 int end() returns the ending index of the matched subsequence. +7 int groupCount() returns the total number of the matched subsequence. + +*/ + + + diff --git a/src/com/p2/staticMembers/CallingMethodsInSameClass.java b/src/com/p2/staticMembers/CallingMethodsInSameClass.java new file mode 100644 index 0000000..d8970e6 --- /dev/null +++ b/src/com/p2/staticMembers/CallingMethodsInSameClass.java @@ -0,0 +1,52 @@ +package com.p2.staticMembers; + +/* CallingMethodsInSameClass.java + * + * illustrates how to call static methods a class + * from a method in the same class + */ + +public class CallingMethodsInSameClass { + + public static void main(String[] args) { + printOne(); + printOne(); + printTwo(); + // Cannot make a static reference to the non-static method printThree() + // from the type CallingMethodsInSameClass + // printThree(); + CallingMethodsInSameClass cmi = new CallingMethodsInSameClass(); + cmi.printThree(); + + // below classes will be not available outside of the class definition + cmi.printMeNonStatic(); + cmi.printMe(); + CallingMethodsInSameClass.printMe(); + } + + public static void printOne() { + System.out.println("Hello World"); + } + + public static void printTwo() { + printOne(); + printOne(); + } + + // non static methods can be called only on object and not on class + public void printThree() { + System.out.println("Hello World 3"); + // printOne(); + } + + private static void printMe() { + + System.out.println("printMe ------------------ > 39"); + } + + private void printMeNonStatic() { + System.out.println("printMeNonStatic ------------------ > 43"); + + } + +} \ No newline at end of file diff --git a/src/com/p2/staticMembers/Example.java b/src/com/p2/staticMembers/Example.java new file mode 100644 index 0000000..e69de29 diff --git a/src/com/p2/staticMembers/Main.java b/src/com/p2/staticMembers/Main.java new file mode 100644 index 0000000..3d00e16 --- /dev/null +++ b/src/com/p2/staticMembers/Main.java @@ -0,0 +1,20 @@ +package com.p2.staticMembers; + +public class Main { + + /** + * @param args + */ + public static void main(String[] args) { + + StaticEx staticEx = new StaticEx(); + StaticEx.age = 37; + staticEx.age = 49; + StaticEx staticEx2 = new StaticEx(); + System.out.println(staticEx2.age); + + CallingMethodsInSameClass ex = new CallingMethodsInSameClass(); + + } + +} diff --git a/src/com/p2/staticMembers/MainC.java b/src/com/p2/staticMembers/MainC.java new file mode 100644 index 0000000..ce6e2f9 --- /dev/null +++ b/src/com/p2/staticMembers/MainC.java @@ -0,0 +1,55 @@ +package com.p2.staticMembers; + +/* Java program to demonstrate how to implement static and non-static + classes in a java program. */ +class OuterClass { + private static String msg = "GeeksForGeeks"; + // Static nested class + public static class NestedStaticClass { + // Only static members of Outer class is directly accessible in nested + // static class + public void printMessage() { + // Try making 'message' a non-static variable, there will be + // compiler error + System.out.println("Message from nested static class: " + msg); + } + } + + // non-static nested class - also called Inner class + public class InnerClass { + + // Both static and non-static members of Outer class are accessible in + // this Inner class + public void display() { + System.out.println("Message from non-static nested class: " + msg); + } + } +} + +class MainC { + // How to create instance of static and non static nested class? + public static void main(String args[]) { + + // create instance of nested Static class + OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass(); + + // call non static method of nested static class + printer.printMessage(); + + // In order to create instance of Inner class we need an Outer class + // instance. Let us create Outer class instance for creating + // non-static nested class + OuterClass outer = new OuterClass(); + OuterClass.InnerClass inner = outer.new InnerClass(); + + // calling non-static method of Inner class + inner.display(); + + // we can also combine above steps in one step to create instance of + // Inner class + OuterClass.InnerClass innerObject = new OuterClass().new InnerClass(); + + // similarly we can now call Inner class method + innerObject.display(); + } +} diff --git a/src/com/p2/staticMembers/MethodHidingEx.java b/src/com/p2/staticMembers/MethodHidingEx.java new file mode 100644 index 0000000..748e2ed --- /dev/null +++ b/src/com/p2/staticMembers/MethodHidingEx.java @@ -0,0 +1,19 @@ +package com.p2.staticMembers; + +class A { + static void fun() { + System.out.println("A.fun()"); + } +} +class B extends A { + static void fun() { + System.out.println("B.fun()"); + } +} +public class MethodHidingEx { + public static void main(String args[]) { + A a = new B(); + a.fun(); // prints A.fun() + new B().fun(); // prints B.fun() + } +} \ No newline at end of file diff --git a/src/com/p2/staticMembers/StaticDemo.java b/src/com/p2/staticMembers/StaticDemo.java new file mode 100644 index 0000000..c77b0b2 --- /dev/null +++ b/src/com/p2/staticMembers/StaticDemo.java @@ -0,0 +1,46 @@ +package com.p2.staticMembers; + +class Student { + String name; + int rollNo; + // static variable + static String cllgName; + // static counter to set unique roll no + static int counter = 0; + public Student(String name) { + this.name = name; + this.rollNo = setRollNo(); + } + // getting unique rollNo + // through static variable(counter) + static int setRollNo() { + counter++; + return counter; + } + // static method + static void setCllg(String name) { + cllgName = name; + } + // instance method + void getStudentInfo() { + System.out.println("name : " + this.name); + System.out.println("rollNo : " + this.rollNo); + // accessing static variable + System.out.println("cllgName : " + cllgName); + } +} + +// Driver class +public class StaticDemo { + public static void main(String[] args) { + // calling static method + // without instantiating Student class + Student.setCllg("XYZ"); + Student s1 = new Student("Alice"); + Student s2 = new Student("Bob"); + + s1.getStudentInfo(); + s2.getStudentInfo(); + + } +} diff --git a/src/com/p2/staticMembers/StaticEx.java b/src/com/p2/staticMembers/StaticEx.java new file mode 100644 index 0000000..8e6682f --- /dev/null +++ b/src/com/p2/staticMembers/StaticEx.java @@ -0,0 +1,8 @@ +package com.p2.staticMembers; + +public class StaticEx { + + public static Integer age = null; + private static Integer profession = null; + +} diff --git a/src/com/p2/staticMembers/StaticExecution.java b/src/com/p2/staticMembers/StaticExecution.java new file mode 100644 index 0000000..1fb9c3d --- /dev/null +++ b/src/com/p2/staticMembers/StaticExecution.java @@ -0,0 +1,22 @@ +package com.p2.staticMembers; + +//java program to demonstrate execution +//of static blocks and variables +class StaticExecution { + // static variable + static int a = m1(); + // static block + static { + System.out.println("Inside static block"); + } + // static method + static int m1() { + System.out.println("from m1"); + return 20; + } + // static method(main !!) + public static void main(String[] args) { + System.out.println("Value of a : " + a); + System.out.println("from main"); + } +} \ No newline at end of file diff --git a/src/com/p2/staticMembers/Test.java b/src/com/p2/staticMembers/Test.java new file mode 100644 index 0000000..89995f1 --- /dev/null +++ b/src/com/p2/staticMembers/Test.java @@ -0,0 +1,25 @@ +package com.p2.staticMembers; + +//filename: Main.java +// The public type StaticB must be defined in its own file + class StaticB { + static int i; + int j; + + // start of static block + static { + i = 10; + System.out.println("static block called "); + } + // end of static block +} + + + +class Test { + public static void main(String args[]) { + // Although we don't have an object of Test, static block is + // called because i is being accessed in following statement. + System.out.println(StaticB.i); + } +} \ No newline at end of file diff --git a/src/com/p2/utility/EnhancedForLoop.java b/src/com/p2/utility/EnhancedForLoop.java new file mode 100644 index 0000000..1398486 --- /dev/null +++ b/src/com/p2/utility/EnhancedForLoop.java @@ -0,0 +1,10 @@ +package com.p2.utility; + +public class EnhancedForLoop { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/com/p2/utility/FactorialUsingLoop.java b/src/com/p2/utility/FactorialUsingLoop.java new file mode 100644 index 0000000..7cd479f --- /dev/null +++ b/src/com/p2/utility/FactorialUsingLoop.java @@ -0,0 +1,26 @@ +package com.p2.utility; + +public class FactorialUsingLoop { + + public static void main(String[] args) { + + Long z = (long) 1; int facto = 80; + for (int i = 1; i <= facto; i++) { z = z * i; // + //System.out.println(z); + + } System.out.println("Factorial of " + facto + ":" + z); + + + /*final int NUM_FACTS = 100; + for (int i = 0; i < NUM_FACTS; i++) + System.out.println(i + "! is " + factorial(i));*/ + } + + public static int factorial(int n) { + int result = 1; + for (int i = 2; i <= n; i++) + result *= i; + return result; + } + +} diff --git a/src/com/p2/utility/FactorialusingRecursion.java b/src/com/p2/utility/FactorialusingRecursion.java new file mode 100644 index 0000000..facf54e --- /dev/null +++ b/src/com/p2/utility/FactorialusingRecursion.java @@ -0,0 +1,20 @@ +package com.p2.utility; + +/* + * @Author Pradeep + * */ + +public class FactorialusingRecursion { + + public static void main(String args[]) { + System.out.println(factorial(1)); + } + + public static long factorial(long f) { + if (f != 1) { + return f * factorial(f - 1); + } else { + return f; + } + } +} diff --git a/src/com/p2/wrapper/WrapperExamples.java b/src/com/p2/wrapper/WrapperExamples.java new file mode 100644 index 0000000..2aa1955 --- /dev/null +++ b/src/com/p2/wrapper/WrapperExamples.java @@ -0,0 +1,50 @@ +package com.p2.wrapper; + + +/** + * + * @author pradeep_patel + * + * Demonstrate ValueOf(),ValueOf(.. , .. ), parseXXX(), xxxValue() + * + */ + + +public class WrapperExamples { + + public static void main(String[] args) { + + Integer I = Integer.valueOf("10"); + System.out.println(I); + + I = Integer.valueOf("1111", 2); + System.out.println("Radix: " +I); + + I = Integer.valueOf("128"); + + // byteValue + System.out.println("Byte Value: " +I.byteValue()); + System.out.println(I.shortValue()); + System.out.println(I.intValue()); + System.out.println(I.longValue()); + System.out.println(I.floatValue()); + System.out.println(I.doubleValue()); + + + Double D = Double.valueOf("10.0"); + System.out.println(D); + Boolean B = Boolean.valueOf("true"); + System.out.println(B); + // Here we will get RuntimeException + //Integer I1 = Integer.valueOf("ten"); + + + int i = Integer.parseInt("10"); + double d = Double.parseDouble("10.5"); + boolean b = Boolean.parseBoolean("true"); + System.out.println(i); + System.out.println(d); + System.out.println(b); + + } +} diff --git a/src/com/p2/wrapper/package-info.java b/src/com/p2/wrapper/package-info.java new file mode 100644 index 0000000..286fae3 --- /dev/null +++ b/src/com/p2/wrapper/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author pradeep_patel + * + */ +package com.p2.wrapper; \ No newline at end of file