├── Set Interface in Java ├── Iterator and Iterable Interface ├── Mutex vs Semaphore ├── Marker Interfaces in Java ├── Threads - notify vs notifyAll ├── InterThread and InterProcess Communication ├── README.md ├── Important Websites ├── Size of Int in Java in 64 bit machines ├── Space Complexity of Recursive Calls ├── NoReturnTypeForConstructors ├── IMP Theory Questions in Java ├── Threads in Java ├── Important Youtube Channels ├── static vs dynamic typed languages ├── Threads, Process and Program(Application) ├── Representing Polynomial Time Complexity ├── Two Best Sources to understand Java ├── Important Forums For Help ├── Interface Collection Hierarchy Tree Diagram ├── compareTo(Object o) method in Java ├── Does-adding-a-duplicate-value-to-a-HashSet └── HashMap replace the previous value ├── charArray to String ├── Declare Arrays ├── QuickSelect 2 partitions ├── What is RPC? ├── Behaviour of HashMap and HashSet with duplicate elements ├── Retrieve number of Rows and Columns from [][] array ├── ArrayList of integer array ├── Iterator vs loop for Collection ├── Comparable and Comparator Interface ├── Important Concepts ├── Golden Questions ├── Iterator Interface ├── Integer and int ├── Collection and Collections ├── Creating and Initializing 1D,2D Arrays ├── HashMap Disadvantages ├── Space and Time Complexity ├── String, StringBuilder and StringBuffer ├── Time Complexity of predefined methods in JAVA ├── Self Balancing Search Trees ├── Priority Queue ├── Primitive types and Wrapper Classes ├── Left Right Shift in Java ├── When is 'return null' valid ├── Applications of various data structures ├── Find whether a bit is set in Character or Integer ├── 75 IMP Java Questions ├── Diff between Set and List ├── Threads, synchronized, Lock, volatile └── B and B+ Trees /Set Interface in Java: -------------------------------------------------------------------------------- 1 | http://www.youtube.com/watch?v=9a0wZNI9bQE 2 | -------------------------------------------------------------------------------- /Iterator and Iterable Interface: -------------------------------------------------------------------------------- 1 | http://javapapers.com/core-java/java-iterator/ 2 | -------------------------------------------------------------------------------- /Mutex vs Semaphore: -------------------------------------------------------------------------------- 1 | Source: http://www.geeksforgeeks.org/mutex-vs-semaphore/ 2 | -------------------------------------------------------------------------------- /Marker Interfaces in Java: -------------------------------------------------------------------------------- 1 | http://javarevisited.blogspot.com/2012/01/what-is-marker-interfaces-in-java-and.html 2 | -------------------------------------------------------------------------------- /Threads - notify vs notifyAll: -------------------------------------------------------------------------------- 1 | http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again 2 | -------------------------------------------------------------------------------- /InterThread and InterProcess Communication: -------------------------------------------------------------------------------- 1 | http://programmers.stackexchange.com/questions/174963/inter-process-and-inter-thread-data-sharing 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Learning-Java 2 | ============= 3 | 4 | These are the following links, videos and important text to help you to learn java better 5 | -------------------------------------------------------------------------------- /Important Websites: -------------------------------------------------------------------------------- 1 | http://algorithmsandme.blogspot.com/2014/12/find-median-of-two-sorted-arrays-of.html#.VLOPb5_0_VO 2 | http://www.caveofprogramming.com/youtube/ 3 | -------------------------------------------------------------------------------- /Size of Int in Java in 64 bit machines: -------------------------------------------------------------------------------- 1 | Source: https://github.com/nkatre/TimeComplexityOfPredefinedMethodsInJava/blob/master/Size%20of%20Int%20in%20Java%20in%2064%20bit%20machines 2 | -------------------------------------------------------------------------------- /Space Complexity of Recursive Calls: -------------------------------------------------------------------------------- 1 | Question: Space complexity of recursive algorithm 2 | Source: http://stackoverflow.com/questions/10821059/space-complexity-of-recursive-algorithm 3 | -------------------------------------------------------------------------------- /NoReturnTypeForConstructors: -------------------------------------------------------------------------------- 1 | Question: Why don't constructors have return type in Java ? 2 | Ans: http://stackoverflow.com/questions/6801500/why-do-constructors-in-java-not-have-a-return-type 3 | -------------------------------------------------------------------------------- /IMP Theory Questions in Java: -------------------------------------------------------------------------------- 1 | Just read all the questions on this link. Nothing more is needed on questions regarding the working of Java. 2 | 3 | http://www.java2novice.com/java_interview_questions/ 4 | -------------------------------------------------------------------------------- /Threads in Java: -------------------------------------------------------------------------------- 1 | Watch all 14 videos in the following link 2 | https://www.youtube.com/watch?v=51KeZazThyI&list=PLTZbNwgO5ebr1O4i3CI9XHLJmiKBRRZsL 3 | Each video is of 10 minutes. Watch all of them. 4 | -------------------------------------------------------------------------------- /Important Youtube Channels: -------------------------------------------------------------------------------- 1 | mycodeschool 2 | saurabhschool 3 | visualthinkersnet 4 | SharingIsLearning 5 | InterviewDot Job -> https://www.youtube.com/channel/UCd0U_xlQxdZynq09knDszXA/playlists 6 | Anuranjan Kumar 7 | nptelhrd 8 | -------------------------------------------------------------------------------- /static vs dynamic typed languages: -------------------------------------------------------------------------------- 1 | Question: Whats the difference between statically and dynamically typed languages? 2 | 3 | Question Source: http://www.careercup.com/question?id=56902 4 | 5 | Answer Source: http://campuscoke.blogspot.in/2014/12/whats-difference-between-statically-and.html 6 | -------------------------------------------------------------------------------- /Threads, Process and Program(Application): -------------------------------------------------------------------------------- 1 | http://www.qnx.com/developers/docs/6.4.1/neutrino/getting_started/s1_procs.html 2 | http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread 3 | http://ksearch.wordpress.com/2010/09/12/program-vs-process-vs-thread/ 4 | -------------------------------------------------------------------------------- /Representing Polynomial Time Complexity: -------------------------------------------------------------------------------- 1 | Time Complexity = O(n^(0.5)). O(n^constant) This is valid representation because we have other 2 | time complexities which are valid such as O(n^2) OR O(n^3) etc. Hence polynomial time complexity 3 | always involves mention of n^constant 4 | 5 | Source: http://bigocheatsheet.com/ 6 | -------------------------------------------------------------------------------- /Two Best Sources to understand Java: -------------------------------------------------------------------------------- 1 | Java2novice website: http://www.java2novice.com/java_interview_questions/ 2 | List to all the 152 videos of InterviewDot Job channel on youtube: https://www.youtube.com/playlist?list=PLHyEAfc_mrxbpkMK_dMLNztJVDquEKzfA 3 | 4 | Video number 17 is very very IMP. Prepare all the 75 questions 5 | -------------------------------------------------------------------------------- /Important Forums For Help: -------------------------------------------------------------------------------- 1 | github.com (Search the content in "All repositories", surely if the relevant code is uploaded on github and 2 | made public then you will find it) 3 | http://algorithmsandme.blogspot.com/2014/12/find-median-of-two-sorted-arrays-of.html#.VLOPb5_0_VO 4 | careercup.com 5 | geeksforgeeks.com 6 | quora.com 7 | -------------------------------------------------------------------------------- /Interface Collection Hierarchy Tree Diagram: -------------------------------------------------------------------------------- 1 | Please refer all the below sources, in the order as mentioned below: 2 | 1. http://www.falkhausen.de/en/diagram/html/java.util.Collection.html 3 | 2. http://way2java.com/collections/java-collections-interfaces-hierarchy/ 4 | 3. http://www.programcreek.com/2009/02/the-interface-and-class-hierarchy-for-collections/ 5 | -------------------------------------------------------------------------------- /compareTo(Object o) method in Java: -------------------------------------------------------------------------------- 1 | The compareTo(Object o) method is a method of the Comparable Interface (and not Comparator Interface) 2 | 3 | 4 | Its VERY IMPORTANT to learn this method thoroughly. 5 | 6 | Please watch the Youtube video mentioned in the below link which explains this method very well. 7 | This video is only of 6 minutes. Please watch it carefully. 8 | 9 | http://www.youtube.com/watch?v=iTC43mLZG38 10 | -------------------------------------------------------------------------------- /Does-adding-a-duplicate-value-to-a-HashSet/HashMap replace the previous value: -------------------------------------------------------------------------------- 1 | Please consider the below piece of code: 2 | 3 | HashSet hs = new HashSet(); 4 | hs.add("hi"); -- (1) 5 | hs.add("hi"); -- (2) 6 | hs.size() will give 1 as HashSet doesn't allow duplicates so only one element will be stored. 7 | 8 | I want to know if we add the duplicate element, then does it replace the previous element or it simply doesn't add it? 9 | 10 | Also, what will happen usingHashMap for the same case? 11 | 12 | 13 | Answer -> 14 | 15 | In the case of HashMap, it replaces the old value with the new one. 16 | 17 | In the case of HashSet, the item isn't inserted. 18 | -------------------------------------------------------------------------------- /charArray to String: -------------------------------------------------------------------------------- 1 | The fastest method present in String class in JAVA to convert charArray to String is the static method of String class 2 | called valueOf(charArray[]) OR String(char[]) constructor. 3 | 4 | Source: http://stackoverflow.com/questions/7655127/how-to-convert-a-char-array-back-to-a-string-java 5 | 6 | PLEASE DO REMEMBER THIS 7 | 8 | Example: 9 | public static String sortString(String s){ 10 | char[] array = s.toCharArray(); 11 | Arrays.sort(array); 12 | return String.valueOf(array); // convert char array to String 13 | OR 14 | return (new String(array)); // convert char array to String. String class has String(char[]) constructor 15 | } 16 | -------------------------------------------------------------------------------- /Declare Arrays: -------------------------------------------------------------------------------- 1 | Question: All possible ways to declare an array in JAVA 2 | Source: http://stackoverflow.com/questions/1200621/declare-array-in-java 3 | 4 | NOTE: Every array of any Primitive(int,char,......,etc) OR ObjectTypes(LinkedList[] <--- array of linked list) 5 | is an " instantiated object". i.e. Every array (be it of primitive or object type is an "object") 6 | 7 | For Integer Array: 8 | 1.int[] intArray = new int[3]; 9 | 2.int[] intArray = new int[]{10,20,30}; 10 | 3.int[] intArray = {10,20,30}; 11 | 12 | For String Array: 13 | String[] myStringArray = new String[3]; 14 | String[] myStringArray = new String[]{"a","b","c"}; 15 | String[] myStringArray = {"a","b","c"}; 16 | -------------------------------------------------------------------------------- /QuickSelect 2 partitions: -------------------------------------------------------------------------------- 1 | Two Types of Partition Exists in QuickSelect 2 | Source: http://cs.stackexchange.com/questions/11458/quicksort-partitioning-hoare-vs-lomuto 3 | 1. Lomuto -> To understand this watch this video: https://www.youtube.com/watch?v=MZaf_9IZCrc 4 | 2. Hoare -> Normal i and j counter partition 5 | The code for Hoare parition is: 6 | private static int partition(int[] a, int low, int high) { 7 | 8 | int i = low; 9 | int j = high; 10 | int temp = 0; 11 | 12 | int pivot = a[low+(high-low)/2]; 13 | 14 | while(i<=j){ 15 | while(a[i]pivot) 18 | j--; 19 | if(i>j) 20 | break; 21 | else{ // if(i<=j) 22 | temp=a[i]; 23 | a[i]=a[j]; 24 | a[j]=temp; 25 | i++; 26 | j--; 27 | } 28 | } 29 | return i; // return the pivot index 30 | 31 | } 32 | */ 33 | -------------------------------------------------------------------------------- /What is RPC?: -------------------------------------------------------------------------------- 1 | Question : What is RPC ? 2 | 3 | Source: http://searchsoa.techtarget.com/definition/Remote-Procedure-Call 4 | 5 | Remote Procedure Call (RPC) is a protocol that one program can use to request 6 | a service from a program located in another computer in a network without having 7 | to understand network details. (A procedure call is also sometimes known as a function call 8 | or a subroutine call.) RPC uses the client/server model. The requesting program is a client 9 | and the service-providing program is the server. Like a regular or local procedure call, 10 | an RPC is a synchronous operation requiring the requesting program to be suspended until 11 | the results of the remote procedure are returned. However, the use of lightweight processes 12 | or threads that share the same address space allows multiple RPCs to be performed concurrently. 13 | -------------------------------------------------------------------------------- /Behaviour of HashMap and HashSet with duplicate elements: -------------------------------------------------------------------------------- 1 | Please consider the below piece of code: 2 | 3 | HashSet hs = new HashSet(); 4 | hs.add("hi"); -- (1) 5 | hs.add("hi"); -- (2) 6 | hs.size() will give 1 7 | 8 | I want to know if we add the duplicate element, then does it replace the previous element or it simply doesn't add it? 9 | 10 | Also, what will happen usingHashMap for the same case? 11 | 12 | 13 | Answer -> 14 | 15 | Now in HashMap, it replaces the old value with the new one. 16 | 17 | Also in the case of HashSet, the old is replaced with the new one. 18 | 19 | 20 | Both of them dont allow duplicates, the old is replaced with the new value. 21 | 22 | 23 | Only in case of LinkedList, duplicates are allowed. 24 | 25 | Between LL, HashMap and HashSet -> LL is the data structure which allows duplicates. The rest two dont allow 26 | duplicates. 27 | -------------------------------------------------------------------------------- /Retrieve number of Rows and Columns from [][] array: -------------------------------------------------------------------------------- 1 | /* 2 | This is a sample program to show how to retrieve the number of columns and rows from multidimentional array 3 | */ 4 | 5 | 6 | package forTesting; 7 | 8 | public class sampleTest { 9 | public static void main(String[] args) { 10 | int[] array = new int[10]; // declare an array with 10 rows 11 | 12 | int[][] multiDimensional = new int[5][10]; // declare an array with 5 rows and 10 columns 13 | 14 | System.out.println(array.length); // get the number of rows 15 | System.out.println("Number of Rows of multi dimentional array: "+multiDimensional.length); // get the number of rows 16 | System.out.println("Number of Columns of multi dimentional array: "+multiDimensional[0].length); // get the number of columns 17 | } 18 | } 19 | 20 | 21 | /* 22 | Output: 23 | 10 24 | Number of Rows of multi dimentional array: 5 25 | Number of Columns of multi dimentional array: 10 26 | */ 27 | -------------------------------------------------------------------------------- /ArrayList of integer array: -------------------------------------------------------------------------------- 1 | Question: How to create an ArrayList of integer array 2 | Source: http://stackoverflow.com/questions/13665188/arraylist-of-integer-arrays-in-java 3 | 4 | Ans. 5 | List list = new ArrayList(); 6 | OR 7 | ArrayList list = new ArrayList(); 8 | 9 | First of all, several of the other answers are misleading and/or incorrect. 10 | Note that an array is an object. So you can use them as elements in a list, no matter 11 | whether the arrays themselves contain primitive types or object references. 12 | 13 | Next, declaring a variable as List list is preferred over declaring it as ArrayList. 14 | This allows you to easily change the List to a LinkedList or some other implementation without breaking 15 | the rest of your code because it is guaranteed to use only methods available in the List interface. 16 | For more information, you should research "programming to the interface." 17 | -------------------------------------------------------------------------------- /Iterator vs loop for Collection: -------------------------------------------------------------------------------- 1 | // NOTE 1: Arrays.sort, Collections.sort etc use quicksort which is inplace sorting algo. Hence these methods are void 2 | /* 3 | * Note 2: While iterating over Collection, if we are making modification to Collection 4 | * then we sould use Iterator for iterating 5 | * 6 | * If we are not making any modification, then we can use get(int index) method 7 | * Example: List meetings = new ArrayList(); 8 | * int count=0; 9 | * Meeting curr=null; 10 | * Meeting prev = meetings.get(0); 11 | * for(int i=1;i To Remember: eater.Hence the method name is compare(Object o1, Object o2) 8 | But for balance it has the second method as well which is equals(Object o) 9 | Comparable -> To Remember: keep the thing. Hence the method is compareTo(Object o). But this is the only method 10 | that it has. 11 | 12 | 13 | Comparator belongs to util package 14 | Comparable belongs to lang package 15 | 16 | Comparator is used for user-defined ordering 17 | Comparable is used for natural ordering 18 | 19 | Both are interfaces and support generics: 20 | Interface Comparator 21 | Interface Comparable 22 | 23 | Also before going to the video tutorials, please read the java docs for Comparator and Comparable. 24 | 25 | http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html 26 | http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html 27 | -------------------------------------------------------------------------------- /Important Concepts: -------------------------------------------------------------------------------- 1 | Important Java Questions: 2 | 3 | 1) Difference betweeen Class, Object and Instance 4 | Link is -> http://alfredjava.wordpress.com/2008/07/08/class-vs-object-vs-instance/ 5 | http://wiki.answers.com/Q/Difference_between_instance_and_object#slide=2 6 | 7 | 2) super keyword with example 8 | 9 | The super is a reference variable that is used to refer immediate parent class object. 10 | 11 | Whenever you create the instance of subclass, an instance of parent class is created implicitly 12 | i.e. referred by super reference variable. 13 | 14 | Usage of super Keyword: 15 | -> super is used to refer immediate parent class instance variable. 16 | -> super() is used to invoke immediate parent class constructor. 17 | super() is added in each class constructor automatically by compiler. 18 | Please see the link: http://www.javatpoint.com/super-keyword 19 | -> super is used to invoke immediate parent class method. 20 | 21 | Examples given in this link. Source: http://www.javatpoint.com/super-keyword 22 | 23 | 24 | 3) Difference between Error and Exceptions(Clearly explained in the Youtube Channel "SharingIsLearning" 25 | in the video titled as "Exception Handling" 26 | Link is -> https://www.youtube.com/watch?v=vjmMF9ZZkiQ 27 | -------------------------------------------------------------------------------- /Golden Questions: -------------------------------------------------------------------------------- 1 | Question: GOLDEN QUESTIONS to be asked for every program that you type 2 | Ans. 3 | TR: SEBI SAUCY check 4 | (SEBI SOSI) 5 | 6 | This kind of checking is called SEBI-SOSI check, which is mandatory for every program. 7 | 8 | SEBI SOSI check: 9 | S -> Sample Input 10 | E -> Extreme Cases 11 | B -> Bugs 12 | I -> Iterative or Recursive 13 | 14 | S -> Streamlined 15 | O -> Optimal 16 | S -> Space and Time Complexity 17 | I -> Improve Space and Time Complexity 18 | 19 | Questions to be asked for each program: 20 | 1. Did you test the code for SAMPLE inputs ? If no, then test it for sample inputs. 21 | 2. Did you handle EXTREME cases when the input is null, or 1, or 2 ? No, then handle the extreme cases. 22 | 3. Does the program have BUGS ? If yes, then remove the bugs. 23 | 4. Is the solution ITERATIVE or recursive ? If recursive, then implement iterative solution if it exists. 24 | 5. Is the solution STREAMLINED ? Are all import statement included. If not streamlined then make it streamlined 25 | 6. Is the solution OPTIMAL ? If no, then make it optimal 26 | 7. What is the SPACE and time complexity ? 27 | 8. Can you IMPROVE the space and time complexity ? If yes, then improve the space and time complexity 28 | 29 | FOLLOW EVEYTHING MENTIONED ABOVE RELIGIOUSLY FOR EVERY PROGRAM THAT YOU TYPE. 30 | -------------------------------------------------------------------------------- /Iterator Interface: -------------------------------------------------------------------------------- 1 | IMP link for understanding Iterator Interface in Java 2 | 3 | 4 | http://www.youtube.com/watch?v=5TaZbcXkpxs 5 | 6 | 7 | 8 | The following below classes implement the Iterator Interface: 9 | 10 | 11 | All Known Implementing Classes: 12 | AbstractCollection, AbstractList, AbstractQueue, 13 | AbstractSequentialList, AbstractSet, ArrayBlockingQueue, 14 | ArrayDeque, ArrayList, AttributeList, BatchUpdateException, 15 | BeanContextServicesSupport,BeanContextSupport, ConcurrentLinkedQueue, 16 | ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DataTruncation, 17 | DelayQueue, EnumSet, HashSet, JobStateReasons,LinkedBlockingDeque, 18 | LinkedBlockingQueue, LinkedHashSet, LinkedList, PriorityBlockingQueue, 19 | PriorityQueue, RoleList, RoleUnresolvedList, RowSetWarning, SerialException, 20 | ServiceLoader,SQLClientInfoException, SQLDataException, SQLException, 21 | SQLFeatureNotSupportedException, SQLIntegrityConstraintViolationException, 22 | SQLInvalidAuthorizationSpecException,SQLNonTransientConnectionException, 23 | SQLNonTransientException, SQLRecoverableException, SQLSyntaxErrorException, 24 | SQLTimeoutException, SQLTransactionRollbackException,SQLTransientConnectionException, 25 | SQLTransientException, SQLWarning, Stack, SyncFactoryException, SynchronousQueue, 26 | SyncProviderException, TreeSet, Vector 27 | -------------------------------------------------------------------------------- /Integer and int: -------------------------------------------------------------------------------- 1 | Question -> I am confused as to why Integer and int can be used interchangeably in Java even though 2 | one is a primitive type and the other is an object? 3 | 4 | For example: 5 | 6 | Integer b = 42; 7 | int a = b; 8 | 9 | Or 10 | 11 | int d = 12; 12 | Integer c = d; 13 | 14 | 15 | 16 | Answer: 17 | 18 | You can’t put an int (or other primitive value) into a collection. Collections can only hold object 19 | references, so you have to box primitive values into the appropriate wrapper class (which is "Integer" in 20 | the case of int). When you take the object out of the collection, you get the Integer that you put in; 21 | if you need an int, you must unbox the Integer using the "intValue()" method. All of this boxing and unboxing 22 | is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, 23 | eliminating the pain and the clutter. 24 | 25 | That is basically it in a nutshell. It allows you take advantage of the Collections Framework 26 | for primatives without having to do the work yourself. 27 | 28 | The primary disadvantage is that it confuses new programmers, and can lead to messy/confusing 29 | code if it's not understood and used correctly. 30 | 31 | 32 | This matter is taken from the following link: http://stackoverflow.com/questions/7121581/why-can-integer-and-int-be-used-interchangably 33 | -------------------------------------------------------------------------------- /Collection and Collections: -------------------------------------------------------------------------------- 1 | Collection is an interface in java which is implemented by List, Set and Map. 2 | Collections is a class in Java which consists of famous methods such as Collections.sort() method. 3 | All methods of Collections class are static methods. 4 | 5 | Please go through all the classes and interfaces which implement Collection. 6 | The following is the link for java docs: http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html 7 | 8 | Whereas Collections is a proper class in java which consists of some famous predefined methods such as Collections.sort() method. 9 | All methods of Collections class are static methods. 10 | Please go through the following link for more details on the Collections class: 11 | http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html 12 | 13 | Whereas Comparable (compareTo(Object o) method) and Comparator(compare(Object o1, Object o2) and equals(Object o)), 14 | both are interfaces in Java. 15 | 16 | THE MOST IMPORTANT OF ALL. 17 | 18 | Please go through the channel "SharingIsLearning" on Youtube. In this channel, the author has very nicely explained 19 | the Collection interface and Collections class in detail and very precise. The total videos for the Collection interface 20 | is about 4 videos. Please watch all the 4 videos (Each video is of hardly 6 minutes). 21 | They are very helpful. 22 | 23 | 24 | The following are the URL's of the above mentioned videos: 25 | 1) Java Collection -> https://www.youtube.com/watch?v=NGccvHsIU3A 26 | 2) List and Family -> https://www.youtube.com/watch?v=KCKrHDLZjT8 27 | 3) Set and Map -> https://www.youtube.com/watch?v=gRWloZnqvTQ 28 | 4) Java Collection Hands On -> https://www.youtube.com/watch?v=j3EUDM1NpDc 29 | -------------------------------------------------------------------------------- /Creating and Initializing 1D,2D Arrays: -------------------------------------------------------------------------------- 1 | In the below mentioned program, we undersand two things: 2 | 3 | 1. This is to understand creating and initializing 1D, 2D arrays. Doing initialization and creation in the same step, 4 | does not require 'new' operator. PLEASE UNDERSTAND CAREFULLY, how this is done. 5 | 6 | 2. We also understand, how to access the number of rows and columns in 2D arrays. PLEASE UNDERSTAND CAREFULLY. 7 | 8 | 9 | package forTesting; 10 | 11 | public class SingleAndMultiDimentionalArraysInitialization { 12 | public static void main(String[] args) { 13 | // Initializing single dimensional arrays. Doing initialization and creation in the same step, does not require 'new' operator. 14 | String[] OneDArray = {"hello","world","my","name","is"}; 15 | int[] intArray = {1,2,3,4,5,6,7,8}; 16 | 17 | // Initialzing 2d array. Doing initialization and creation in the same step, does not require 'new' operator. 18 | String[][] TwoDArray = {{"hello","world"},{"hi","bye"},{"me","tu"},{"aapli","aapla"}}; // 4*2 array 19 | int[][] intTwoArray = {{1,2,3},{4,5,6},{8,9,10},{11,12,13},{14,15,16}}; // 3*5 array 20 | //Use 2D array 21 | int[][] maze = new int[6][6]; 22 | maze[0] = new int[] { 1, 1, 0, 0, 0, 0 }; 23 | maze[1] = new int[] { 0, 1, 0, 0, 0, 0 }; 24 | maze[2] = new int[] { 0, 1, 0, 1, 1, 1 }; 25 | maze[3] = new int[] { 1, 1, 1, 1, 0, 1 }; 26 | maze[4] = new int[] { 0, 1, 0, 0, 0, 1 }; 27 | maze[5] = new int[] { 0, 1, 0, 0, 0, 1 }; 28 | 29 | // Accessing number of rows and columns in multidimentional arrays 30 | int rows = TwoDArray.length; // Gives number of rows 31 | int columns = TwoDArray[0].length; // Gives number of coulmns 32 | 33 | System.out.println(rows); 34 | System.out.println(columns); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /HashMap Disadvantages: -------------------------------------------------------------------------------- 1 | Very IMP Q -> Disadvantages of HashMap or Hashtable OR Why is BALANCED TREES better than using Hashtable 2 | or HashMap? 3 | Ans -> 4 | In short: 5 | 1) Requires more main memory 6 | 2) Hashing algorithm does not result in spatial locality. Because hash tables cause 7 | access patterns that jump around, this can trigger microprocessor cache misses that cause long delays. 8 | 3) Similar key types will result in more collision and hence the hashtable would be more like a linkedlist. 9 | Collisions also ruin memory utilization- if I have 70 elements in 100 buckets, but those 70 elements hash to 10 | only 4 buckets (and yes, Virginia, I’ve seen collision rates this bad), then 96 of my buckets aren’t doing 11 | me any good at, I’m just wasting that space. 12 | 4) Occasionally HashMap/Hashtable requires resizing when the original size of HashMap/Hashtable buckets 13 | are full. Resizing takes O(n) time as the elements from the previous hashtable/HashMap are transferred to 14 | a new bigger Hashtable/HashMap. This is not good for implementation. 15 | 5) The concept that Hashtables/HashMap offers O(constant) (aka O(1) ) time complexity 16 | for insertion, deletion and searching is something to rethink on as the datastructure gives that 17 | time complexity on a average scale, which is called as "AMORTIZED" time complexity. That means that there 18 | would be atleast one instance out of n instances where the Time Complexity would be O(n) and not O(constant). 19 | This is the time when the HashMap/Hashtable requires resizing. 20 | 21 | http://stackoverflow.com/questions/6924852/what-are-the-disadvantages-to-hashmaps 22 | http://web.archive.org/web/20090430172748/http://enfranchisedmind.com/blog/posts/problems-with-hash-tables/ 23 | http://en.wikipedia.org/wiki/Hash_table#Drawbacks 24 | -------------------------------------------------------------------------------- /Space and Time Complexity: -------------------------------------------------------------------------------- 1 | The time and space complexities are not related to each other. 2 | They are used to describe how much space/time your algorithm takes based on the input. 3 | 4 | For example When the algorithm has space complexity of: 5 | 6 | O(1) - constant - the algorithm uses a fixed (small) amount of space which 7 | doesn't depend on the input. For every size of the input the algorithm will take 8 | the same (constant) amount of space. This is the case in your example as the input 9 | is not taken into account and what matters is the time/space of the print command. 10 | 11 | O(n), O(n^2), O(log(n))... - these indicate that you create additional objects based 12 | on the length of your input. For example creating a copy of each object of v storing 13 | it in an array and printing it after that takes O(n) space as you create n additional objects. 14 | 15 | Your example is an example that time and space complexity might be different. 16 | It takes v.length * print.time to print all the elements. But the space is always 17 | the same - O(1) because you don't create additional objects. 18 | 19 | In contrast the time complexity describes how much time your algorithm consumes based 20 | on the length of the input. Again: 21 | 22 | O(1) - no matter how big is the input it always takes a constant time - for example only one 23 | instruction. Like 24 | 25 | function(list l) { print("i got a list"); } 26 | 27 | O(n), O(n^2), O(log(n)) - again it's based on the length of the input. For example 28 | 29 | function(list l) { 30 | for(node in l) { 31 | print(node); 32 | } 33 | } 34 | Note that both last examples take O(1) space as you don't create anything. Compare it to 35 | 36 | function(list l) { 37 | list c; 38 | for(node in l) { 39 | c.add(node); 40 | } 41 | } 42 | which takes O(n) space 43 | -------------------------------------------------------------------------------- /String, StringBuilder and StringBuffer: -------------------------------------------------------------------------------- 1 | String -> Immutable 2 | StringBuilder -> Mutable(can be changed) 3 | StringBuffer -> Mutable(can be changed) 4 | The only difference between StringBuffer and StringBuilder is StringBuffer is thread-safe, that is StringBuffer is synchronized. 5 | whereas StringBuilder is NOT thread-safe, that is StringBuilder is NOT synchronized. 6 | 7 | Difference between StringBuilder and StringBuffer: 8 | StringBuilder -> provides NO ThreadSafety(means all methods of StringBuilder are not synchronized) 9 | hence no performance overhead 10 | StringBuffer -> provides ThreadSafety(means all methods of StringBuffer are synchronized) 11 | hence it has some performance overhead 12 | 13 | When to use StringBuilder and StringBuffer: 14 | In multithreaded system, where thread safety is required, we use StringBuffer 15 | In normal programs, we use StringBuilder, since it has NO threadsafety overhead and hence it is fast. 16 | 17 | 18 | Please go throughly through the following YouTube link, in the video it is explained very nicely. 19 | http://www.youtube.com/watch?v=nQHVt-nOpxQ 20 | 21 | Also go through the Java documentation for: 22 | 1) String -> http://docs.oracle.com/javase/7/docs/api/java/lang/String.html 23 | 2) StringBuilder -> http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html 24 | 3) StringBuffer -> http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html 25 | 26 | 27 | Example: 28 | Question -> For a given string of some sentence, reverse words in that sentence. 29 | Ex: I am Don , return Don am I 30 | Solution: 31 | 32 | 33 | 34 | public class ReverseArray { 35 | public static void main(String[] args) { 36 | 37 | String givenString = "Am I bad ? "; 38 | StringBuilder reverse=new StringBuilder(givenString.length()); 39 | for(int i=givenString.length()-1;i>=0;i--){ 40 | reverse.append(givenString.charAt(i)); 41 | } 42 | System.out.println(reverse.toString()); 43 | 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Time Complexity of predefined methods in JAVA: -------------------------------------------------------------------------------- 1 | NOTE: For updated version of this file, please redirect to 2 | https://github.com/nkatre/IMP-Interview-Questions/blob/master/Time%20Complexity%20of%20predefined%20methods%20in%20JAVA 3 | 4 | *************************************************************************************************** 5 | I. Time Complexity of substring() method in Java String class 6 | *************************************************************************************************** 7 | 8 | Question: What is the time complexity of the following program ? 9 | 10 | public static void calculateTimeComplexity(String s){ 11 | for(int i=0;i=0;j--){ 13 | System.out.println(s.substring(j,i+1)); 14 | } 15 | } 16 | } 17 | 18 | Options: 1. O(n^2) 19 | 2. O(n^3) 20 | where n = length of the string 21 | 22 | 23 | Solution: 24 | 25 | Answer is option 2. O(n^3) 26 | 27 | Source: http://stackoverflow.com/questions/4679746/time-complexity-of-javas-substring 28 | http://stackoverflow.com/questions/16123446/java-7-string-substring-complexity 29 | http://stackoverflow.com/questions/25514062/what-is-the-time-complexity-of-java-stringbuilder-substring-method-if-it-is-l 30 | 31 | Explanation: 32 | It was O(1) in older versions of Java - as Jon stated, it just created a new String with the same underlying char[], 33 | and a different offset and length. 34 | However, this has actually changed started with Java 7 update 6. 35 | The char[] sharing was eliminated, and the offset and length fields were removed. substring() now just copies all the 36 | characters into a new String. 37 | Ergo, substring is O(n) in Java 7 update 38 | 39 | 40 | *************************************************************************************************** 41 | II. Time Complexity of Arrays.sort() method 42 | *************************************************************************************************** 43 | Soltion: The time complexity of this predefined method of Arrays class is nlgn 44 | Source: http://stackoverflow.com/questions/4254122/what-is-the-time-complexity-of-this-sort-method?rq=1 45 | -------------------------------------------------------------------------------- /Self Balancing Search Trees: -------------------------------------------------------------------------------- 1 | First of all let us clear a concept that: 2 | 2-3-4(aka 2-4) Trees are search(i.e. left subtree is less than right subtree) trees 3 | but not Binary(i.e. atmost 2 children) Search Trees. 4 | 5 | Whereas, both AVL Trees and Red Black Trees are "self balancing" BINARY SEARCH TRESS. 6 | 7 | Exact meaning of few IMP words: 8 | Search means "Left subtree is always less than right subtree" 9 | Binary means "Atmost 2 children" 10 | 2-3-4(aka 2-4) means "either 2 or 3 or 4 children" (cannot have 0 or 1 children) 11 | 12 | 13 | 14 | In order for the search trees to be effective the MANTRA that everyone teaches is that: 15 | "The height of the tree should be log(n) [to the base 2]" -> Always remember this 16 | If any tree satisfies this MANTRA then its an efficient Tree for searching operations. 17 | 18 | 19 | Question -> What are some real-world applications of Red-Black trees today? 20 | Answer: There are two popular Balanced Binary Search Tree: AVL Tree and Red-Black Tree. 21 | Both offers O(lg n) search time. But the hidden constant behind Big O makes AVL Tree more 22 | suitable for search and Red-Black Tree for insertion-deletion. Insertion-deletion takes less 23 | time in Red-Black Tree than AVL Tree. That's Red-Black Tree are more popular than AVL Tree although 24 | implementing Red-Black is very complicated task. 25 | 26 | 27 | Video for understanding balancing in AVL Trees: 28 | http://www.youtube.com/watch?v=ij1gSage9uA 29 | 30 | 31 | IMP NOTE: 32 | To understand RB Trees, you have to first understand 2-3-4 Trees (aka 2-4 Trees). 33 | The following are the best videos for understanding 2-3-4 (or 2-4) Trees. 34 | Basics of 2-3-4(aka 2-4) Trees -> http://www.youtube.com/watch?v=47u7RU0XNR0 35 | Bottom Up and Top Down 2-3-4(aka 2-4) Trees -> http://www.youtube.com/watch?v=2679VQ26Fp4 36 | IMP concepts of 2-3-4(aka 2-4) Trees -> http://www.youtube.com/watch?v=JZhdUb5F7oY&list=PL104E2710A064F69E [The author talks about 2-3-4(aka 2-4) Tress from the 11th minute in this video] 37 | Insertion in 2-3-4(aka 2-4) Trees -> http://www.youtube.com/watch?v=uIWLCfT9daI 38 | Deletion in 2-3-4(aka 2-4) Trees -> http://www.youtube.com/watch?v=M_z-qYOY5JQ 39 | 40 | 41 | Video for understanding Red Black Trees: 42 | http://www.youtube.com/watch?v=JRsN4Oz36QU&list=PL104E2710A064F69E 43 | http://www.youtube.com/watch?v=6QOKk_pcv3U&list=PL104E2710A064F69E 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Priority Queue: -------------------------------------------------------------------------------- 1 | 2 | Best Explanation for arranging elements according to user defined priority in Java defined Priority Queue 3 | 4 | 5 | Source of below explanation: http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue 6 | 7 | 8 | 9 | Use the constructor overload which takes a Comparator comparator and pass in a comparator 10 | which compares in the appropriate way for your sort order. If you give an example of how you want to sort, 11 | we can provide some sample code to implement the comparator if you're not sure. (It's pretty 12 | straightforward though.) 13 | 14 | As has been said elsewhere: offer and add are just different interface method implementations. 15 | In the JDK source I've got, add calls offer. Although add and offer have potentially different 16 | behaviour in general due to the ability for offer to indicate that the value can't be added due 17 | to size limitations, this difference is irrelevant in PriorityQueue which is unbounded. 18 | 19 | Here's an example of a priority queue sorting by string length: 20 | 21 | 22 | 23 | package Demo; 24 | 25 | 26 | 27 | //Test.java 28 | 29 | import java.util.Comparator; 30 | 31 | import java.util.PriorityQueue; 32 | 33 | 34 | 35 | public class Test 36 | 37 | { 38 | 39 | public static void main(String[] args) 40 | 41 | { 42 | 43 | Comparator comparator = (Comparator) new StringLengthComparator(); 44 | 45 | PriorityQueue queue = new PriorityQueue(10, comparator); 46 | 47 | queue.add("short"); 48 | 49 | queue.add("very long indeed"); 50 | 51 | queue.add("medium"); 52 | 53 | while (queue.size() != 0) 54 | 55 | { 56 | 57 | System.out.println(queue.remove()); 58 | 59 | } 60 | 61 | } 62 | 63 | } 64 | 65 | package Demo; 66 | 67 | 68 | 69 | 70 | 71 | //StringLengthComparator.java (new java file) 72 | 73 | import java.util.Comparator; 74 | 75 | 76 | 77 | public class StringLengthComparator implements Comparator 78 | 79 | { 80 | 81 | @Override 82 | 83 | public int compare(String x, String y) 84 | 85 | { 86 | 87 | // Assume neither string is null. Real code should 88 | 89 | // probably be more robust 90 | 91 | if (x.length() < y.length()) 92 | 93 | { 94 | 95 | return -1; 96 | 97 | } 98 | 99 | if (x.length() > y.length()) 100 | 101 | { 102 | 103 | return 1; 104 | 105 | } 106 | 107 | return 0; 108 | 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /Primitive types and Wrapper Classes: -------------------------------------------------------------------------------- 1 | There are eight primitive types in Java. Since Java still has these primitive types, hence it cannot be said that 2 | Java is PURE OBJECT ORIENTED LANGUEAGE. Hence Java is said to be OBJECT ORIENTED but NOT PURE OBJECT ORIENTED 3 | LANGUAGE. 4 | 5 | The eight primitive types are: 6 | (Source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) 7 | char 8 | byte 9 | short 10 | int 11 | long 12 | float 13 | double 14 | boolean 15 | 16 | Whereas the following are the datatypes in Java: 17 | String (Please note that in String S is capital) 18 | char 19 | byte 20 | short 21 | int 22 | long 23 | float 24 | double 25 | boolean 26 | 27 | Every primitive type has its own wrapper class and their respective important methods used while 28 | implementing Comparator or Comparable interface are: 29 | 30 | 31 | Character -> compare(char x, char y) , compareTo(Character anotherCharacter) "compareTo compares Character objects" 32 | Byte -> compareTo(Byte anotherByte) "Byte wrapper class does not have compare method" 33 | Short -> compare(short x, short y) , compareTo(Short anotherShort) 34 | Integer -> compare(int x, int y) , compareTo(Integer anotherInteger) 35 | Long -> compare(long x, long y) , compareTo(Long anotherLong) 36 | Float -> compare(float f1, float f2) , compareTo(Float anotherFloat) 37 | Double -> compare(double d1, double d2) , compareTo(Double anotherDouble) 38 | Boolean -> compare(boolean x, boolean y) , compareTo(Boolean b) 39 | String -> compareTo(String anotherString) , compareToIgnoreCase(String str) "In String, both compare and 40 | compareTo methods have String objects" 41 | 42 | IMP: All the wrapper classes have compareTo() method. Only Byte and String does not have compare() method 43 | 44 | Please NOTE: 45 | 1) (VERY IMP) If we declare or initialize a string with small "s", it will give compilation ERROR. 46 | String in Java is always defined and declared with capital "S" 47 | 2) As learned in the above mentioned IMP methods, compareTo() method always uses Object(also in case of Byte 48 | Wrapper class), whereas compare() method always uses primitive data type(Byte wrapper class does not have 49 | compare() method) 50 | 3) compare(T o1, T o2) method of Comparator interface has both arguments as Objects 51 | (Source: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html) 52 | compareTo(T o) method of Comparable interface has arguments as Object 53 | That means while overriding compare() and compareTo() methods we have to use ojects as arguments since 54 | these methods are overridden from respective Comparator and Comparable interfaces 55 | -------------------------------------------------------------------------------- /Left Right Shift in Java: -------------------------------------------------------------------------------- 1 | VERY IMPORTANCE SOURCES: 2 | http://www.xyzws.com/javafaq/how-do-the-bitwise-shift-operators-work/12 3 | http://stackoverflow.com/questions/10910913/how-do-shift-operators-work-in-java 4 | 5 | Summary: 6 | 1. RIGHT SHIFT (>>) 7 | In >>, the void bits are filled in with previous contents of the leftmost bit.(FOR BOTH POSITIVE AND NEGATIVE NUMBERS) 8 | Note that right shifting ( >> ) always preserves the sign of the original number i.e. to say that a negative number will 9 | stay negative while a positive number will stay positive after a right shift ( >> ). 10 | 11 | Example: 12 | Consider 12 whose binary equivalent is 00000000 00000000 00000000 00001100 (binary for 32 bits). 13 | Remember that the type operands (such as byte and short) are implicitly promoted to the int type before 14 | any shift operators are applied. Let's shift it right 2 times. 15 | 16 | 00000000 00000000 00000000 00001100 >> 2(times) 17 | When shifting right ( >> ) the leftmost bits exposed by the right shift are filled in with previous contents 18 | of the leftmost bit. This is the result of (12>>2): 19 | 20 | 00000000 00000000 00000000 00000011 (3) 21 | Consider -12 whose binary equivalent is 11111111 11111111 11111111 11110100 (binary for 32 bits). 22 | Let's shift it right 2 times. 23 | 24 | 11111111 11111111 11111111 11110100 >> 2(times) 25 | When shifting right ( >> ) the leftmost bits exposed by the right shift are filled in with previous contents of 26 | the leftmost bit. This is the result of (-12>>2): 27 | 28 | 11111111 11111111 11111111 11111101 (-3) 29 | 30 | 2. Unsigned Right Shift Operator (>>>) 31 | In >>, the void bits are filled with 0's.(FOR BOTH POSITIVE AND NEGATIVE NUMBERS) 32 | Let's do 00000000 00000000 00000000 00001100 >>> 2 (12>>>2) and the result is 00000000 00000000 00000000 00000011 (3). 33 | Let's do 11111111 11111111 11111111 11110100 >>> 2 (-12>>>2) and the result is 00111111 11111111 11111111 11111101 (1073741821). 34 | 35 | 3. LEFT SHIFT (<<) 36 | In <<, the void left behind by the shift is filled by zero's. (FOR BOTH POSITIVE AND NEGATIVE NUMBERS) 37 | 38 | Example: 39 | Consider 12 whose binary equivalent is 00000000 00000000 00000000 00001100 (binary for 32 bits). 40 | Remember that the type operands (such as byte and short) are implicitly promoted to the int type before any shift 41 | operators are applied. Let's shift it left 2 times. 42 | 43 | 00000000 00000000 00000000 00001100 << 2(times) 44 | When you shift left ( << ) the void left behind by the shift is filled by zero's. This is the result of (12<<2): 45 | 46 | 00000000 00000000 00000000 00110000 (48) 47 | Consider -12 whose binary equivalent is 11111111 11111111 11111111 11110100 (binary for 32 bits). Let's shift it left 2 times. 48 | 49 | 11111111 11111111 11111111 11110100 << 2(times) 50 | When you shift left ( << ) the void left behind by the shift is filled by zero's. This is the result of (-12<<2): 51 | 52 | 11111111 11111111 11111111 11010000 (-48) 53 | Let's do -12<<28 and the result is 54 | 55 | 01000000 00000000 00000000 00000000 (1073741824) 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /When is 'return null' valid: -------------------------------------------------------------------------------- 1 | 2 | ANOTHER IMP CONCEPT IN JAVA: When is "return null;" valid ? 3 | Answer: 4 | 1. Valid: "return null;" is valid only for complex datatypes and complex datastructures such as Wrapper Classes, 5 | Object, List, Arrays etc. 6 | 2. Invalid: "return null;" is invalid for Primitive datatypes such as int,double,char. 7 | 3. If the return type is void, the instead of 'return null;' we should always write 'return;'. Otherwise ERROR will be thrown. 8 | 9 | The following program clearly displays 2 things. 10 | 1. 'return null' is invalid for primitive datatypes. 11 | 2. 'string' does not exist. But 'String' wrapper class exist. This means that 'string' is not primitive datatype in Java. 12 | 3. If the return type is void, the instead of 'return null;' we should always write 'return;'. Otherwise ERROR will be thrown. 13 | 14 | Program: 15 | package forTesting; 16 | import java.util.List; 17 | 18 | public class CheckingNullForAllReturnTypes { 19 | public static void main(String[] args) { 20 | System.out.println(returnList()); 21 | System.out.println(returnDouble()); 22 | System.out.println(returndoubleArray()); 23 | System.out.println(returnDoubleArray()); 24 | System.out.println(returnObject()); 25 | System.out.println(returnString()); 26 | System.out.println(returndouble()); // VERY IMP: CANNOT RETURN NULL for Primitive Datatypes 27 | } 28 | 29 | public static List returnList(){ // CAN RETURN NULL for return type of complex datatype 30 | return null; 31 | } 32 | public static Double returnDouble(){ // CAN RETURN NULL for return type of Wrapper Classes 33 | return null; 34 | } 35 | public static double[] returndoubleArray(){ // CAN RETURN NULL for complex DS such as array of primitive datatype 36 | return null; 37 | } 38 | public static Double[] returnDoubleArray(){ // CAN RETURN NULL for complex DS such as array of Wrapper datatype 39 | return null; 40 | } 41 | public static Object returnObject(){ 42 | return null; // CAN RETURN NULL for return type of complex datatype such as Object 43 | } 44 | public static String returnString(){ 45 | return null; // CAN RETURN NULL for Wrapper class such as String, since there is no such thing called 'string' 46 | // The primitive datatype of String Wrapper Class is 'char' and NOT 'string' 47 | } 48 | 49 | public static double returndouble(){ 50 | return null; // CANNOT RETURN NULL for Primitive Datatype 51 | } 52 | /*ANOTHER IMPORTANT THING: 53 | * public static string returnstring(){ // Throws ERROR, since there is no such thing called as 'string' 54 | // since 'string' is not Primitive datatype. 'String' exists which is Wrapper class 55 | // and not 'string'. The primitive type of 'String' Wrapper Class can be said to be 'char'. 56 | // Also the primitive type of 'Character' wrapper class is also 'char' 57 | return null; 58 | } 59 | ONE MORE IMP THING: 60 | public static void returnVoid(){ 61 | return null; // This gives ERROR since the return type is void 62 | } 63 | 64 | public static void returnVoid(){ 65 | return; // This DOES NOT gives ERROR since the return type is void 66 | } 67 | */ 68 | } 69 | 70 | /* 71 | * 72 | Output: 73 | null 74 | null 75 | null 76 | null 77 | null 78 | null 79 | Exception in thread "main" java.lang.Error: Unresolved compilation problem: 80 | Type mismatch: cannot convert from null to double 81 | 82 | at forTesting.CheckingNullForAllReturnTypes.returndouble(CheckingNullForAllReturnTypes.java:36) 83 | at forTesting.CheckingNullForAllReturnTypes.main(CheckingNullForAllReturnTypes.java:13) 84 | */ 85 | -------------------------------------------------------------------------------- /Applications of various data structures: -------------------------------------------------------------------------------- 1 | Queue: 2 | 1) Queueing processes : any device does not have infinite resources, so a queue has 3 | to be used in order to allocate resources to those process that need it on a priority level. 4 | 5 | Bloom filters: 6 | 1) In shortening URLs. 7 | 8 | Graphs: 9 | 1) GIS : in Geographic Informative Systems, transport and vehicular technology. 10 | 2) Maps : Google Maps, Bing, etc. 11 | 3) Paths between points(keys) : Like the A* Algorithm, etc. 12 | 13 | Trees 14 | 1) Data base designing : creating your own database just to store the data based upon some key value 15 | 2) Creating file system : Operating systems maintain a disk's file system as a tree. 16 | 3) Zoology: Maintaining the structures of the entire animal & plant kingdom. 17 | 4) Social Networks : Establishing relations between users based on some key. 18 | 19 | B-Trees (Binary Trees): 20 | 1) E-commerce : while accessing unique keys. B-Trees balanced multi-way search tree of order N. 21 | 2) Searching : Searching quickly for a given element. 22 | 3) For File Systems 23 | 24 | Hash Tables: 25 | 1) In Banks for combining two or more accounts for matching Social Security Numbers. 26 | 27 | Trie(prefix tree): 28 | 1) In auto-complete dictionary in mobiles, search engines etc. 29 | 2) As approximate algorithms in spell-checking 30 | 31 | B+ Trees 32 | 1) for building Data Bases 33 | 34 | Splay Tree: 35 | 1) Used in caches 36 | 37 | Suffix tree: 38 | 1) Genomic sequencing 39 | 40 | 41 | ★ Question ->Why are Red-Black trees used more often in industry than AVL trees? 42 | Though AVL trees appear to be simpler (ie. fewer cases to handle) and have shorter heights, 43 | yet Red-Black trees appear more predominate (ie. used in Java and in functional language implementations) 44 | 45 | There are two popular Balanced Binary Search Tree: AVL Tree and Red-Black Tree. 46 | Both offers O(lg n) search time. But the hidden constant behind Big O makes AVL Tree more 47 | suitable for search and Red-Black Tree for insertion-deletion. Insertion-deletion takes less 48 | time in Red-Black Tree than AVL Tree. That's Red-Black Tree are more popular than AVL Tree although 49 | implementing Red-Black is very complicated task. 50 | 51 | RBs handle all operations better on average (insertion, retrieval, deletes), 52 | whilst AVLs are good for frequent retrievals, but infrequent insertions and deletes. 53 | 54 | That being said, RBs are suitable for more situations than AVLs. 55 | 56 | 57 | Special trees, special lists and probabilistic data structures - 58 | 59 | Skiplist: 60 | Used by Redis datastore for the implementation of ordered sets. 61 | Used in nessDB. 62 | 63 | Bloom filter: 64 | Used by Cassandra to check which SSTables mostly contains the key. 65 | Hbase also uses it to optimize the reads. 66 | 67 | LSM trees: 68 | Used by Cassandra(SSTables), Big table for storage. 69 | 70 | Merkle tree: 71 | Used by various eventually consistent datastores like Dynamo, Cassandra for anti-entropy mechanism. 72 | 73 | 74 | Judy Tree: 75 | I want to talk about one awesome in-memory data structure which is not yet discussed in this thread 76 | 77 | JudyTree is the efficient in-memory data structure which is fast and consumes less memory 78 | 79 | Judy has two main strategies: use a 256-ary tree, compressed and designed to require one (at most two) 80 | secondary cache misses per tree node lookups 81 | 82 | A (CPU) cache-line fill is additional time required to read from RAM when a word is not found in cache. 83 | In today’s computers the time for a cache-line fill is in the range of 50..2000 machine instructions. 84 | Hence a cache-line fill should be avoided when fewer than 50 instructions can do the same job. 85 | 86 | * Judy is generally faster then a hashing method and popular forms of balanced binary tree 87 | * Judy is cache - concious because its designed to avoid cache-line fills wherever possible 88 | * Judy tree is more memory-efficient than almost any other competitive structure 89 | 90 | Useful link: A 10 minute description of how Judy arrays work and why they are so fast: 91 | http://judy.sourceforge.net/doc/10minutes.htm 92 | -------------------------------------------------------------------------------- /Find whether a bit is set in Character or Integer: -------------------------------------------------------------------------------- 1 | Question: Program to find whether a bit is SET or UNSET(Not SET) in character and integer values. 2 | Logic: 3 | Understand the code mentioned in all the below mentioned links: 4 | I. For Reference you can understand the program mentioned in the link: http://www.geeksforgeeks.org/power-set/ 5 | II. How to check whether a bit is set in JAVA OR C OR ANY Programming Language:(See both the below mentioned links) 6 | 1.http://stackoverflow.com/questions/1092411/java-checking-if-a-bit-is-0-or-1-in-a-long 7 | 2.http://stackoverflow.com/questions/13420241/check-if-one-single-bit-only-is-set-within-a-64-bits-integer 8 | 9 | Solution: 10 | package CheckForSetBitsInIntegerAndCharacter; 11 | 12 | import java.util.Scanner; 13 | 14 | public class UsingLeftShift { 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | try{ 18 | while(true){ 19 | 20 | System.out.println("Program to check which of the first 8 bits (counting from right to left) "+ 21 | "are SET or UNSET"); 22 | System.out.println("1. Character \n2. Integer \n3. END"); 23 | System.out.println("Enter choice"); 24 | int choice = in.nextInt(); 25 | 26 | switch(choice){ 27 | 28 | case 1: 29 | System.out.println("Checking set bits in Characters:"); 30 | System.out.println("Enter the string"); 31 | String s = in.next(); 32 | char[] charArray = s.toCharArray(); 33 | printSetBits(charArray); 34 | break; 35 | 36 | case 2: 37 | System.out.println("Checking set bits in Integers:"); 38 | System.out.println("Enter the size of the integer array"); 39 | int n = in.nextInt(); 40 | int[] a = new int[n]; 41 | System.out.println("Enter the elements of the integer array"); 42 | for(int i=0;i http://javarevisited.blogspot.com/2012/04/difference-between-list-and-set-in-java.html 2 | 3 | 4 | Please Note: This is much better explanation than given in the link above. 5 | 6 | List vs Set in Java 7 | 8 | Difference between Set and List in Java: 9 | Here are few note worthy differences between List and Set in Java. 10 | Remember that both of them are used to store objects and provides convenient API to insert, remove and 11 | retrieve elements, along with to support Iteration over collection. 12 | 13 | 1) Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows 14 | duplicates while Set doesn't allow any duplicate. If you insert duplicate in Set it will replace the older 15 | value. While if a duplicate is inserted in a List, it will be appended as the next element in the List. 16 | In case of duplicates in Map, if the keys are the same, the value of the latest will overwrite the value 17 | previously existed at that same key. (Remember, Map works on KEY-VALUE pairs) 18 | 19 | 2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while 20 | Set is an unordered Collection. List maintains insertion order of elements, means any element which is 21 | inserted before will go on lower index than any element which is inserted after. Set in Java doesn't 22 | maintain any order. Though Set provide another alternative called SortedSet which can store Set elements 23 | in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set. 24 | 25 | 3) Set uses equals() method to check uniqueness of elements stored in Set, while SortedSet uses compareTo() 26 | method to implement natural sorting order of elements. In order for an element to behave properly in Set and 27 | SortedSet, equals and compareTo must be consistent to each other. 28 | 29 | 4) Popular implementation of List interface in Java includes ArrayList, Vector and LinkedList. While popular 30 | implementation of Set interface includes HashSet, TreeSet and LinkedHashSet. 31 | 32 | 33 | Read more: http://javarevisited.blogspot.com/2012/04/difference-between-list-and-set-in-java.html#ixzz2qF8yRnUr 34 | 35 | 36 | Code to test the statements written above: 37 | import java.awt.List; 38 | import java.util.HashMap; 39 | import java.util.HashSet; 40 | import java.util.LinkedList; 41 | import java.util.Map; 42 | import java.util.Set; 43 | 44 | public class Difference { 45 | public static void main(String[] args) { 46 | Set sets=new HashSet(); 47 | sets.add(1); 48 | sets.add(1); 49 | System.out.println(sets.size()); 50 | 51 | LinkedList lists=new LinkedList(); 52 | lists.add(1); 53 | lists.add(1); 54 | System.out.println(lists.size()); 55 | 56 | Map maps=new HashMap(); 57 | maps.put(1, 1); 58 | maps.put(1, 2); // Just to check whether the pevious VALUE at the same key is over written or not. 59 | System.out.println(maps.size()); 60 | System.out.println(maps.get(1)); // Output comes 2, hence the pevious VALUE at the same key is over written 61 | } 62 | } 63 | 64 | /* 65 | Output 66 | 67 | 1 //size of Set 68 | 2 //size of List 69 | 1 //size of Map 70 | 2 // value at key 1 of the Map 71 | 72 | */ 73 | 74 | Ordered lists of element (unique or not) 75 | Conform to Java's interface named List 76 | Can be accessed by index 77 | 78 | LinkedList 79 | ArrayList 80 | Lists of unique elements: 81 | Conform to Java's interface named Set 82 | Can not be accessed by index 83 | 84 | HashSet (unordered) 85 | LinkedHashSet (ordered) 86 | TreeSet (sorted by natural order or by provided comparator) 87 | Both interfaces Set and List conform to Java's interface named Collection 88 | 89 | ╔═══════════════════╦══════════════════════╦═════════════════════════════╗ 90 | ║ ║ List ║ Set ║ 91 | ╠═══════════════════╬══════════════════════╬═════════════════════════════╣ 92 | ║ Duplicates ║ YES ║ NO ║ 93 | ╠═══════════════════╬══════════════════════╬═════════════════════════════╣ 94 | ║ Order ║ ORDERED ║ DEPENDS ON IMPLEMENTATION ║ 95 | ╠═══════════════════╬══════════════════════╬═════════════════════════════╣ 96 | ║ Positional Access ║ YES ║ NO ║ 97 | ╚═══════════════════╩══════════════════════╩═════════════════════════════╝ 98 | -------------------------------------------------------------------------------- /Threads, synchronized, Lock, volatile: -------------------------------------------------------------------------------- 1 | Please follow the below links of YouTube for the following: 2 | 3 | All these are 2 minute videos. Please watch all of them. 4 | 5 | 6 | VERY IMPORTANT CONCEPT ABOUT SYNCHRONIZATION: 7 | 8 | 9 | Whenever, we think about locks: just remember 2 things 10 | -> Lock at the CLASS LEVEL(static methods) 11 | -> Lock at the INSTANCE LEVEL (non-static methods) 12 | 13 | 1) Consider two objects on a class. Both the objects belong to the SAME INSTANCE of the class. 14 | i.e. Animal a1=new Animal(); 15 | Animal a2=a1; 16 | 17 | Both objects a1 and a2 belong to the same instance of the Animal class. 18 | 2) The class Animal contains 4 non-static synchronized methods, 4 static synchronized methods and 4 non-synchronized methods. 19 | 3) If two threads are created such that Thread1 has object a1 20 | and Thread2 has object a2. 21 | 4) Then if Thread1 starts before Thread2. Then Thread1 will acquire locks for all the synchronized methods, 22 | hence Thread2 cannot enter in any of the synchronized methods of the class, even if Thread 1 wants to 23 | execute in only 2 synchronized methods, but not all synchronized methods, but still all synchronized methods 24 | will be locked by object a1 which belongs to Thread1. But Thread2 can enter in non-synchronized methods of the class. 25 | Thread2 cannot enter in any of the synchronized methods of the class. 26 | 5) But if a1 and a2 are different instances of the class Animal such that: 27 | Animal a1=new Animal(); 28 | Animal a2=new Animal(); 29 | Thus, a1 and a2 are different instances of Animal class. 30 | In this case, if Thread1 which has object a1 enters in one of the non-static synchronized methods of the 31 | class, then the Thread2 which has object a2 can enter in other non-static synchronized methods of the class. 32 | But, if Thread1 enters in static synchronized method of the class, then any of the other static synchronized 33 | methods of the class can not be accessed by Thread2 even if object1 and object2 are different instance of 34 | the same class or same instances of the same class. 35 | This is because, even if a1 and a2 are different instances, but the STATIC keyword acquires lock at the 36 | class level. Hence no other instances of the object can be allowed in STATIC SYNCHRONIZED methods. 37 | But if Thread1 enters in STATIC SyNCHRONiZED methods(that is obtains lock for static synchronized methods) 38 | then Thread2 which is another instance of the same class Animal can enter(that means obtain lock) for 39 | STATIC NON-SYNCHRONIZED methods, NON-STATIC(that means INSTANCE) SYNCHRONIZED methods and 40 | NON-STATIC(in other words INSTANCE) NON-SYNCHRONIZED methods. 41 | 42 | 43 | Whenever, we think about locks: just remember 2 things 44 | -> Lock at the CLASS LEVEL(static methods) 45 | -> Lock at the INSTANCE LEVEL (non-static methods) 46 | 47 | Please remember the following IMPORTANT things: 48 | 1) A static(Lock is at the CLASS level) synchronized and non-static(Lock is at the instance level that is object level) 49 | will NOT-BLOCK each other EVER. The static methods locks on a CLASS level while the non-static methods 50 | locks on a INSTANCE level also known as the Object level. These actions DONOT interfere with each other AT ALL. 51 | 2) For synchronized blocks, we look at exactly what object has been used for locking. That is we look at the 52 | parameters of the synchronized methods to check which object is used for locking. Threads that 53 | synchronize on the same objects(same instance of the same class) will BLOCK each other. 54 | Threads that synchronize on different objects(different instance of the same class) will NOT-BLOCK each other. 55 | 3) Methods that give up the locks are: only one methods in entire Java which is: 56 | wait() method defined in Object class. 57 | 4) Methods thathold the locks are: 58 | notify() and notifyAll() -> These two methods belong to Object class 59 | join() -> This method belongs to Thread class 60 | sleep() -> This method belongs to Thread class 61 | yield() -> This method belongs to Thread class 62 | 63 | Please remember every part of the above explanation. Each and every word from the start of the page to the 64 | end of the page is VERY VERY IMPORTANT. 65 | 66 | 67 | 68 | 69 | Threads, synchronized methods and blocks and Lock -> 1) http://www.youtube.com/watch?v=yvLYSXi8U_g 70 | 2) http://www.youtube.com/watch?v=b779xXBDC9w 71 | 3) http://www.youtube.com/watch?v=NDw-KnRNPso 72 | 73 | volatile keyword -> http://www.youtube.com/watch?v=7BShcgKkVAU 74 | -------------------------------------------------------------------------------- /B and B+ Trees: -------------------------------------------------------------------------------- 1 | For understanding the importance and the need for B+ and B trees, please go through the material given in the 2 | below links 3 | 4 | 5 | PLEASE NOT THAT: 6 | 1) B-Trees and B+ Trees are not BINARY(having 2 children) TREES, 7 | they are Multiway(M-way, that is having M children) Trees. 8 | 2) Both B and B+ trees are SEARCH(that is left is less than right) Trees. 9 | 10 | Motivation for B-Trees 11 | Index structures for large datasets cannot be stored in main memory 12 | Storing it on disk requires different approach to efficiency 13 | Assuming that a disk spins at 3600 RPM, one revolution occurs in 1/60 of a second, or 16.7ms 14 | Crudely speaking, one disk access takes about the same time as 200,000 instructions 15 | Assume that we use an AVL tree to store about 20 million records 16 | We end up with a very deep binary tree with lots of different disk accesses; log2 20,000,000 is about 24, 17 | so this takes about 0.2 seconds 18 | We know we can’t improve on the log n lower bound on search for a binary tree 19 | But, the solution is to use more branches and thus reduce the height of the tree! 20 | As branching increases, depth decreases 21 | A B-tree of order m is an m-way tree (i.e., a tree where each node may have up to m children) in which: 22 | 1. the number of keys in each non-leaf node is one less than the number of its children and these keys 23 | partition the keys in the children in the fashion of a search tree 24 | 2. all leaves are on the same level 25 | 3. all non-leaf nodes except the root have at least m/2 children 26 | 4. the root is either a leaf node, or it has from two to m children 27 | 5. a leaf node contains no more than m–1 keys 28 | The number m should always be odd 29 | 30 | (VERY IMP)Please go through the below links: 31 | 32 | cecs.wright.edu/~tkprasad/courses/cs707/L04-X-B-Trees.ppt 33 | http://bluerwhite.org/btree/#applications 34 | http://ayende.com/blog/162945/b-trees-and-why-i-love-them-part-i 35 | http://toyhouse.cc/profiles/blogs/b-tree-b-tree-amp-b-tree 36 | http://www.entrycoder.com/2013/04/difference-between-b-and-b-tree-in.html 37 | http://stackoverflow.com/questions/870218/b-trees-b-trees-difference 38 | http://guide.couchdb.org/draft/btree.html 39 | 40 | 41 | Advantages of B and B+ Tress over Biary Search Trees: 42 | source -> http://stackoverflow.com/questions/15485220/advantage-of-b-trees-over-bsts 43 | The major advantage of the B+ tree (and B-trees in general) over binary search trees is 44 | that they play well with caches. If you have a binary search tree whose nodes are stored in 45 | more or less random order in memory, then each time you follow a pointer, the machine will have 46 | to pull in a new block of memory into the processor cache, which is dramatically slower than 47 | accessing memory already in cache. 48 | 49 | The B+-tree and the B-tree work by having each node store a huge number of keys or values and 50 | have a large number of children. They are typically packed together in a way that makes it possible 51 | for a single node to fit nicely into cache (or, if stored on disk, to be pulled from the disk in a 52 | single read operation). You then have to do more work to find a key within the node or determine 53 | which child to read next, but because all memory accesses done on a single node can be done without 54 | going back to disk, the access times are very small. This means that even though in principle a BST 55 | might be better in terms of number of memory accesses, the B+-tree and the B-tree can performed better 56 | in terms of the runtime of those memory accesses. 57 | 58 | The typical use case for a B+-tree or B-tree is in a database, where there is a huge amount of 59 | information and the data are so numerous that they can't all fit into main memory. Accordingly, 60 | the data can then be stored in a B+-tree or B-tree on a hard disk somewhere. This minimizes the 61 | number of disk reads necessary to pull in the data during lookups. Some filesystems (like ext4, I believe) 62 | use B-trees as well for the same reason - they minimize the number of disk lookups necessary, 63 | which is the real bottleneck. 64 | 65 | 66 | Advantages of B+ Trees over B-Trees 67 | source -> http://www.quora.com/What-are-the-advantages-of-B+-Tree-over-B-Tree 68 | Short Answer: 69 | It's all about branching factor. Because of the way B+-Trees store records (called "satellite information") at the leaf level of the tree, they maximize the branching factor of the internal nodes. High branching factor allows for a tree of lower height. Lower tree height allows for less disk I/O. Less disk I/O theoretically means better performance. 70 | 71 | Long Answer: 72 | B-Trees ("B Trees") and B+-Trees ("B Plus Trees") are balanced search trees that perform well 73 | on magnetic media and secondary storage because they minimize disk I/O ops. 74 | 75 | * As a matter of background information, in a typical 7200 RPM disk drive one platter rotation 76 | takes ~8.3ms which is ~5 orders of magnitude longer than the typical 100ns access time of silicon memory. 77 | So using the most efficient data structures to do dynamic set operations (like Search() Create() Insert()) 78 | is very important. 79 | 80 | B-Tree algorithms are good for accessing pages (or blocks) of stored information which are then 81 | copied into main memory for processing. In the worst case, they are designed to do dynamic set operations 82 | in O(lg n) time because of their high "branching factor" (think hundreds or thousands of keys off of any 83 | node). It is this branching factor that makes B-Trees so efficient for block storage/retrieval, 84 | since a large branching factor greatly reduces the height of the tree and thus the number of 85 | disk accesses needed to find any key! 86 | 87 | * For relative sizing reference: A B-Tree with a branching factor of 1001 and a height of 2 88 | can store over 1 Billion keys! And since the root node can be kept in main memory, you only need 89 | 2 disk accesses to find any key in this tree! 90 | 91 | In B+-Trees, all records ("satellite information") are stored at the leaf level while keys and 92 | child pointers are stored in interior nodes (aka non-leaf nodes). This maximizes the branching factor 93 | of the internal nodes. This is the advantage of a B+-Tree over a regular B-Tree. 94 | --------------------------------------------------------------------------------