From 46c3d1034b3e3bc01b75685edc7defbc1b6f0cdc Mon Sep 17 00:00:00 2001 From: pradeipk Date: Wed, 29 Nov 2017 19:14:26 +0530 Subject: [PATCH 1/3] Added more examples --- src/com/p2/collections/ArraysEx.java | 45 +++ src/com/p2/collections/CollectionEx.java | 31 ++ src/com/p2/collections/ComparableEx.java | 59 ++++ src/com/p2/collections/ComparatorEx.java | 65 ++++ .../p2/collections/InnerClassInInterface.java | 10 + src/com/p2/collections/ListIteratorEx.java | 40 +++ src/com/p2/collections/SetExample.java | 25 ++ src/com/p2/collections/generics/BaseDao.java | 64 ++++ .../p2/collections/generics/GenericsEx.java | 161 ++++++++++ .../p2/collections/generics/package-info.java | 8 + .../hashmap/HashCodeAndEquals.java | 121 ++++++++ .../collections/hashmap/MapExIteration.java | 75 +++++ .../p2/collections/hashmap/package-info.java | 8 + src/com/p2/collections/package-info.java | 8 + src/com/p2/constructors/Box.java | 37 +++ src/com/p2/constructors/package-info.java | 8 + .../p2/designpatterns/BillPughSingleton.java | 31 ++ .../p2/designpatterns/JDBCSingletonDemo.java | 292 ++++++++++++++++++ src/com/p2/designpatterns/Main.java | 113 +++++++ .../p2/designpatterns/MainSingletonEx.java | 34 ++ src/com/p2/designpatterns/ServiceLocator.java | 126 ++++++++ .../SigletonUsingStaticBlock.java | 37 +++ .../SingleTonWithLazyInitialization.java | 64 ++++ .../designpatterns/ThreadSafeSingleton.java | 43 +++ ...eadSafeSingletonWithBlockSynchronized.java | 34 ++ src/com/p2/designpatterns/package-info.java | 22 ++ src/com/p2/designproblems/ParkingSpot.java | 42 +++ src/com/p2/designproblems/Vehicle.java | 81 +++++ src/com/p2/designproblems/package-info.java | 8 + src/com/p2/enums/Colors.java | 12 + src/com/p2/enums/EnumConstr.java | 28 ++ src/com/p2/enums/EnumEx.java | 25 ++ src/com/p2/enums/EnumEx03.java | 44 +++ src/com/p2/enums/EnumExInsideClass.java | 14 + src/com/p2/enums/package-info.java | 8 + src/com/p2/finals/ChildOfFinal.java | 32 ++ src/com/p2/finals/package-info.java | 8 + src/com/p2/inheritance/Main.java | 3 +- src/com/p2/jvm/NewInstanceExample.java | 19 ++ src/com/p2/jvm/String.java | 9 + src/com/p2/jvm/Test.java | 54 ++++ src/com/p2/jvm/TestMain.java | 10 + src/com/p2/jvm/package-info.java | 8 + src/com/p2/loops/DoWhile.java | 11 + src/com/p2/loops/Loop.java | 5 + src/com/p2/loops/SwitchStmt.java | 5 + src/com/p2/loops/package-info.java | 8 + src/com/p2/multithreading/SyncDemo.java | 63 ++++ src/com/p2/objectsandclasses/Finalize.java | 27 ++ .../p2/objectsandclasses/package-info.java | 8 + src/com/p2/operatorsAndDatatypes/Bitwise.java | 13 + .../operatorsAndDatatypes/package-info.java | 8 + src/com/p2/programs/SinglyLinkedListImpl.java | 103 ++++++ src/com/p2/programs/package-info.java | 8 + .../CallingMethodsInSameClass.java | 18 ++ src/com/p2/staticMembers/Main.java | 2 + src/com/p2/wrapper/WrapperExamples.java | 50 +++ src/com/p2/wrapper/package-info.java | 8 + 58 files changed, 2301 insertions(+), 2 deletions(-) create mode 100644 src/com/p2/collections/ArraysEx.java create mode 100644 src/com/p2/collections/CollectionEx.java create mode 100644 src/com/p2/collections/ComparableEx.java create mode 100644 src/com/p2/collections/ComparatorEx.java create mode 100644 src/com/p2/collections/InnerClassInInterface.java create mode 100644 src/com/p2/collections/ListIteratorEx.java create mode 100644 src/com/p2/collections/SetExample.java create mode 100644 src/com/p2/collections/generics/BaseDao.java create mode 100644 src/com/p2/collections/generics/GenericsEx.java create mode 100644 src/com/p2/collections/generics/package-info.java create mode 100644 src/com/p2/collections/hashmap/HashCodeAndEquals.java create mode 100644 src/com/p2/collections/hashmap/MapExIteration.java create mode 100644 src/com/p2/collections/hashmap/package-info.java create mode 100644 src/com/p2/collections/package-info.java create mode 100644 src/com/p2/constructors/Box.java create mode 100644 src/com/p2/constructors/package-info.java create mode 100644 src/com/p2/designpatterns/BillPughSingleton.java create mode 100644 src/com/p2/designpatterns/JDBCSingletonDemo.java create mode 100644 src/com/p2/designpatterns/Main.java create mode 100644 src/com/p2/designpatterns/MainSingletonEx.java create mode 100644 src/com/p2/designpatterns/ServiceLocator.java create mode 100644 src/com/p2/designpatterns/SigletonUsingStaticBlock.java create mode 100644 src/com/p2/designpatterns/SingleTonWithLazyInitialization.java create mode 100644 src/com/p2/designpatterns/ThreadSafeSingleton.java create mode 100644 src/com/p2/designpatterns/ThreadSafeSingletonWithBlockSynchronized.java create mode 100644 src/com/p2/designpatterns/package-info.java create mode 100644 src/com/p2/designproblems/ParkingSpot.java create mode 100644 src/com/p2/designproblems/Vehicle.java create mode 100644 src/com/p2/designproblems/package-info.java create mode 100644 src/com/p2/enums/Colors.java create mode 100644 src/com/p2/enums/EnumConstr.java create mode 100644 src/com/p2/enums/EnumEx.java create mode 100644 src/com/p2/enums/EnumEx03.java create mode 100644 src/com/p2/enums/EnumExInsideClass.java create mode 100644 src/com/p2/enums/package-info.java create mode 100644 src/com/p2/finals/ChildOfFinal.java create mode 100644 src/com/p2/finals/package-info.java create mode 100644 src/com/p2/jvm/NewInstanceExample.java create mode 100644 src/com/p2/jvm/String.java create mode 100644 src/com/p2/jvm/Test.java create mode 100644 src/com/p2/jvm/TestMain.java create mode 100644 src/com/p2/jvm/package-info.java create mode 100644 src/com/p2/loops/DoWhile.java create mode 100644 src/com/p2/loops/Loop.java create mode 100644 src/com/p2/loops/SwitchStmt.java create mode 100644 src/com/p2/loops/package-info.java create mode 100644 src/com/p2/multithreading/SyncDemo.java create mode 100644 src/com/p2/objectsandclasses/Finalize.java create mode 100644 src/com/p2/objectsandclasses/package-info.java create mode 100644 src/com/p2/operatorsAndDatatypes/Bitwise.java create mode 100644 src/com/p2/operatorsAndDatatypes/package-info.java create mode 100644 src/com/p2/programs/SinglyLinkedListImpl.java create mode 100644 src/com/p2/programs/package-info.java create mode 100644 src/com/p2/wrapper/WrapperExamples.java create mode 100644 src/com/p2/wrapper/package-info.java 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/ComparableEx.java b/src/com/p2/collections/ComparableEx.java new file mode 100644 index 0000000..a14e60b --- /dev/null +++ b/src/com/p2/collections/ComparableEx.java @@ -0,0 +1,59 @@ +package com.p2.collections; + +//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.*; + +//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; + } +} + +// Driver class +public class ComparableEx { + 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()); + } + } +} diff --git a/src/com/p2/collections/ComparatorEx.java b/src/com/p2/collections/ComparatorEx.java new file mode 100644 index 0000000..661298f --- /dev/null +++ b/src/com/p2/collections/ComparatorEx.java @@ -0,0 +1,65 @@ +package com.p2.collections; + +// Java program to demonstrate working of Comparator +// interface +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) { + 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)); + + 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)); + + 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/GenericsEx.java b/src/com/p2/collections/generics/GenericsEx.java new file mode 100644 index 0000000..89b2076 --- /dev/null +++ b/src/com/p2/collections/generics/GenericsEx.java @@ -0,0 +1,161 @@ +package com.p2.collections.generics; + +import java.util.ArrayList; +import java.util.List; + +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/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/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/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/Main.java b/src/com/p2/inheritance/Main.java index f802244..031db38 100644 --- a/src/com/p2/inheritance/Main.java +++ b/src/com/p2/inheritance/Main.java @@ -5,8 +5,7 @@ public class Main { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object - Animal b = new Dog(); // Animal reference but Dog object vice vers will - // not work + 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 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/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/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/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/staticMembers/CallingMethodsInSameClass.java b/src/com/p2/staticMembers/CallingMethodsInSameClass.java index e7b23e6..d8970e6 100644 --- a/src/com/p2/staticMembers/CallingMethodsInSameClass.java +++ b/src/com/p2/staticMembers/CallingMethodsInSameClass.java @@ -7,6 +7,7 @@ */ public class CallingMethodsInSameClass { + public static void main(String[] args) { printOne(); printOne(); @@ -16,6 +17,11 @@ public static void main(String[] args) { // 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() { @@ -27,8 +33,20 @@ public static void printTwo() { 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/Main.java b/src/com/p2/staticMembers/Main.java index 1a8d970..3d00e16 100644 --- a/src/com/p2/staticMembers/Main.java +++ b/src/com/p2/staticMembers/Main.java @@ -12,6 +12,8 @@ public static void main(String[] args) { staticEx.age = 49; StaticEx staticEx2 = new StaticEx(); System.out.println(staticEx2.age); + + CallingMethodsInSameClass ex = new CallingMethodsInSameClass(); } 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 From 5f3023465153fd37ffd82a888e780807e89d63e8 Mon Sep 17 00:00:00 2001 From: pradeipk Date: Fri, 1 Dec 2017 20:38:18 +0530 Subject: [PATCH 2/3] Added code for Filehandling,generics,exception handling,overriding --- .../collections/CollectionsClassExample.java | 78 ++++++++++ src/com/p2/collections/ComparableEx.java | 43 +++--- src/com/p2/collections/ComparatorEx.java | 13 +- .../p2/collections/generics/BoundedClass.java | 68 +++++++++ .../p2/collections/generics/GenericsEx.java | 5 + .../p2/collections/generics/MaximumTest.java | 29 ++++ .../collections/list/CollectionExamples.java | 76 ++++++++++ src/com/p2/collections/list/package-info.java | 8 ++ ...verridingAndExceptionThrownBySubClass.java | 126 ++++++++++++++++ .../UserDefinedExceptionExample.java | 43 ++++++ src/com/p2/fileHandling/FileHandlingEx.java | 106 ++++++++++++++ .../ReaderAndWriterClassExample.java | 134 +++++++++++++++++ src/com/p2/fileHandling/package-info.java | 8 ++ .../OverridingAndOverloadingExample.java | 135 ++++++++++++++++++ src/com/p2/polymorphism/package-info.java | 8 ++ 15 files changed, 855 insertions(+), 25 deletions(-) create mode 100644 src/com/p2/collections/CollectionsClassExample.java create mode 100644 src/com/p2/collections/generics/BoundedClass.java create mode 100644 src/com/p2/collections/generics/MaximumTest.java create mode 100644 src/com/p2/collections/list/CollectionExamples.java create mode 100644 src/com/p2/collections/list/package-info.java create mode 100644 src/com/p2/exception/OverridingAndExceptionThrownBySubClass.java create mode 100644 src/com/p2/exception/UserDefinedExceptionExample.java create mode 100644 src/com/p2/fileHandling/FileHandlingEx.java create mode 100644 src/com/p2/fileHandling/ReaderAndWriterClassExample.java create mode 100644 src/com/p2/fileHandling/package-info.java create mode 100644 src/com/p2/polymorphism/OverridingAndOverloadingExample.java create mode 100644 src/com/p2/polymorphism/package-info.java 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 index a14e60b..30be5d8 100644 --- a/src/com/p2/collections/ComparableEx.java +++ b/src/com/p2/collections/ComparableEx.java @@ -1,5 +1,6 @@ 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 @@ -7,7 +8,26 @@ import java.util.*; -//A class 'Movie' that implements Comparable +// 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; @@ -37,23 +57,4 @@ public String getName() { public int getYear() { return year; } -} - -// Driver class -public class ComparableEx { - 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()); - } - } -} +} \ No newline at end of file diff --git a/src/com/p2/collections/ComparatorEx.java b/src/com/p2/collections/ComparatorEx.java index 661298f..37d383c 100644 --- a/src/com/p2/collections/ComparatorEx.java +++ b/src/com/p2/collections/ComparatorEx.java @@ -1,7 +1,11 @@ package com.p2.collections; -// Java program to demonstrate working of Comparator -// interface +/** + * 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. @@ -34,6 +38,7 @@ 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); } } @@ -50,14 +55,14 @@ public static void main(String[] args) { 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/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 index 89b2076..9bd8af8 100644 --- a/src/com/p2/collections/generics/GenericsEx.java +++ b/src/com/p2/collections/generics/GenericsEx.java @@ -3,6 +3,11 @@ 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) { 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/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/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/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 From df6fc7c5848d4b6df8fe1d31f1b3b118a32dc0a6 Mon Sep 17 00:00:00 2001 From: pradeipk Date: Fri, 15 Dec 2017 14:11:06 +0530 Subject: [PATCH 3/3] Added Client code --- src/com/p2/client/CassandraClient.java | 48 ++++++++++ src/com/p2/client/NetClientGet.java | 53 +++++++++++ src/com/p2/client/package-info.java | 8 ++ src/com/p2/io/CurrentDirectoryAndPath.java | 30 ++++++ src/com/p2/json/JsonParserExample.java | 105 +++++++++++++++++++++ src/com/p2/json/package-info.java | 8 ++ src/com/p2/marshalling/package-info.java | 8 ++ src/com/p2/regex/PatternExample.java | 29 ++++++ src/com/p2/regex/RegexExample.java | 27 ++++++ src/com/p2/regex/package-info.java | 39 ++++++++ 10 files changed, 355 insertions(+) create mode 100644 src/com/p2/client/CassandraClient.java create mode 100644 src/com/p2/client/NetClientGet.java create mode 100644 src/com/p2/client/package-info.java create mode 100644 src/com/p2/io/CurrentDirectoryAndPath.java create mode 100644 src/com/p2/json/JsonParserExample.java create mode 100644 src/com/p2/json/package-info.java create mode 100644 src/com/p2/marshalling/package-info.java create mode 100644 src/com/p2/regex/PatternExample.java create mode 100644 src/com/p2/regex/RegexExample.java create mode 100644 src/com/p2/regex/package-info.java 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/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/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/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/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. + +*/ + + +