├── 0 └── 0-1 Knapsack Problem ├── 0-1 Knapsack Problem ├── 75 IMP Java Questions ├── == Vs equals() ├── Abstract Class Vs Interface ├── Abstraction vs Encasulation ├── Access Modifiers in Java ├── All About Threads ├── Anonymous Classes in Java ├── Applications of various data structures ├── Arrays Vs LinkedList ├── B and B+ Trees ├── Best Sources to understand Java ├── Best of Best website for Java Interview Questions ├── Binomial Coefficient Calculation ├── Bitwise Operations in Java ├── Boundary test cases to check whether a LL is circular ├── BufferedReader vs Scanner ├── C++ vs Java ├── Classpath importance in Java ├── Coding to interfaces ├── Comparable interface vs Comparator interface ├── ConcurrentHashMap vs Collections.synchronizedMap(Map) ├── Design Patterns ├── Diff between Set and List ├── Dynamic Programming vs Greedy vs Divide & Conquer ├── Enumeration Vs Iterator ├── Exception vs Error ├── Find whether a bit is set in Character or Integer ├── Garbage Collection in ├── Garbage Collection in Java ├── Generics - Advtgs and Disadtgs ├── Golden Questions ├── HashMap Disadvantages ├── How does Thread Locks work ├── How to make code readable to the other programmers who look your code ├── IMP Questions ├── IMP Theory Questions in Java ├── IMP Websites for Interview Preparation ├── IMP Websites with Java Intervew Questions ├── Inclusive vs Exclusive OR ├── Indexing in Databases ├── Inner Class in Java ├── InterThread and InterProcess Communication ├── Iterator vs loop for Collection ├── LRU Cache ├── Left Right Shift in Java ├── Local variables default value in Java ├── MVC design pattern or architecture ├── Marker Interfaces in Java ├── Maven vs Ant ├── Mem Management in C ├── Mutex Vs Semaphore ├── Obj Oriented vs Procesdural(a.k.a Functional Programming) ├── Overriding equals and hashCode methods in Java ├── Polymorphism OOP Feature Explained ├── Power of XOR in Programming ├── Primitive data type conversions in Java ├── Primitive types and Wrapper Classes ├── Questions about Testing ├── QuickSelect 2 partitions ├── README.md ├── Recursion vs Iteration ├── Regex Learning ├── Retrieve number of Rows and Columns from [][] array ├── Size of Int in Java in 64 bit machines ├── Space Complexity of Recursive Calls ├── Stack vs Heap memory in Java ├── Static vs Dynamic Class Loading in Java ├── Synchronization concept in Java ├── System class Java ├── TCP Vs UDP ├── Testing ├── Threads, Process and Program(Application) ├── Throwable ├── Time Complexity of predefined methods in JAVA ├── VERY VERY IMP THING IN PROGRAMMING ├── VERY VERY IMPORTANT INTERVIEW PREPARATION SOURCE ├── What is a hashcode? ├── What is lambda expression? ├── What is the meaning of 'static' in a method header? ├── When is 'return null' valid ├── Which is faster? ├── Working of Garbage Collector in Java ├── Working of JVM, Compiler and Interpreter ├── Working of TreeMap & TreeSet ├── charArray to String ├── end of character marking in char array ├── equals and hashcode method ├── final finally finalize ├── final keyword allowed or not allowed on abstract ? ├── finally block execution Importance ├── hashCode and equals method ├── isAnagramOfAStringPalindrome ├── package or import statement should be first ├── private classes in Java ├── shallow vs deep cloning of objects in Java ├── sleep Vs wait ├── static members allowed or not allowed in non-static methods ├── static syncronization vs non-static synchronization ├── static vs dynamic typed languages ├── switch case ├── toString can output Set,List and Map └── wait vs sleep vs yield method /0-1 Knapsack Problem: -------------------------------------------------------------------------------- 1 | http://www.youtube.com/watch?v=ROW7Us0kRDI 2 | -------------------------------------------------------------------------------- /0/0-1 Knapsack Problem: -------------------------------------------------------------------------------- 1 | http://www.youtube.com/watch?v=ROW7Us0kRDI 2 | -------------------------------------------------------------------------------- /75 IMP Java Questions: -------------------------------------------------------------------------------- 1 | Java Freshers Top 75 Core Java Intervie Questions List Java Interview Questions 2 | 3 | 1.Can Java thread object invoke start method "twice" ? 4 | 2.Give the list of Java Object class methods ? 5 | 3.Can we call servlet destory() from service() ? 6 | 4.Can we override a static method ? 7 | 5.Can you list "Serialization" Interface methods ? 8 | 6.What is the difference between super() and this() ? 9 | 7.How to prevent a method from being overridden ? 10 | 8.Can we create abstract classes without any abstract methods ? 11 | 9.Explain private,protected,public ? 12 | 10.Can we have static methods in interface ? 13 | 11.What is transient variable ? 14 | 12.Incase, there is a return at the end of try block, will execute finally block ? 15 | 13.What is abstract class or abstract method ? 16 | 14.What is default value of a boolean ? 17 | 15.When to use LinkedList or ArrayList ? 18 | 16.What is daemon thread ? 19 | 17.Does each thread in java uses seperate stack ? 20 | 18.What is the difference between Enumeration and Iterator ? 21 | 19.Does system.exit() in try block executes finally block ? 22 | 20.What is fail-fast in Java ? Explain ? 23 | 21.What is final, finally and finalize ? 24 | 22.In java, are true and false keywords ? 25 | 23.What is the purpose of "Garbage Collection" ? 26 | 24.What are the types of ResultSet ? 27 | 25.What is difference between "wait" and "sleep" methods in Java ? 28 | 26.What is servlet context ? 29 | 27.What happens if one of the members in a class does not implement Serializable interface ? 30 | 28.What is race condition ? 31 | 29.How to get current time in milli seconds ? 32 | 30.How can you convert Map to List ? 33 | 31.What is strictfp keyword ? 34 | 32.What is System.out in Java ? 35 | 33.What is difference between ServletOuptputStream and PrintWriter ? 36 | 34.What is Java static import ? 37 | 35.When to use String and StringBuffer ? 38 | 36.What is difference between StringBuffer and StringBuilder ? 39 | 37.What is wrapper class in Java ? 40 | 38.Is Iterator a Class ? 41 | 39.What is Java classpath ? 42 | 40.Can a class in Java be marked as private ? 43 | 41.Is null a keyword in Java ? 44 | 42.What is the initial state of a thread when it is started ? 45 | 43.What is the super class for Exception and Error ? 46 | 44.What is Class.forName() ? 45.Can interface be final ? 47 | 46.What is the difference between exception and error ? 48 | 47.What is default value of a local variables ? 49 | 48.What is local class in Java ? 50 | 49.Can we initialize uninitialized final variable ? 51 | 50.Can we declare abstract method as final ? 52 | 51.Can we have finally block without catch block ? 53 | 52.What is pass by value and pass by reference ? 54 | 53.Can we declare main method as private ? 55 | 54.What is the difference between preemptive scheduling and time slicing ? 56 | 53.Can non-static member classes (Local classes) have static members ? 57 | 54.What are the environment variables do we neet to set to run Java ? 58 | 55.Can you serialize static fields of a class ? 59 | 56.What is the difference between declaring a variable and defining a variable ? 60 | 57.Where can we use serialization ? 61 | 58.What modifiers are allowed for methods in an Interface ? 62 | 59.What is the purpose of Runtime and System class ? 63 | 60.Which one is faster ? ArrayList or Vector ? Why ? 64 | 61.What is the difference between "Static Synchronized" and "Synchronized" methods ? 65 | 62.What is the order of catch blocks when catching more than one exception ? 66 | 63.What is the difference between the prefix and postfix forms of the increment(++) operator ? 67 | 64.What is hashCode ? 65.What is the difference between Hashtable and HashMap ? 68 | 66.What are the restrictions when overriding a method ? 67.What is the use of assert keyword ? 69 | 68.What is difference between break, continue and return statements ? 70 | 69.What is the difference between while and do-while statements ? 71 | 70.When does the compiler provides the default constructor ? 72 | 71.How to create and start a thread in Java ? 73 | 72.Can I extend a "Final" class in Java ? 74 | 73.Explain "volatile" keyword in Java ? 75 | 74.Can we catch "RuntimeException" ? What is "Checked" and "Unchecked" Exception ? 76 | 75.When to make a constructor "private" and why ? 77 | -------------------------------------------------------------------------------- /== Vs equals(): -------------------------------------------------------------------------------- 1 | Difference between heap and string pool memory: (Source: http://www.coderanch.com/t/390447/java/java/Difference-Heap-Pool) 2 | Video of 6 minutes to explain this: https://www.youtube.com/watch?v=WTOiuY7cNTo 3 | 4 | Heap: 5 | The heap is just the area of RAM that is allotted to the JVM by the operating system for runtime activity. 6 | As such it is the place that objects get created during a JVM session. 7 | 8 | Pool: 9 | Pool is a separate portion WITHIN the heap memory. This separate portion of heap memory is called "POOL" 10 | The 'pool' is just a special area of the heap memory that Java sets up to store all String literals. 11 | Imagine a box with a partition wall; on one side is the 'pool' on the other side the 'heap'. 12 | Everytime you use a string literal, it gets stored on the pool side, regular objects get stored on 13 | the heap side. 14 | 15 | 16 | Difference between HEAP memory and STACK memory 17 | All objects are stored on the heap(including their attributes) memory. 18 | Local variables of functions/methods(including function/method arguments) always contain primitive values 19 | or references and are stored on the stack memory. 20 | 21 | Best video of 6 minutes to explain difference between == and equals() : https://www.youtube.com/watch?v=WTOiuY7cNTo 22 | 23 | The == (double equals) returns true, if the variable reference points to the same object in memory. 24 | This is called “shallow comparison”. 25 | 26 | 27 | 28 | 29 | The object class contains the equals() method. This equals() method is then implemented by String class, 30 | Double class, Long class, Integer class, Byte class, Integer class, Boolean class. 31 | The only thing to be noted is that the equals method is called using object and accepts a parameter which is 32 | an object. Hence the primitive types need to be converted to Objects using Wrapper classes to call the their 33 | respective equals() method. 34 | Object equals(Object o) 35 | return type and parameter, both are objects. 36 | 37 | Best explantion for difference between == and equals(). It also explains the 38 | difference between equals method of Object class and equals method of String class. It also explains the 39 | difference between hashcode method of Object class and hashcode method of String class. Similarly Integer, Byte and other wrapper 40 | classes have their own different version of hashcode and equals method. If they are not invoked then the default implementation 41 | of hashcode and equals method mentioned in the Object class is invoked. 42 | 1) --> http://stackoverflow.com/questions/16089282/how-equals-method-works 43 | 2) -->http://howtodoinjava.com/2012/10/09/working-with-hashcode-and-equals-methods-in-java/ 44 | 45 | If the equals method is passes with Object of Generic type, then it has to be implemented manually, so that 46 | it can override the equals() method of the object class. Otherwise if not implemented then, equals() method 47 | will work similar to == operator and will only compare reference(i.e. SHALLOW COMPARISON) 48 | 49 | 50 | The equals() method calls the user implemented equals() method, which compares the object attribute values. 51 | The equals() method provides “deep comparison” by checking if two objects are logically equal as opposed to 52 | the shallow comparison provided by the operator ==. 53 | 54 | If equals() method does not exist in a user supplied class then the inherited Object class's equals() method 55 | will be called which evaluates if the references point to the same object in memory. In this case, the object. 56 | equals() works just like the "==" operator. 57 | 58 | Source -> http://www.java2novice.com/java_interview_questions/==-and-equals/ 59 | -------------------------------------------------------------------------------- /Abstract Class Vs Interface: -------------------------------------------------------------------------------- 1 | VERY IMPORTANT POINT: 2 | A normal class cannot have abstract methods. If a method in a normal class is declared as abstract, then the 3 | whole class has to be declared as abstract. Otherwise compilation and runtime error would take place. 4 | 5 | 6 | Interfaces:(Datamembers: public static final, Methods: public abstract, Object cannot be created) 7 | a) Cannot be instantiated 8 | b) ALL datamembers(NOT METHODS) BUT NOT METHODS are "public static final" 9 | 3) All methods are "public abstract" (AND THEY ARE NEITHER static NOR final SINCE THE CLASS IMPLEMENTING THIS 10 | INTERFACE HAS TO COMPULSORILY DEFINE THE METHODS BY OVERRIDING THEM. HENCE THEY CANNOT BE STATIC NOR FINAL 11 | BECAUSE STATIC OR/AND FINAL METHODS CANNOT BE OVERRIDDEN) 12 | 4) Each and every method dont have a defination 13 | 5) Classes which implement the Interface have to define the abstract methods 14 | 6) By default, ALL METHODS in an interface are decleared as public, abstract. It will never be static.(BECAUSE 15 | STATIC METHODS CANNOT BE OVERRIDDEN) 16 | 17 | 18 | Abstract Classes:(Methods: can or cannot be public abstract, Object cannot be created) 19 | 1) Cannot be instantiated 20 | 2) We cannot create instance for an abstract class. We can able to create instance for its subclass only. 21 | By specifying abstract keyword just before class, we can make a class as abstract class. 22 | public abstract class MyAbstractClass{ 23 | 24 | } 25 | 3) Abstract class may or may not contains abstract methods. Abstract method is 26 | just method signature, it does not containes any implementation. Its subclass 27 | must provide implementation for abstract methods. Abstract methods are looks 28 | like as given below: 29 | 30 | public abstract int getLength(); 31 | 32 | 33 | 4) Methods can have defination. Some of the methods can be defined while some of the methods can be abstract. 34 | However an abstract class can have NO abstract methods. Even if a class does not have abstract methods but 35 | is declared as abstract is said to be an abstract class. 36 | 5) We have to explicitly declare the abstract methods as "public abstract" so that they can be defined by the 37 | classes which inherit the abstract class. 38 | 6) Abstract classes fall in between "Interfaces" and proper actual defined "Classes" since they have both the 39 | properties. 40 | 7) A normal class cannot have abstract methods. If a method in a normal class is declared as abstract, then the 41 | whole class has to be declared as abstract. Otherwise compilation and runtime error would take place(VERY IMPORTANT POINT). 42 | -------------------------------------------------------------------------------- /Abstraction vs Encasulation: -------------------------------------------------------------------------------- 1 | Beautiful 10 minute video explaining the difference: 2 | Please watch all the videos to understand the difference properly: 3 | 4 | https://www.youtube.com/watch?v=1Q4I63-hKcY 5 | https://www.youtube.com/watch?v=O5hBf2plAyY 6 | https://www.youtube.com/watch?v=ab82D1Vqcso 7 | https://www.youtube.com/watch?v=57SIpmA3vcg 8 | -------------------------------------------------------------------------------- /Access Modifiers in Java: -------------------------------------------------------------------------------- 1 | Access Modifiers 2 | 3 | 4 | Same Class Same Package Subclass Other packages 5 | public Y Y Y Y 6 | protected Y Y Y N 7 | default Y Y N N 8 | private Y N N N 9 | 10 | Source of the above table: http://javapapers.com/core-java/access-modifiers-in-java-explain/ 11 | 12 | Access level of class: 13 | 14 | Java class has mainly two type of access level: 15 | 16 | default: class objects are accessible only inside the package. 17 | 18 | public: class objects are accessible in code in any package. 19 | 20 | private: can only be accessed within that class. Not anywhere outside it 21 | 22 | protected: Can be accessed within the class and all the classes which inherit this class and only 23 | within that package. 24 | 25 | 26 | 27 | Source: http://staff.science.uva.nl/~heck/JAVAcourse/ch4/ss2_2.html 28 | 29 | http://javapapers.com/core-java/access-modifiers-in-java-explain/ 30 | 31 | Access Specifiers 32 | 33 | 34 | One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of 35 | data in a class and making this class available only through methods. In this way the chance of 36 | making accidental mistakes in changing values is minimized. Java allows you to control access to 37 | classes, methods, and fields via so-called access specifiers. 38 | Java offers four access specifiers, listed below in decreasing accessibility: 39 | 40 | public 41 | protected 42 | default (no specifier) 43 | private 44 | We look at these access specifiers in more detail. 45 | public 46 | 47 | public classes, methods, and fields can be accessed from everywhere. 48 | The only constraint is that a file with Java source code can only contain one 49 | public class whose name must also match with the filename. If it exists, this 50 | public class represents the application or the applet, in which case the public 51 | keyword is necessary to enable your Web browser or appletviewer to show the applet. 52 | You use public classes, methods, or fields only if you explicitly want to offer access 53 | to these entities and if this access cannot do any harm. An example of a square determined 54 | by the position of its upper-left corner and its size: 55 | public class Square { // public class 56 | public x, y, size; // public instance variables 57 | } 58 | protected 59 | 60 | protected methods and fields can only be accessed within the same class to which the methods and 61 | fields belong, within its subclasses, and within classes of the same package, but not from anywhere 62 | else. You use the protected access level when it is appropriate for a class's subclasses to have access 63 | to the method or field, but not for unrelated classes. 64 | default (no specifier) 65 | 66 | If you do not set access to specific level, then such a class, method, or field will be accessible 67 | from inside the same package to which the class, method, or field belongs, but not from outside this 68 | package. This access-level is convenient if you are creating packages. For example, a geometry package 69 | that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of 70 | the upper-left corner of a Square are directly available to the Tiling class but not outside the 71 | geometry package. 72 | private 73 | 74 | private methods and fields can only be accessed within the same class to which the methods and 75 | fields belong. private methods and fields are not visible within subclasses and are not inherited 76 | by subclasses. So, the private access specifier is opposite to the public access specifier. 77 | It is mostly used for encapsulation: data are hidden within the class and accessor methods are 78 | provided. An example, in which the position of the upper-left corner of a square can be set or 79 | obtained by accessor methods, but individual coordinates are not accessible to the user. 80 | 81 | 82 | public class Square { // public class 83 | private double x, y // private (encapsulated) instance variables 84 | 85 | public setCorner(int x, int y) { // setting values of private fields 86 | this.x = x; 87 | this.y = y; 88 | } 89 | 90 | public getCorner() { // setting values of private fields 91 | return Point(x, y); 92 | } 93 | } 94 | 95 | 96 | Summary of Access Specifiers 97 | 98 | 99 | 100 | Access Modifiers 101 | 102 | 103 | Same Class Same Package Subclass Other packages 104 | public Y Y Y Y 105 | protected Y Y Y N 106 | default Y Y N N 107 | private Y N N N 108 | 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /All About Threads: -------------------------------------------------------------------------------- 1 | http://java-questions.com/Threads_interview_questions.html 2 | 3 | Why creating threads through Runnable interface is preferred as compared to craeting threads through Thread class -> 4 | http://manikandanmv.wordpress.com/2010/12/10/thread-vs-runnable/ 5 | http://stackoverflow.com/questions/15471432/why-implements-runnable-is-preferred-over-extends-thread 6 | http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread 7 | 8 | Difference between Thread and Cores of a CPU(processor) 9 | http://www.tomshardware.com/forum/306079-28-what-core-thread 10 | 11 | 12 | Thread Count of a CPU: 13 | The core is the hardware the thread is the software, the thread count for a CPU is how many threads 14 | it can handle at once. 15 | -------------------------------------------------------------------------------- /Anonymous Classes in Java: -------------------------------------------------------------------------------- 1 | http://www.cs.rit.edu/~tmh/courses/allJava/Anonymous.html 2 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Arrays Vs LinkedList: -------------------------------------------------------------------------------- 1 | Source -> http://javarevisited.blogspot.com/2013/07/difference-between-array-and-linked-list-java.html 2 | -> http://stackoverflow.com/questions/166884/array-vs-linked-list 3 | 4 | 5 | Array vs linked list in Java ( CRF - FID - SGS ) 6 | C - Contigugous memory bock 7 | R - Random Access 8 | F - Fixed Length 9 | F - Fast caches 10 | I/D - Insert and Delete operations 11 | D - Single or Multidimensional ) 12 | 13 | array vs linked list in JavaHere is my list of differences between array and linked list. 14 | Though data structure concept are independent of any programming language and more or less 15 | applicable in all programming language including C and C++, I have explained differences in Java's context. 16 | 17 | 1. First and major difference between linked list and array data structure is that former doesn't 18 | support random access, while later support random access. linked list is sequential, in order to 19 | retrieve an element, you need to traverse till that, while if you know index, you can retrieve an 20 | element from array very quickly, because it doesn't involved traversal. 21 | 22 | 2. Second major difference between array and linked-list data structure is that, array needs contiguous 23 | memory allocation, which may result in java.lang.OutOfMemoryError: Java Heap Space if there is not enough 24 | contiguous ( a big chunk) of memory in Java Heap. On the other hand, linked list is distributed data 25 | structure, it's element are scattered over heap and doesn't need a contiguous memory allocation. This 26 | makes linked list ideal, if you have scattered memory. 27 | 28 | 3. Third major difference is fixed length, array is a fixed length data structure, you provide length 29 | or size of array at the time of creation, later you can not modify that size. On the other hand, linked 30 | list is dynamic data structure, it can grow and doesn't required size to be specified at the time of 31 | creation, because each node keep tracks of other. 32 | 33 | 4. It's easy to insert and delete elements from linked list than array, especially inserting element 34 | at beginning of linked list, and deleting element from end of linked list is O(1) operation. On the 35 | other hand array is fixed length data structure, so memory is allocated during initialization, and doesn't 36 | really change due to addition and removal of elements. Though you can set a particular index null, to cut 37 | the reference count of that object. 38 | 39 | 5. Array is ideal for implementing fast caches e.g. HashMap or Hashtable, which requires constant time 40 | retrieval e.g. Map data structure provides O(1) performance for get(Key key) operation, while linked list 41 | based structure provides liner performance i.e. O(n) for retrieval operation, where n is the number of 42 | elements in linked list. 43 | 44 | 6. Array can be one or multi-dimensional, while linked list can be singly, doubly or circular linked list. 45 | Two dimensional array are most common in multi-dimensional and used to represent matrix in Java. You can 46 | use two dimensional array to represent a plain of x,y coordinates, frequently used in Game programming. 47 | Java programming language provides support for creating array at syntax level, it supports both single 48 | and multidimensional array. Java API also provides a class called java.util.LinkedList, which is an 49 | implementation of doubly linked list data structure. 50 | 51 | That's all on my list of differences between array and linked list data structure. I strongly suggest 52 | to get a good hold of these data structure, especially linked list, which is very popular among data 53 | structure interview questions. Questions like appending elements into linked list, deleting elements, 54 | reversing linked list are quite common in various programming jobs. At very least, knowledge of 55 | fundamental data structure is essential to do well in programming jobs. 56 | 57 | 58 | Read more: http://javarevisited.blogspot.com/2013/07/difference-between-array-and-linked-list-java.html#ixzz2qGX08GX3 59 | (S - Store elements 60 | G - Grow organically 61 | S - Shuffling) 62 | 63 | It's easier to store data of different sizes in a linked list. An array assumes every element is 64 | exactly the same size. 65 | As mentioned, it's easier for a linked list to grow organically. An array's size needs to be 66 | known ahead of time, or re-created when it needs to grow. 67 | Shuffling a linked list is just a matter of changing what points to what. Shuffling an array is 68 | more complicated and/or takes more memory. 69 | -------------------------------------------------------------------------------- /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 | Difference between B+ and B Trees: 5 | 1) In B+ trees the parent node is also present in the leaf node unlike B trees 6 | 2) The leaves of the B+ trees are interconnected unlike B trees 7 | 8 | 9 | PLEASE NOT THAT: 10 | 1) B-Trees and B+ Trees are NOT-BINARY(having 2 children) TREES, [B stands for BALANCED] 11 | they are Multiway(M-way, that is having M children) Trees. 12 | 2) Both B and B+ trees are SEARCH(that is left is less than right) Trees. 13 | 14 | Motivation for B-Trees 15 | Index structures for large datasets cannot be stored in main memory 16 | Storing it on disk requires different approach to efficiency 17 | Assuming that a disk spins at 3600 RPM, one revolution occurs in 1/60 of a second, or 16.7ms 18 | Crudely speaking, one disk access takes about the same time as 200,000 instructions 19 | Assume that we use an AVL tree to store about 20 million records 20 | We end up with a very deep binary tree with lots of different disk accesses; log2 20,000,000 is about 24, 21 | so this takes about 0.2 seconds 22 | We know we can’t improve on the log n lower bound on search for a binary tree 23 | But, the solution is to use more branches and thus reduce the height of the tree! 24 | As branching increases, depth decreases 25 | 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: 26 | 1. the number of keys in each non-leaf node is one less than the number of its children and these keys 27 | partition the keys in the children in the fashion of a search tree 28 | 2. all leaves are on the same level 29 | 3. all non-leaf nodes except the root have at least m/2 children 30 | 4. the root is either a leaf node, or it has from two to m children 31 | 5. a leaf node contains no more than m–1 keys 32 | The number m should always be odd 33 | 34 | (VERY IMP)Please go through the below links: 35 | 36 | cecs.wright.edu/~tkprasad/courses/cs707/L04-X-B-Trees.ppt 37 | http://bluerwhite.org/btree/#applications 38 | http://ayende.com/blog/162945/b-trees-and-why-i-love-them-part-i 39 | http://toyhouse.cc/profiles/blogs/b-tree-b-tree-amp-b-tree 40 | http://www.entrycoder.com/2013/04/difference-between-b-and-b-tree-in.html 41 | http://stackoverflow.com/questions/870218/b-trees-b-trees-difference 42 | http://guide.couchdb.org/draft/btree.html 43 | 44 | 45 | Advantages of B and B+ Tress over Biary Search Trees: 46 | 47 | (VERY IMPORTANT) IMAGE of B+ Tree-> http://en.wikipedia.org/wiki/File:Bplustree.png 48 | 49 | source -> http://stackoverflow.com/questions/15485220/advantage-of-b-trees-over-bsts 50 | The major advantage of the B+ tree (and B-trees in general) over binary search trees is 51 | that they play well with caches. If you have a binary search tree whose nodes are stored in 52 | more or less random order in memory, then each time you follow a pointer, the machine will have 53 | to pull in a new block of memory into the processor cache, which is dramatically slower than 54 | accessing memory already in cache. 55 | 56 | The B+-tree and the B-tree work by having each node store a huge number of keys or values and 57 | have a large number of children. They are typically packed together in a way that makes it possible 58 | for a single node to fit nicely into cache (or, if stored on disk, to be pulled from the disk in a 59 | single read operation). You then have to do more work to find a key within the node or determine 60 | which child to read next, but because all memory accesses done on a single node can be done without 61 | going back to disk, the access times are very small. This means that even though in principle a BST 62 | might be better in terms of number of memory accesses, the B+-tree and the B-tree can performed better 63 | in terms of the runtime of those memory accesses. 64 | 65 | The typical use case for a B+-tree or B-tree is in a database, where there is a huge amount of 66 | information and the data are so numerous that they can't all fit into main memory. Accordingly, 67 | the data can then be stored in a B+-tree or B-tree on a hard disk somewhere. This minimizes the 68 | number of disk reads necessary to pull in the data during lookups. Some filesystems (like ext4, I believe) 69 | use B-trees as well for the same reason - they minimize the number of disk lookups necessary, 70 | which is the real bottleneck. 71 | 72 | 73 | Advantages of B+ Trees over B-Trees 74 | source -> http://www.quora.com/What-are-the-advantages-of-B+-Tree-over-B-Tree 75 | Short Answer: 76 | It's all about branching factor. Because of the way B+-Trees store records (called "satellite information") 77 | at the leaf level of the tree, they maximize the branching factor of the internal nodes. 78 | High branching factor allows for a tree of lower height. Lower tree height allows for less disk I/O. 79 | Less disk I/O theoretically means better performance. 80 | 81 | Long Answer: 82 | B-Trees ("B Trees") and B+-Trees ("B Plus Trees") are balanced search trees that perform well 83 | on magnetic media and secondary storage because they minimize disk I/O ops. 84 | 85 | * As a matter of background information, in a typical 7200 RPM disk drive one platter rotation 86 | takes ~8.3ms which is ~5 orders of magnitude longer than the typical 100ns access time of silicon memory. 87 | So using the most efficient data structures to do dynamic set operations (like Search() Create() Insert()) 88 | is very important. 89 | 90 | B-Tree algorithms are good for accessing pages (or blocks) of stored information which are then 91 | copied into main memory for processing. In the worst case, they are designed to do dynamic set operations 92 | in O(lg n) time because of their high "branching factor" (think hundreds or thousands of keys off of any 93 | node). It is this branching factor that makes B-Trees so efficient for block storage/retrieval, 94 | since a large branching factor greatly reduces the height of the tree and thus the number of 95 | disk accesses needed to find any key! 96 | 97 | * For relative sizing reference: A B-Tree with a branching factor of 1001 and a height of 2 98 | can store over 1 Billion keys! And since the root node can be kept in main memory, you only need 99 | 2 disk accesses to find any key in this tree! 100 | 101 | In B+-Trees, all records ("satellite information") are stored at the leaf level while keys and 102 | child pointers are stored in interior nodes (aka non-leaf nodes). This maximizes the branching factor 103 | of the internal nodes. This is the advantage of a B+-Tree over a regular B-Tree. 104 | -------------------------------------------------------------------------------- /Best Sources to understand Java: -------------------------------------------------------------------------------- 1 | http://howtodoinjava.com/java-interview-questions/ 2 | Java2novice website: http://www.java2novice.com/java_interview_questions/ 3 | List to all the 152 videos of InterviewDot Job channel on youtube: https://www.youtube.com/playlist?list=PLHyEAfc_mrxbpkMK_dMLNztJVDquEKzfA 4 | 5 | Video number 17 is very very IMP. Prepare all the 75 questions 6 | 7 | Videos on Youtube channel: SharingIsLearning 8 | -------------------------------------------------------------------------------- /Best of Best website for Java Interview Questions: -------------------------------------------------------------------------------- 1 | http://howtodoinjava.com/java-interview-questions/ 2 | -------------------------------------------------------------------------------- /Binomial Coefficient Calculation: -------------------------------------------------------------------------------- 1 | Source: http://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/ 2 | Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). 3 | For example, your function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2. 4 | 5 | We have discussed a O(n*k) time and O(k) extra space algorithm in this post. The value of C(n, k) can be 6 | calculated in O(k) time and O(1) extra space 7 | 8 | 9 | 10 | // Returns value of Binomial Coefficient C(n, k) 11 | int binomialCoeff(int n, int k) 12 | { 13 | int res = 1; 14 | 15 | // Since C(n, k) = C(n, n-k) 16 | if ( k > n - k ) 17 | k = n - k; 18 | 19 | // Calculate value of [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] 20 | for (int i = 0; i < k; ++i) 21 | { 22 | res *= (n - i); 23 | res /= (i + 1); 24 | } 25 | 26 | return res; 27 | } 28 | -------------------------------------------------------------------------------- /Bitwise Operations in Java: -------------------------------------------------------------------------------- 1 | http://www.fredosaurus.com/notes-java/data/expressions/bitops.html 2 | Examples -> http://www.erpgreat.com/java/java-bitwise-shift-operators.htm 3 | -> http://stackoverflow.com/questions/16763917/what-is-the-purpose-of-the-unsigned-right-shift-operator-in-java 4 | NOTE: Specifically look for use of >>> bitwise operator in the above example 5 | 6 | 7 | UNSIGNED RIGHT SHIFT OPERATOR (>>>): 8 | A normal right shift >> of a negative number will keep it negative. I.e. the sign bit will be retained. 9 | 10 | An unsigned right shift >>> will shift the sign bit too, replacing it with a zero bit. 11 | 12 | There is no need to have the equivalent left shift because there is only one sign bit and it is the leftmost bit so it only interferes when shifting right. 13 | 14 | Essentially, the difference is that one preserves the sign bit, the other shifts in zeros to replace the sign bit. 15 | 16 | For positive numbers they act identically. 17 | 18 | For an example of using both >> and >>> see BigInteger shiftRight. 19 | 20 | -------------------------------------------------------------------------------- /Boundary test cases to check whether a LL is circular: -------------------------------------------------------------------------------- 1 | Question : write boundary test cases for whether a linked list is circular linked list or not? 2 | 3 | Source: http://www.careercup.com/question?id=5670876009725952 4 | 5 | Ans: 6 | here are several approach to check whether link list is circular or not:- 7 | 8 | 1st Approach : (Boolean Flag) 9 | Take a flag bit at each node and make it zero initially. While visiting each node make the flag bit as one if it is zero. 10 | If already flag bit found as one then loop exist that is circular list. 11 | If somebody ask how we can take the flag bit at each node by own then you just give answer as while 12 | doing programming we always take some extra bit for future purpose.so we make it as flag bit. If they also 13 | not satisfied then just say i will take resize function to increase the size of node and then we use the flag bit. 14 | Time complexity= O(n). 15 | 16 | 2nd Approach : (Address Array) 17 | Take an array. Store the 1st node next address and go to second node. while go to next node just check whether 18 | next address is already stored in array........and so on .Time complexity =O(square of n) 19 | 20 | 3rd approach: (Slow and Fast Pointer) 21 | start with two pointer from starting point of the list and increase 1st pointer by one and 2nd by two if the 22 | pointer meet on same point then the list is circular list else not. 23 | Time complexity = O(n). This is the best algorithm. Its time complexity is asymptotically order of n but actually 24 | on an average it is n/2. 25 | -------------------------------------------------------------------------------- /BufferedReader vs Scanner: -------------------------------------------------------------------------------- 1 | http://en.allexperts.com/q/Java-1046/2009/2/Difference-Scanner-Method-Buffered.htm 2 | http://stackoverflow.com/questions/2231369/scanner-vs-bufferedreader 3 | What does a parser do ? -> http://stackoverflow.com/questions/13924111/what-does-this-mean-parsing-a-text-file-or-data-stream-and-does-it-apply-with 4 | -------------------------------------------------------------------------------- /C++ vs Java: -------------------------------------------------------------------------------- 1 | Question: What are the differences between C++ and Java? 2 | Ans: 3 | 4 | IMP POINT: 5 | Java is platform independant whereas c++ is platform dependant.(NOTE: Every different OS has a different JVM) 6 | Please watch this video to clear all doubts: https://www.youtube.com/watch?v=XjNwyXx2os8 7 | 8 | 1) Java doesnot support pointers. Pointers are tricky to use and troublesome. 9 | 10 | 2) Java does not support multiple inheritances because it causes more problems than it solves. 11 | Instead Java supports multiple interface inheritance, which allows an object to 12 | inherit many method signatures from different interfaces with the condition 13 | that the inheriting object must implement those inherited methods. 14 | The multiple interface inheritance also allows an object to behave polymorphically on those methods. 15 | 16 | 3) Java does not include structures or unions. 17 | 18 | 4) Java does not support destructors but adds a finalize() method. 19 | Finalize methods are invoked by the garbage collector prior to reclaiming 20 | the memory occupied by the object, which has the finalize() method. 21 | This means you do not know when the objects are going to be finalized. 22 | Avoid using finalize() method to release non-memory resources like file 23 | handles, sockets, database connections etc because Java has only a finite 24 | number of these resources and you do not know when the garbage collection is going to kick in 25 | to release these resources through the finalize() method. 26 | 27 | 5) All the code in Java program is encapsulated within classes therefore Java does not have 28 | global variables or functions. 29 | 30 | 6) C++ requires explicit memory management, while Java includes automatic garbage collection. 31 | 32 | 33 | 34 | 35 | VERY IMPORTANT TO REMEMBER: GG-MS-PhD(h is silent) 36 | G-> Global variables 37 | G-> Garbage Collection(required for memory management) 38 | M-> Multiple Inheritance 39 | S-> Struct and Union 40 | P-> Pointers 41 | D-> Destructors 42 | -------------------------------------------------------------------------------- /Classpath importance in Java: -------------------------------------------------------------------------------- 1 | http://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html 2 | 3 | IMP video tutorial for classpath in Java -> https://www.youtube.com/watch?v=o08TvSyKmpk 4 | -> https://www.youtube.com/watch?v=O8eNxELc4dE 5 | 6 | Other Importance of classpath: 7 | 8 | 1. Classpath in Java is an environment variable used by Java Virtual machine to locate or find 9 | class files in Java during class loading. 10 | 11 | 2. You can override value of Classpath in Java defined by environment variable CLASSPATH by providing 12 | JVM command line option –cp or –classpath while running your application. 13 | 14 | 3. If two classes with same name exist in Java Classpath then the class which comes earlier in 15 | Classpath will be picked by Java Virtual Machine. 16 | 17 | 4. By default CLASSPATH in Java points to current directory denoted by "." and it will look for 18 | any class only in current directory. 19 | 20 | 5. When you use the -jar command line option to run your program as an executable JAR, then the 21 | Java CLASSPATH environment variable will be ignored, and also the -cp and -classpath switches will be ignored and In this case you can set your java classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute. 22 | 23 | 6. In Unix of Linux Java Classpath contains names of directory with colon “:” separated , On 24 | Windows Java Classpath will be semi colon “;” separated while if you defined java classpath in Manifest 25 | file those will be space separated. 26 | 27 | 7. You can check value of classpath in java inside your application by looking at following 28 | system property “java.class.path” System.getProperty("java.class.path") 29 | 30 | Class-Path attribute is used to contain classpath inside manifest file. Also make sure that your 31 | manifest file must end with a blank line (carriage return or new line) , here is an example of java 32 | classpath in manifest file. 33 | 34 | Main-Class: com.classpathexample.Demo_Classpath 35 | Class-Path: lib/tibco.jar lib/log4j.jar 36 | 37 | 8. It’s also important to note that path specified in manifest file is not absolute instead 38 | they are relative from application jar’s path. For example in above if your application jar file is 39 | in C:\test directory you must need a lib directory inside test and tibco.jar and log4j.jar inside that. 40 | 41 | 9. ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries 42 | to load a particular Class at Runtime and don’t find that on Java classpath due to result 43 | of Class.forName() or loadClass() method invocation. 44 | 45 | 10. NoClassDefFoundError comes when a particular class was present in Java Classpath during 46 | compile time but not available during runtime on Classpath in Java. 47 | 48 | -------------------------------------------------------------------------------- /Coding to interfaces: -------------------------------------------------------------------------------- 1 | Why coding to interfaces in better than coding to classes: 2 | http://manikandanmv.wordpress.com/2010/12/18/coding-to-interfaces/ 3 | -------------------------------------------------------------------------------- /Comparable interface vs Comparator interface: -------------------------------------------------------------------------------- 1 | Best video of 15 minutes to expain this: https://www.youtube.com/watch?v=Xy2PqCNgFig 2 | Another VERY IMP video: https://www.youtube.com/watch?v=qBRBAqA25o8 3 | 4 | Theory: 5 | Both interfaces support Generics. 6 | That is Comparable and Comparator 7 | 8 | Comparable belongs to lang package 9 | Comparator belongs to util package 10 | 11 | Comparable is used for natural ordering of Elements 12 | Comparator is used for other comparisons 13 | 14 | 15 | NOTE: compareTo() method of predefined String class returns the following: 16 | public class compare { 17 | public static void main(String[] args) { 18 | String s1="Hello"; 19 | String s2="World"; 20 | System.out.println(s1.compareTo(s2)); 21 | } 22 | } 23 | 24 | O/P: -15 25 | -------------------------------------------------------------------------------- /ConcurrentHashMap vs Collections.synchronizedMap(Map): -------------------------------------------------------------------------------- 1 | Source: http://www.pixelstech.net/article/1394026282-ConcurrentHashMap-vs-Collections-synchronizedMap() 2 | http://stackoverflow.com/questions/510632/whats-the-difference-between-concurrenthashmap-and-collections-synchronizedmap 3 | http://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 4 | 5 | 6 | The main difference between these two is that ConcurrentHashMap will lock only portion of the data which are 7 | being updated while other portion of data can be accessed by other threads. However, Collections.synchronizedMap() 8 | will lock all the data while updating, other threads can only access the data when the lock is released. 9 | If there are many update operations and relative small amount of read operations, you should choose 10 | ConcurrentHashMap. 11 | 12 | Also one other difference is that ConcurrentHashMap will not preserve the order of elements in the Map passed in. 13 | It is similar to HashMap when storing data. There is no guarantee that the element order is preserved. 14 | While Collections.synchronizedMap(0 will preserve the elements order of the Map passed in. For example, 15 | if you pass a TreeMap to ConcurrentHashMap, the elements order in the ConcurrentHashMap may not be the same 16 | as the order in the TreeMap, but Collections.synchronizedMap() will preserve the order. 17 | 18 | Furthermore, ConcurrentHashMap can guarantee that there is no ConcurrentModificationException thrown while 19 | one thread is updating the map and another thread is traversing the iterator obtained from the map. 20 | However, Collections.synchronizedMap() is not guaranteed on this. If we obtain an Iterator from 21 | Collections.synchronizedMap() by calling map.keySet().iterator() and then traverse the iterator, 22 | at the same time if another thread is trying to updating the map by calling map.put(K,V), we will get 23 | a ConcurrentModificationException. 24 | 25 | Map map = Collections.synchronizedMap(new TreeMap()); 26 | 27 | map.put("key1","value1"); 28 | map.put("key2","value2"); 29 | map.put("key3","value3"); 30 | 31 | Set> entries = map.entrySet(); 32 | 33 | Iterator> iter = entries.iterator(); 34 | 35 | while(iter.hasNext()){ 36 | System.out.println(iter.next()); //Will throw ConcurrentModificationException 37 | map.remove("key2"); 38 | } 39 | Now I am wondering whether there is one object which can preserve the insertion order of elements like 40 | Collections.synchronizedMap() and also doesn't throw ConcurrentModificationException like ConcurrentHashMap. 41 | Fortunately since 1.6 there is a class called ConcurrentSkipListMap which can fulfill these two requirements, 42 | from the documentation, we can find that ConcurrentSkipListMap will not throw ConcurrentModificationException 43 | and also it will preserve the insertion order of the Map passed in. The only drawback it may have is its 44 | performance. 45 | 46 | -------------------------------------------------------------------------------- /Design Patterns: -------------------------------------------------------------------------------- 1 | Learn all the design patterns from MikeAbyss channel on youtube 2 | Below is the link: 3 | https://www.youtube.com/playlist?list=PL8C53D99ABAD3F4C8 4 | -------------------------------------------------------------------------------- /Diff between Set and List: -------------------------------------------------------------------------------- 1 | Source-> http://javarevisited.blogspot.com/2012/04/difference-between-list-and-set-in-java.html 2 | 3 | ALL three Map,SET and LIST are interfaces in Java. 4 | http://docs.oracle.com/javase/7/docs/api/java/util/Map.html 5 | http://docs.oracle.com/javase/7/docs/api/java/util/Set.html 6 | http://docs.oracle.com/javase/7/docs/api/java/util/List.html 7 | 8 | Please Note: This is much better explanation than given in the link above. 9 | 10 | List vs Set in Java 11 | 12 | Difference between Set and List in Java: 13 | Here are few note worthy differences between List and Set in Java. 14 | Remember that both of them are used to store objects and provides convenient API(that means libraries) 15 | to insert, remove and retrieve elements, along with to support Iteration over collection. 16 | 17 | 1) Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows 18 | duplicates while Set doesn't allow any duplicate. If you insert duplicate in Set it will replace the older 19 | value with the new value. While if a duplicate is inserted in a List, it will be appended as the next 20 | element in the List. In case of duplicates in Map, if the keys are the same(Remember, Map works on KEY-VALUE pairs), 21 | the value of the latest will overwrite the value previously existed at that same key(Remember, Map works on KEY-VALUE pairs). 22 | 23 | 2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while 24 | Set is an unordered Collection. List maintains insertion order of elements(Example: ArrayList), means any element which is 25 | inserted before will go on lower index than any element which is inserted after. Set in Java doesn't 26 | maintain any order(Example: HashSet). Though Set provide another alternative called SortedSet which can store Set elements 27 | in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set. 28 | 29 | 3) Set uses equals() method to check uniqueness of elements stored in Set, while SortedSet uses compareTo() 30 | method to implement natural sorting order of elements. In order for an element to behave properly in Set and 31 | SortedSet, equals and compareTo must be consistent to each other. 32 | 33 | 4) Popular implementation of List interface in Java includes ArrayList, Vector and LinkedList. While popular 34 | implementation of Set interface includes HashSet, TreeSet and LinkedHashSet. 35 | 36 | 37 | Read more: http://javarevisited.blogspot.com/2012/04/difference-between-list-and-set-in-java.html#ixzz2qF8yRnUr 38 | 39 | 40 | Code to test the statements written above: 41 | import java.awt.List; 42 | import java.util.HashMap; 43 | import java.util.HashSet; 44 | import java.util.LinkedList; 45 | import java.util.Map; 46 | import java.util.Set; 47 | 48 | public class Difference { 49 | public static void main(String[] args) { 50 | Set sets=new HashSet(); 51 | sets.add(1); 52 | sets.add(1); 53 | System.out.println(sets.size()); 54 | 55 | LinkedList lists=new LinkedList(); 56 | lists.add(1); 57 | lists.add(1); 58 | System.out.println(lists.size()); 59 | 60 | Map maps=new HashMap(); 61 | maps.put(1, 1); 62 | maps.put(1, 2); // Just to check whether the pevious VALUE at the same key is over written or not. 63 | System.out.println(maps.size()); 64 | System.out.println(maps.get(1)); // Output comes 2, hence the pevious VALUE at the same key is over written 65 | } 66 | } 67 | 68 | /* 69 | Output 70 | 71 | 1 //size of Set 72 | 2 //size of List 73 | 1 //size of Map 74 | 2 // value at key 1 of the Map 75 | 76 | */ 77 | 78 | Ordered lists of element (unique or not) 79 | Conform to Java's interface named List 80 | Can be accessed by index 81 | 82 | LinkedList 83 | ArrayList 84 | Lists of unique elements: 85 | Conform to Java's interface named Set 86 | Can not be accessed by index 87 | 88 | HashSet (unordered) 89 | LinkedHashSet (ordered) 90 | TreeSet (sorted by natural order or by provided comparator) 91 | Both interfaces Set and List conform to Java's interface named Collection 92 | 93 | ╔═══════════════════╦══════════════════════╦═════════════════════════════╗ 94 | ║ ║ List ║ Set ║ 95 | ╠═══════════════════╬══════════════════════╬═════════════════════════════╣ 96 | ║ Duplicates ║ YES ║ NO ║ 97 | ╠═══════════════════╬══════════════════════╬═════════════════════════════╣ 98 | ║ Order ║ ORDERED ║ DEPENDS ON IMPLEMENTATION ║ 99 | ╠═══════════════════╬══════════════════════╬═════════════════════════════╣ 100 | ║ Positional Access ║ YES ║ NO ║ 101 | ╚═══════════════════╩══════════════════════╩═════════════════════════════╝ 102 | -------------------------------------------------------------------------------- /Dynamic Programming vs Greedy vs Divide & Conquer: -------------------------------------------------------------------------------- 1 | StackOverflow: http://stackoverflow.com/questions/16690249/what-is-the-main-difference-between-dynamic-programming-and-greedy-approach-in-t 2 | http://stackoverflow.com/questions/13713572/how-is-dynamic-programming-different-from-greedy-technique 3 | 4 | 5 | Divide & Conquer vs DP vs Gredy: http://stackoverflow.com/questions/6162465/divide-and-conquer-dynamic-programming-and-greedy-algorithms 6 | Divide & Conquer vs DP: http://stackoverflow.com/questions/13538459/difference-between-divide-and-conquer-algo-and-dynamic-programming 7 | 8 | Examples of Divide & Conquer: 9 | SEARCHING ALGORITHM: 10 | 1.Binary Search 11 | SORTING ALGORITHMS: 12 | 1. MergeSort 13 | 2. QuickSort 14 | 15 | Examples of Dynamic Programming: 16 | 1. BellmanFord Algorithm for Single Source Shortest Path Calculation(It gives path from single source to all the other nodes) 17 | [Youtube Video: https://www.youtube.com/watch?v=iTW2yFYd1Nc&list=PLATr4Ip40BjYUgHgTKe5ZJ_hl-ccCeAai] 18 | 2. Floyd Warshall Algorithm for All Pair Shorted Path Calculation(It gives path from all nodes to all other nodes) 19 | [Youtube Video: https://www.youtube.com/watch?v=odeFemb3o-o] 20 | 21 | Examples of Greedy: 22 | 1. Dijkstra's algorithm for Single Source Shortest Path Calculation(It gives path from single source to a single destination node) 23 | 2. Prim's Algorithm to find Minimum Spanning Tree 24 | 3. Kruskal's Algorithm to find Minimum Spanning Tree 25 | (Difference between Prims and Kruskals Algorithm: http://www.quora.com/What-is-the-difference-in-Kruskals-and-Prims-algorithm) 26 | Q: Given the above differences, how is Kruskal's algorithm considered as a greedy approach ? 27 | [It is said that Kruskal's algorithm for MST construction is greedy, but the algorithm chooses global minimum and 28 | instead of local minimum unlike Prim's algorithm. Can someone explain how Kruskal's algorithm 29 | is considered a greedy approach ?] 30 | Source: http://stackoverflow.com/questions/27639942/how-is-kruskals-algorithm-greedy/27640057#27640057 31 | Ans: In Kruskal's algorithm, we sort all the edges in the graph and iteratively choose minimum edge during each iteration 32 | to check whether it can be added to the MST (doesn't form cycle). 33 | Thus, once an edge is selected and added in the MST, no further changes are made during the remaining other iterations. 34 | If you compare this with Bellman-Ford algorithm for Shortest Path, during each iteration we get the shortest path, and during 35 | other remaining iterations we check to see if there are any shortest paths that can replace the previously calculated 36 | shortest path. Thus, here we are modifying the previous results and taking into consideration the results of all iterations, 37 | that is the shortest paths from all the nodes (since no of iterations = (no of nodes in graph) - 1). 38 | 39 | This, is the reason why Bellman Ford is Dynamic and Kruskal's is Greedy 40 | [NOTE: Though Bellman Ford is for Single Source Shortest Path and Kruskal's is for MST, hence once might consider that 41 | these two cannot be compared together, though concentrate that the solution is not compared but the approach of algorithm 42 | is compared to understand difference between DYNAMIC vs GREEDY] 43 | -------------------------------------------------------------------------------- /Enumeration Vs Iterator: -------------------------------------------------------------------------------- 1 | Both Enumeration and Iterator are interfaces in Java. 2 | Both are used to store the elements of a data structure in Java 3 | The functionality of Enumeration and the Iterator have minor difference. You can get remove() 4 | from Iterator to remove an element, while Enumeration does not have remove() 5 | method. Using Enumeration you can only traverse and fetch the objects, where as using 6 | Iterator we can also add and remove the objects. So Iterator can be useful if you want 7 | to manipulate the list and Enumeration is for read-only access. 8 | public interface Iterator 9 | An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. 10 | Iterators differ from enumerations in two ways: 11 | a) Iterators allow the caller to remove elements from the underlying collection during the iteration with 12 | well-defined semantics. 13 | b) Method names have been improved. 14 | The Iterator interface is a member of the Java Collections Framework whereas the Enumeration interface is not. 15 | 16 | 17 | Please see Enumeration Interface Java Docs -> http://docs.oracle.com/javase/6/docs/api/java/util/Enumeration.html 18 | Iterator Interface Java Docs -> http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html 19 | -------------------------------------------------------------------------------- /Exception vs Error: -------------------------------------------------------------------------------- 1 | Question: What is the difference between exception and error? 2 | Ans: An error is an irrecoverable condition occurring at runtime like out of 3 | memory error. These kind of jvm errors cannot be handled at runtime. 4 | Exceptions are because of condition failures, which can be handled 5 | easily at runtime. 6 | 7 | 8 | The super class of both Exception(which is a class) and Error(which is a class) is Throwable(which is a class). 9 | -------------------------------------------------------------------------------- /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 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 | -------------------------------------------------------------------------------- /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(LINEAR PROBING AND CHAINING IS THE APPROACH 9 | USED TO SOLVE COLLSION PROBLEM IN HASHMAP) and hence the hashtable would be more like a linkedlist. 10 | Collisions also ruin memory utilization- if I have 70 elements in 100 buckets, but those 70 elements hash to 11 | only 4 buckets (and yes, Virginia, I’ve seen collision rates this bad), then 96 of my buckets aren’t doing 12 | me any good at, I’m just wasting that space. 13 | 4) Occasionally HashMap/Hashtable requires resizing when the original size of HashMap/Hashtable buckets 14 | are full. Resizing takes O(n) time as the elements from the previous hashtable/HashMap are transferred to 15 | a new bigger Hashtable/HashMap. This is not good for implementation. 16 | 5) The concept that Hashtables/HashMap offers O(constant) (aka O(1) ) time complexity 17 | for insertion, deletion and searchingis something to rethink on as the datastructure givies that 18 | time complexity on a average scale, which is called as "AMORTIZED" time complexity. That means that there 19 | would be atleast on instance out of n instances where the Time Complexity would be O(n) and not O(constant). 20 | This is the time when the HashMap/Hashtable requires resizing. 21 | 22 | http://stackoverflow.com/questions/6924852/what-are-the-disadvantages-to-hashmaps 23 | http://web.archive.org/web/20090430172748/http://enfranchisedmind.com/blog/posts/problems-with-hash-tables/ 24 | http://en.wikipedia.org/wiki/Hash_table#Drawbacks 25 | -------------------------------------------------------------------------------- /How does Thread Locks work: -------------------------------------------------------------------------------- 1 | 2 | How does thread locks really work in Java? (Internal Working of Thread Locks) 3 | Ans: http://stackoverflow.com/questions/17368595/java-lock-concept-how-internally-works 4 | -------------------------------------------------------------------------------- /How to make code readable to the other programmers who look your code: -------------------------------------------------------------------------------- 1 | The following methods can be used to make sure that the code is readable and understood by everyone who will 2 | follow you: 3 | 1) Put COMMENTS on important functions on how they behave 4 | 2) Strong DOCUMENTATION for every function implemented properly 5 | 3) Using MEANINGFUL NAMES for variables and object names so that they can be understood properly 6 | Example: Animal i =new Animal(); // instead of using i variable we can use 7 | Animal animalInstance = new Animal(); 8 | 4) Using the SAME STYLE of writing the code as used by the entire team, so that other members can understand 9 | your code that is written. 10 | 11 | -------------------------------------------------------------------------------- /IMP Questions: -------------------------------------------------------------------------------- 1 | ******************************************************************************************************************* 2 | 2 SUM Problem 3 | http://coderevisited.com/2-sum-problem/ 4 | http://www.careercup.com/question?id=15206700 5 | 6 | 7 | The 2 sum problem is a classic variation of the subset sum problem. It is defined as the following: 8 | You have an unsorted array, and you are given a value S. Find all pairs of elements in the array that 9 | add up to value S. 10 | 2 solutions - one minimizes space complexity, and the other time. As stated in the "hint", 11 | one approach is to hash the entire array, and then for each element check if S-array[j] is in the 12 | hash table. This takes O(n) time and O(n) space to store the array. 13 | Alternatively, if one wishes to minimize space complexity, simply sort the array. Then, have two 14 | pointers - one initialized to array[0] and the other array[length-1]. Then check the sums; if the 15 | sum is > S, decrement the right pointer. If it is < S, increment the left pointer. 16 | 17 | Sample Java code for the second method of finding 2sum: 18 | public static void findTwoSum(int[] A, int x) { 19 | Arrays.sort(A); 20 | int start = 0; 21 | int end = A.length - 1; 22 | boolean found = false; 23 | while (!found && start < end) { 24 | if (A[start] + A[end] == x) 25 | found = true; 26 | else if (A[start] + A[end] > x) 27 | end--; 28 | else if (A[start] + A[end] < x) 29 | start++; 30 | } 31 | if (found) 32 | System.out.println("Sum " + x 33 | + " is found, values the making sum are " + A[start] + " , " 34 | + A[end]); 35 | else 36 | System.out.println("No pair exists whose sum is " + x); 37 | } 38 | 39 | *********************************************************************************************************** 40 | To reverse a string in Java: 41 | 42 | package BST_Demo; 43 | 44 | public class ReverseArray { 45 | public static void main(String[] args) { 46 | 47 | String givenString = "Am I bad ? "; 48 | StringBuilder reverse=new StringBuilder(givenString.length()); 49 | for(int i=givenString.length()-1;i>=0;i--){ 50 | reverse.append(givenString.charAt(i)); 51 | } 52 | System.out.println(reverse.toString()); 53 | 54 | } 55 | } 56 | 57 | 58 | How to implement a stack which will support following operations in O(1) time complexity? 59 | 1) push() which adds an element to the top of stack. 60 | 2) pop() which removes an element from top of stack. 61 | 3) findMiddle() which will return middle element of the stack. 62 | 4) deleteMiddle() which will delete the middle element. 63 | Push and pop are standard stack operations. 64 | 65 | http://www.geeksforgeeks.org/design-a-stack-with-find-middle-operation/ 66 | 67 | 68 | Very IMP Q -> Disadvantages of HashMap or Hashtable OR Why is BALANCED TREES better than using Hashtable 69 | or HashMap? 70 | Ans -> 71 | Very IMP Q -> Disadvantages of HashMap or Hashtable OR Why is BALANCED TREES better than using Hashtable 72 | or HashMap? 73 | Ans -> 74 | In short: 75 | 1) Requires more main memory 76 | 2) Hashing algorithm does not result in spatial locality. Because hash tables cause 77 | access patterns that jump around, this can trigger microprocessor cache misses that cause long delays. 78 | 3) Similar key types will result in more collision and hence the hashtable would be more like a linkedlist. 79 | Collisions also ruin memory utilization- if I have 70 elements in 100 buckets, but those 70 elements hash to 80 | only 4 buckets (and yes, Virginia, I’ve seen collision rates this bad), then 96 of my buckets aren’t doing 81 | me any good at, I’m just wasting that space. 82 | 4) Occasionally HashMap/Hashtable requires resizing when the original size of HashMap/Hashtable buckets 83 | are full. Resizing takes O(n) time as the elements from the previous hashtable/HashMap are transferred to 84 | a new bigger Hashtable/HashMap. This is not good for implementation. 85 | 5) The concept that Hashtables/HashMap offers O(constant) (aka O(1) ) time complexity 86 | for insertion, deletion and searchingis something to rethink on as the datastructure givies that 87 | time complexity on a average scale, which is called as "AMORTIZED" time complexity. That means that there 88 | would be atleast on instance out of n instances where the Time Complexity would be O(n) and not O(constant). 89 | This is the time when the HashMap/Hashtable requires resizing. 90 | 91 | http://stackoverflow.com/questions/6924852/what-are-the-disadvantages-to-hashmaps 92 | http://web.archive.org/web/20090430172748/http://enfranchisedmind.com/blog/posts/problems-with-hash-tables/ 93 | http://en.wikipedia.org/wiki/Hash_table#Drawbacks 94 | 95 | 96 | /* Program to find the 2nd minimum element in the array */ 97 | #include 98 | #include /* For INT_MAX */ 99 | 100 | /* Function to print first smallest and second smallest elements 101 | 102 | Algorithm: 103 | 104 | 1) Initialize both first and second smallest as INT_MAX 105 | first = second = INT_MAX 106 | 2) Loop through all the elements. 107 | a) If the current element is smaller than first, then update first 108 | and second. 109 | b) Else if the current element is smaller than second then update 110 | secondAlgorithm: 111 | 112 | */ 113 | 114 | void print2Smallest(int arr[], int arr_size) 115 | { 116 | int i, first, second; 117 | 118 | /* There should be atleast two elements */ 119 | if (arr_size < 2) 120 | { 121 | printf(" Invalid Input "); 122 | return; 123 | } 124 | 125 | first = second = INT_MAX; 126 | for (i = 0; i < arr_size ; i ++) 127 | { 128 | /* If current element is smaller than first then update both 129 | first and second */ 130 | if (arr[i] < first) 131 | { 132 | second = first; 133 | first = arr[i]; 134 | } 135 | 136 | /* If arr[i] is in between first and second then update second */ 137 | else if (arr[i] < second && arr[i] != first) 138 | second = arr[i]; 139 | } 140 | if (second == INT_MAX) 141 | printf("There is no second smallest element\n"); 142 | else 143 | printf("The smallest element is %d and second Smallest element is %d\n", 144 | first, second); 145 | } 146 | 147 | 148 | /* Driver program to test above function */ 149 | int main() 150 | { 151 | int arr[] = {12, 13, 1, 10, 34, 1}; 152 | int n = sizeof(arr)/sizeof(arr[0]); 153 | print2Smallest(arr, n); 154 | return 0; 155 | } 156 | 157 | ****************************************************************************************************** 158 | Longest Common SubSequence Problem: 159 | /* 160 | Question: Find the longest common subsequence between two strings 161 | 162 | Question and Answer Source: http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/ 163 | 164 | Algortihm: 1. declare a matrix of s1.length()+1 and s2.length()+1. 165 | +1 is to store the results of the previous matches 166 | 2. initialize row = 0 OR column = 0 to 0 which indicates that the previous matches was 0 167 | 3. for i=1 to s1.length+1 168 | for j=1 to s2.length+1 169 | if(s1.charAt(i-1)==s2.charAt(j-1)) 170 | dp[i][j]= dp[i-1][j-1]+1 // current match = previous match +1 171 | else 172 | dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]) 173 | 174 | // if the characters don't then the current matches = max of(previous matches) 175 | 176 | */ 177 | 178 | package SubstringAndSubsequenceProblems.Subsequence; 179 | 180 | import java.util.Scanner; 181 | 182 | 183 | public class LongestCommonSubsequence { 184 | 185 | 186 | private static int[][] dp; // matrix to store the match results 187 | 188 | public static void main(String[] args) { 189 | Scanner in = new Scanner(System.in); 190 | try{ 191 | System.out.println("LONGEST COMMON SUBSEQUENCE PROGRAM"); 192 | System.out.println("Enter the two strings"); 193 | String s1 = in.nextLine(); 194 | String s2 = in.nextLine(); 195 | System.out.println("The Longest common SUBSTRING using DP is: "+usingDP(s1,s2)); 196 | 197 | // Printing the Logest Common Subsequence 198 | int lengthOfLCSubSequence = usingDP(s1,s2); 199 | // we will construct a String of LCS from right to left. Hence we will use char array 200 | // instead of using StringBuilder which is used to construct the string from left to right 201 | 202 | char[] LCSubSequence = new char[lengthOfLCSubSequence]; 203 | 204 | // pass this char array along with the matrix and 2 strings to get the result of matches 205 | String longestCommonSubsequence = buildLCSubsequence(LCSubSequence,s1,s2); 206 | 207 | System.out.println("The Longext Common SubSequence is: "+longestCommonSubsequence); 208 | } 209 | finally{ 210 | in.close(); 211 | } 212 | } 213 | 214 | 215 | 216 | private static int usingDP(String s1, String s2) { 217 | 218 | dp = new int[s1.length()+1][s2.length()+1]; // additional +1 to store the previous match result which is 0 219 | 220 | // fill the row with s1 221 | for(int i=0;i<(s1.length()+1);i++) 222 | dp[i][0] = 0; 223 | 224 | // fill the column with s2 225 | for(int j=0;j<(s2.length()+1);j++) 226 | dp[0][j] = 0; 227 | 228 | 229 | int result = 0; // to store the length of MAX COMMON SUBSEQUENCE MATCH 230 | 231 | // fill the remaining rows and columns based on matches 232 | for(int i=1;i<(s1.length()+1);i++){ 233 | for(int j=1;j<(s2.length()+1);j++){ 234 | 235 | // if current characters match then the length of the substring is previous matches + 1 236 | if(s1.charAt(i-1)==s2.charAt(j-1)) 237 | dp[i][j] = dp[i-1][j-1]+1; 238 | 239 | else // if doesnt match then current match = Max of (previous matches) 240 | dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); 241 | 242 | result = Math.max(result,dp[i][j]); // this is to check the maximum match found 243 | 244 | } 245 | } 246 | 247 | return result; 248 | } 249 | 250 | private static String buildLCSubsequence(char[] LCSubSequence, String s1, String s2) { 251 | 252 | 253 | int i = s1.length(); 254 | int j = s2.length(); 255 | 256 | int index = LCSubSequence.length-1; 257 | 258 | while(i>0 && j>0){ // greater than 0 because there is nothing at 0th row and 0th column in the match matrix 259 | 260 | if(s1.charAt(i-1)==s2.charAt(j-1)){ // -1 because i and j start from their respective lengths 261 | // append the character 262 | LCSubSequence[index]=s1.charAt(i-1); 263 | // decrement the index 264 | index--; 265 | // decrement the i and j pointers 266 | i--; 267 | j--; 268 | } 269 | 270 | // if the characters do not match then go in the max direction in the match matrix 271 | 272 | else if(dp[i-1][j]>dp[i][j-1]) 273 | i--; 274 | 275 | else 276 | j--; 277 | 278 | } 279 | 280 | return String.valueOf(LCSubSequence); // convert char array to string and return 281 | 282 | 283 | } 284 | } 285 | 286 | 287 | -------------------------------------------------------------------------------- /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 | 5 | Before reading the above article, please read the below link so that you will undestand the above article: 6 | http://javarevisited.blogspot.com/2013/01/difference-between-stack-and-heap-java.html 7 | -------------------------------------------------------------------------------- /IMP Websites for Interview Preparation: -------------------------------------------------------------------------------- 1 | 1. careercup.com 2 | 2. geeksforgeeks.org 3 | 3. http://www.fgdsb.com/ 4 | -------------------------------------------------------------------------------- /IMP Websites with Java Intervew Questions: -------------------------------------------------------------------------------- 1 | http://www.techinterviews.com/30-simple-java-questions 2 | http://howtodoinjava.com/2012/10/09/working-with-hashcode-and-equals-methods-in-java/ 3 | http://www.caveofprogramming.com/youtube/ 4 | http://www.caveofprogramming.com 5 | -------------------------------------------------------------------------------- /Inclusive vs Exclusive OR: -------------------------------------------------------------------------------- 1 | http://stackoverflow.com/questions/3246249/what-is-the-difference-between-inclusive-and-exclusive-or 2 | -------------------------------------------------------------------------------- /Indexing in Databases: -------------------------------------------------------------------------------- 1 | Advantages: 2 | Searching (Retrieval) is faster as the data is sorted in that column so internally a Binary Search can 3 | be used which reduces the time from O(N) i.e. linear learch to O(lg N) i.e. binary search. 4 | Hence searching/retrieving becomes faster(i.e. database is optimized) 5 | 6 | Disadvantage: 7 | 1) Takes extra space 8 | 2) Insertion, Updation and Deletion is slow since if tuples are inserted, updated or deleted after 9 | creating indexes then the indexes are also modified and reassigned every time for every insert/update/delete 10 | operation. 11 | 12 | Please watch the below video of 10 minutes carefully: 13 | https://www.youtube.com/watch?v=ow6eSj-dNKg 14 | -------------------------------------------------------------------------------- /Inner Class in Java: -------------------------------------------------------------------------------- 1 | https://www.youtube.com/watch?v=5CA07hcesAQ 2 | 3 | 24 minute video on Youtube. But explanation is best 4 | -------------------------------------------------------------------------------- /InterThread and InterProcess Communication: -------------------------------------------------------------------------------- 1 | http://programmers.stackexchange.com/questions/174963/inter-process-and-inter-thread-data-sharing 2 | 3 | Interthread Communication: mutex, semaphores 4 | 5 | Interprocess Communication: http://www.tldp.org/LDP/tlk/ipc/ipc.html 6 | -------------------------------------------------------------------------------- /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 http://www.codewalk.com/2012/04/least-recently-used-lru-cache-implementation-java.html 2 | Implementation-> http://www.geeksforgeeks.org/implement-lru-cache/ 3 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Local variables default value in Java: -------------------------------------------------------------------------------- 1 | Question: What is default value of a local variables? 2 | Ans: The local variables are not initialized to any default values. We should 3 | not use local variables with out initialization. Even the java COMPILER(very important, not runtime but 4 | during compile time itself error is thrown) throws error. 5 | 6 | Example: 7 | class AbstractDemo{ 8 | public static void main(String[] args) { 9 | 10 | 11 | me(10); 12 | } 13 | public static void me(int n) 14 | { 15 | int k; 16 | System.out.println(k); 17 | } 18 | } 19 | 20 | Output: Complilation Error: Local variable k not initialized 21 | -------------------------------------------------------------------------------- /MVC design pattern or architecture: -------------------------------------------------------------------------------- 1 | The MVC architecture or Design Patter is also called as "SEPARATION OF CONCERNS" 2 | 3 | 4 | 5 | Watch the following videos for understanding MVC. Please watch all the videos: 6 | 7 | 4 minute video: https://www.youtube.com/watch?v=qXRcVhWxuaU 8 | 4 minute video: https://www.youtube.com/watch?v=YuqJcy6zCMU 9 | 4 minute video: https://www.youtube.com/watch?v=eTdVkgF_Slo 10 | 4 minute vidoe: https://www.youtube.com/watch?v=vJwE5eNiAfk 11 | 12 | Model -> This layer handles the DATA. 13 | Also called as "the brain". This contains the bussiness logic. This layer also interacts with the 14 | Data-Access layer (also called as database) for retrieving User Query results(the different user queries are 15 | provided by the Controller which interacts with User Input) 16 | View -> This layer handles the DECISIONS. 17 | This is the front end(User Interface) or the part of the application visible to the user. Many views can be created 18 | for different users according to their priority and access levels 19 | Controller -> This layer handles the PRESENTATION. 20 | The Controller is responsible for handling user inputs. This is the part which takes input from 21 | the user and provides to the Model which gives query results to View so that the query results are visible 22 | to the user. 23 | 24 | PLEASE NOTE: 25 | 1) Controller is the middle layer between Model and View. 26 | 2) Model and View donot talk to each other directly. They talk through the controller. 27 | 3) Model can talk to Controller. View can talk to Controller. Controller can talk to both Model and View. 28 | 4) To understand the above three lines, please watch the fourth video link mentioned above 29 | 30 | We can say that one of the COMMON flow in MVC architecture or design patttern is: 31 | Controller(take inputs from user) -> Model (communicate with database or data-access layer to provide query 32 | result) -> View (show the proper query results to the user) 33 | -------------------------------------------------------------------------------- /Marker Interfaces in Java: -------------------------------------------------------------------------------- 1 | http://javarevisited.blogspot.com/2012/01/what-is-marker-interfaces-in-java-and.html 2 | 3 | Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they 4 | are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some 5 | special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation 6 | to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal 7 | or a command to Compiler or JVM. 8 | 9 | In summary marker interface in Java is used to indicate something to compiler, 10 | JVM or any other tool but Annotation is better way of doing same thing. 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Maven vs Ant: -------------------------------------------------------------------------------- 1 | http://stackoverflow.com/questions/603189/differences-between-ant-and-maven 2 | -------------------------------------------------------------------------------- /Mem Management in C: -------------------------------------------------------------------------------- 1 | http://stackoverflow.com/questions/1169858/global-memory-management-in-c-in-stack-or-heap 2 | -------------------------------------------------------------------------------- /Mutex Vs Semaphore: -------------------------------------------------------------------------------- 1 | http://www.geeksforgeeks.org/mutex-vs-semaphore/ 2 | http://koti.mbnet.fi/niclasw/MutexSemaphore.html 3 | 4 | Difference between Binary Semaphore and Mutex 5 | http://chris.dragan.name/2013/05/28/those-pesky-mutices/ 6 | -------------------------------------------------------------------------------- /Obj Oriented vs Procesdural(a.k.a Functional Programming): -------------------------------------------------------------------------------- 1 | http://www.youtube.com/watch?v=OEfSFrk_KEI 2 | Beautiful Explanation between OO vs Procedural Programming -> http://objectorientedcoldfusion.org/procedural-vs-object-oriented.html 3 | -------------------------------------------------------------------------------- /Overriding equals and hashCode methods in Java: -------------------------------------------------------------------------------- 1 | 10 minute Video for understanding this -> https://www.youtube.com/watch?v=T8UHuOVnKDM 2 | http://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.html 3 | Default Implementation of hashCode and equals: http://stackoverflow.com/questions/4178997/how-default-equals-and-hashcode-will-work-for-my-classes 4 | -------------------------------------------------------------------------------- /Polymorphism OOP Feature Explained: -------------------------------------------------------------------------------- 1 | Polymorphism depends or is executed by method overloading and method overriding. The below video explains these in 2 | the best way possible. 3 | 4 | 5 | https://www.youtube.com/watch?v=Qt_XFk6PR_M 6 | 7 | Also one more thing to note: 8 | Dynamic versus Static Polymorphism 9 | 10 | Polymorphism implemented via inheritance is bounded and dynamic: 11 | 12 | - Bounded means that the interfaces of the types participating in the polymorphic behavior are predetermined by the design of the common base class (other terms for this concept are invasive or intrusive). 13 | 14 | - Dynamic means that the binding of the interfaces is done at run time (dynamically). 15 | 16 | Polymorphism implemented via templates is unbounded and static: 17 | 18 | - Unbounded means that the interfaces of the types participating in the polymorphic behavior are not predetermined (other terms for this concept are noninvasive or nonintrusive). 19 | 20 | - Static means that the binding of the interfaces is done at compile time (statically). 21 | 22 | Source -> http://codeidol.com/community/cpp/dynamic-versus-static-polymorphism/21762/ 23 | -------------------------------------------------------------------------------- /Power of XOR in Programming: -------------------------------------------------------------------------------- 1 | Power of XOR in Programming: http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html 2 | 3 | PLEASE READ THE CONTENT IN THE ABOVE LINK BEFORE SOLVING THE BELOW MENTIONED QUESTIONS: 4 | 5 | ALWAYS REMEMBER NUMBERS ARE STORED IN REGISTERS IN PROGRAMMING 6 | 7 | XOR Properties: (Source: http://en.wikipedia.org/wiki/Exclusive_or) 8 | I. Commutative: YES (i.e. a XOR b XOR c = b XOR a XOR c = c XOR a XOR b and all possible combinations are true for 9 | any number of operands) 10 | PRACTICAL APPLICATION: Because of this property, we could solve the "find missing number" problem mentioned below in point(3). 11 | II. Associative: YES (i.e. a XOR (b XOR c) = (a XOR b) XOR c 12 | 13 | 1. Swap two numbers without using temp variable: 14 | http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/ 15 | 16 | 2. Detect if two numbers have different signs 17 | http://www.geeksforgeeks.org/detect-if-two-integers-have-opposite-signs/ 18 | 19 | 3. Find a SINGLE MISSING NUMBER in an array where array elements are SEQUENTIAL STARTING FROM 1 to n 20 | (PLEASE note, only applicable for SINGLE missing number in an array where array elements are SEQUENTIAL STARTING FROM 1 to n) 21 | http://www.geeksforgeeks.org/find-the-missing-number/ 22 | My Implementation: https://github.com/nkatre/Opearations-Variants-in-an-array/blob/master/Find%20Single%20Missing%20Number 23 | 24 | 4. Compute absolute value of integer 25 | http://www.geeksforgeeks.org/compute-the-integer-absolute-value-abs-without-branching/ 26 | BEFORE YOU GO AHEAD WITH THE ABOVE PROBLEM, PLEASE UNDERSTAND THE FOLLOWING: 27 | a. https://github.com/nkatre/Learning-Java/blob/master/Left%20Right%20Shift%20in%20Java 28 | b. How are positive numbers, negative numbers and characters represented in computer ? 29 | Ans. http://www.tldp.org/HOWTO/Unix-and-Internet-Fundamentals-HOWTO/core-formats.html 30 | https://www.youtube.com/watch?v=HhtecBhM_oA 31 | c. How are negative numbers represented in computer ? (Ans. 2's complement) 32 | Ans. https://www.rit.edu/~w-asc/documents/services/resources/handouts/DM3%20Two's%20Complement.pdf 33 | d. Why are negative numbers represented as 2's complment in computer ? 34 | Ans. VERY NICELY EXPLAINED HERE: 35 | http://stackoverflow.com/questions/1125304/why-is-twos-complement-used-to-represent-negative-numbers 36 | 37 | 5. Given an array in which all numbers except two are repeated once. (i.e. we have 2n+2 numbers and n numbers 38 | are occurring twice and remaining two have occurred once). Find those two numbers in the most efficient way. 39 | Source: http://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/ 40 | Solution: https://github.com/nkatre/Opearations-Variants-in-an-array/blob/master/Find2NonRepeatingNumbers 41 | OR 42 | The above question can also be given for String, where we need to find any two characters which are non-repeating in the String. 43 | Solution: https://github.com/nkatre/Opearations-Variants-in-an-array/blob/master/Find2NonRepeatingCharacters 44 | 45 | 6. Given an array in which all numbers except 1 is repeated once. (i.e. we have 2n+1 numbers and n numbers 46 | are occurring twice and remaining one number have occurred once). Find the non-repeating number in the most efficient way. 47 | OR 48 | Given an array in which all characters except 1 is repeated once. (i.e. we have 2n+1 characters and n characters 49 | are occurring twice and remaining one character have occurred once). Find the non-repeating character in the most efficient way. 50 | Solution: https://github.com/nkatre/Opearations-Variants-in-an-array/blob/master/Find1NonRepeatingNumberORChracter 51 | -------------------------------------------------------------------------------- /Primitive data type conversions in Java: -------------------------------------------------------------------------------- 1 | Please read the following link: 2 | 3 | 4 | http://www.myhowto.org/java/60-understanding-the-primitive-numeric-type-conversions-in-java/ 5 | -------------------------------------------------------------------------------- /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 | 56 | 57 | 58 | ANOTHER IMP CONCEPT IN JAVA: When is "return null;" valid ? 59 | Answer: 60 | 1. Valid: "return null;" is valid only for complex datatypes and complex datastructures such as Wrapper Classes, 61 | Object, List, Arrays etc. 62 | 2. Invalid: "return null;" is invalid for Primitive datatypes such as int,double,char. 63 | 64 | The following program clearly displays 2 things. 65 | 1. 'return null' is invalid for primitive datatypes. 66 | 2. 'string' does not exist. But 'String' wrapper class exist. This means that 'string' is not primitive datatype in Java. 67 | 68 | 69 | 70 | package forTesting; 71 | 72 | import java.util.List; 73 | 74 | public class CheckingNullForAllReturnTypes { 75 | public static void main(String[] args) { 76 | System.out.println(returnList()); 77 | System.out.println(returnDouble()); 78 | System.out.println(returndoubleArray()); 79 | System.out.println(returnDoubleArray()); 80 | System.out.println(returnObject()); 81 | System.out.println(returnString()); 82 | System.out.println(returndouble()); // VERY IMP: CANNOT RETURN NULL for Primitive Datatypes 83 | } 84 | 85 | public static List returnList(){ // CAN RETURN NULL for return type of complex datatype 86 | return null; 87 | } 88 | public static Double returnDouble(){ // CAN RETURN NULL for return type of Wrapper Classes 89 | return null; 90 | } 91 | public static double[] returndoubleArray(){ // CAN RETURN NULL for complex DS such as array of primitive datatype 92 | return null; 93 | } 94 | public static Double[] returnDoubleArray(){ // CAN RETURN NULL for complex DS such as array of Wrapper datatype 95 | return null; 96 | } 97 | public static Object returnObject(){ 98 | return null; // CAN RETURN NULL for return type of complex datatype such as Object 99 | } 100 | public static String returnString(){ 101 | return null; // CAN RETURN NULL for complex DS such as String, since there is no such thing called 'string' 102 | // The primitive datatype of String is 'char' and NOT 'string' 103 | } 104 | 105 | public static double returndouble(){ 106 | return null; // CANNOT RETURN NULL for Primitive Datatype 107 | } 108 | /*ANOTHER IMPORTANT THING: 109 | * public static string returnstring(){ // Throws ERROR, since there is no such thing called as 'string' 110 | // since 'string' is not Primitive datatype. 'String' exists which is Wrapper class 111 | // and not 'string'. The primitive type of 'String' can be said to be 'char'. 112 | // Also the primitive type of 'Character' wrapper class is also 'char' 113 | return null; 114 | }*/ 115 | } 116 | 117 | /* 118 | * 119 | Output: 120 | null 121 | null 122 | null 123 | null 124 | null 125 | null 126 | Exception in thread "main" java.lang.Error: Unresolved compilation problem: 127 | Type mismatch: cannot convert from null to double 128 | 129 | at forTesting.CheckingNullForAllReturnTypes.returndouble(CheckingNullForAllReturnTypes.java:36) 130 | at forTesting.CheckingNullForAllReturnTypes.main(CheckingNullForAllReturnTypes.java:13) 131 | */ 132 | 133 | 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /Questions about Testing: -------------------------------------------------------------------------------- 1 | Also have a look at this link: https://github.com/nkatre/IMP-Interview-Questions/blob/master/Testing 2 | 3 | How dou you do testing? 4 | 5 | Ans Talk about Unit testing 6 | 7 | In Java we have JUnit for unit testing (using assert to check the code). 8 | Learn more about Unit testing from the following code of Wikipedia. 9 | http://en.wikipedia.org/wiki/Unit_testing 10 | 11 | 12 | In testing we touch upon the following: 13 | Black box(checks the behaviour of the code) and White box testing(checks the actual code) 14 | 15 | Check whether the application written is: 16 | 1) Compatible with all enviornments on which it is going to run 17 | 2) If its a web application it should be able to run on multiple browsers(Using JQuery we can achieve this) 18 | 3) Check which resources it will require to function properly(for example: Main memory, hard disk space and 19 | CPU specifications) 20 | 4) If its a web application, check its behaviour in flickering internet connection(throw appropriate 21 | messages to the User that the internet connection is unstable so that the user is aware of the exact problem) 22 | 23 | 24 | Watch the following videos(23 videos) of Software Testing. ALL ARE 2-3 MINUTE VIDEOS: 25 | https://www.youtube.com/playlist?list=PLDC2A0C8D2EC934C7 26 | 27 | Specifically watch carefully, Unit Testing video 28 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | IMP-Interview-Questions 2 | ======================= 3 | 4 | The following are the IMP interview questions 5 | -------------------------------------------------------------------------------- /Recursion vs Iteration: -------------------------------------------------------------------------------- 1 | What does recursion do ? And if given a choice between recursion and iteration, why should one choose iteration over recursion ? 2 | Ans: http://stackoverflow.com/questions/3021/what-is-recursion-and-when-should-i-use-it 3 | Recursion is a method of solving problems based on the divide and conquer mentality. 4 | The basic idea is that you take the original problem and divide it into smaller (more easily solved) instances of itself, 5 | solve those smaller instances (usually by using the same algorithm again) and then reassemble them into the final solution. 6 | The canonical example is a routine to generate the Factorial of n. 7 | The Factorial of n is calculated by multiplying all of the numbers between 1 and n. An iterative solution in C# looks like this: 8 | public int Fact(int n) 9 | { 10 | int fact = 1; 11 | for( int i = 2; i <= n; i++) 12 | { 13 | fact = fact * i; 14 | } 15 | return fact; 16 | } 17 | There's nothing surprising about the iterative solution and it should make sense to anyone familiar with C#. 18 | 19 | The recursive solution is found by recognising that the nth Factorial is n * Fact(n-1). 20 | Or to put it another way, if you know what a particular Factorial number is you can calculate the next one. 21 | Here is the recursive solution in C#: 22 | public int FactRec(int n) 23 | { 24 | if( n < 2 ) 25 | { 26 | return 1; 27 | } 28 | return n * FactRec( n - 1 ); 29 | } 30 | The first part of this function is known as a Base Case (or sometimes Guard Clause) and is what prevents the 31 | algorithm from running forever. It just returns the value 1 whenever the function is called with a value of 1 or less. 32 | The second part is more interesting and is known as the Recursive Step. Here we call the same method with a slightly 33 | modified parameter (we decrement it by 1) and then multiply the result with our copy of n. 34 | 35 | When first encountered this can be kind of confusing so it's instructive to examine how it works when run. 36 | Imagine that we call FactRec(5). We enter the routine, are not picked up by the base case and so we end up like this: 37 | 38 | // In FactRec(5) 39 | return 5 * FactRec( 5 - 1 ); 40 | // which is 41 | return 5 * FactRec(4); 42 | If we re-enter the method with the parameter 4 we are again not stopped by the guard clause and so we end up at: 43 | 44 | // In FactRec(4) 45 | return 4 * FactRec(3); 46 | If we substitute this return value into the return value above we get 47 | 48 | // In FactRec(5) 49 | return 5 * (4 * FactRec(3)); 50 | This should give you a clue as to how the final solution is arrived at so we'll fast track and show each step 51 | on the way down: 52 | 53 | return 5 * (4 * FactRec(3)); 54 | return 5 * (4 * (3 * FactRec(2))); 55 | return 5 * (4 * (3 * (2 * FactRec(1)))); 56 | return 5 * (4 * (3 * (2 * (1)))); 57 | That final substitution happens when the base case is triggered. At this point we have a simple algrebraic 58 | formula to solve which equates directly to the definition of Factorials in the first place. 59 | 60 | It's instructive to note that every call into the method results in either a base case being triggered or a call 61 | to the same method where the parameters are closer to a base case (often called a recursive call). 62 | If this is not the case then the method will run forever. 63 | -------------------------------------------------------------------------------- /Regex Learning: -------------------------------------------------------------------------------- 1 | Learn Regex from the following sites: 2 | http://www.vogella.com/tutorials/JavaRegularExpressions/article.html 3 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Stack vs Heap memory in Java: -------------------------------------------------------------------------------- 1 | http://javarevisited.blogspot.com/2013/01/difference-between-stack-and-heap-java.html 2 | 3 | 4 | IMP Q: Does each thread in java uses seperate stack? 5 | Ans: In Java every thread maintains its own separate stack. It is called Runtime Stack but 6 | they share the same memory. 7 | 8 | 9 | 10 | Difference between stack and heap memory is common programming question asked by beginners learning 11 | Java or any other programming language. Stack and heap memory are two terms programmers starts hearing 12 | once they started programming but without any clear and definite explanation. Lack of knowledge on what 13 | is heap in Java and what is stack memory in Java, results in misconcepts related to stack and heap. 14 | To add to this confusion, stack is also a data structure which is used to store elements in LIFO 15 | (Last In First out) order and available in Java API as java.util.Stack. In general both stack and heap 16 | are part of MAIN MEMORY, a program is allocated and used for different purposes. Java program runs inside JVM 17 | which is launched as a process by "java" command. Java also uses both stack and heap memory for 18 | different needs. In our last article 10 points on Java heap space I have touched base on Java heap 19 | space and in this article we will see difference between stack and heap memory in Java. 20 | 21 | Difference between Stack vs Heap in Java: 22 | 23 | Difference between heap and statck in Java - Interview Question 24 | Here are few differences between stack and heap memory in Java: 25 | 26 | 1) Main difference between heap and stack is that stack memory is used to store local variables 27 | and function call, while heap memory is used to store objects in Java. No matter, where object is 28 | created in code e.g. as member variable, local variable of any method either main method or different method 29 | or objects creates as a class variable, they are always created inside heap space in Java. 30 | 31 | 2) Each Thread in Java has there own stack which can be specified using -Xss JVM parameter, similarly 32 | you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting 33 | size of heap and -Xmx is maximum size of java heap. to learn more about JVM options 34 | see my post 10 JVM option Java programmer should know. 35 | 36 | 3) If there is no memory left in stack for storing function call or local variable, 37 | JVM will throw java.lang.StackOverFlowError, while if there is no more heap memory for creating object, 38 | JVM will throw java.lang.OutOfMemoryError: Java Heap Space. Read more about how to deal 39 | with java.lang.OutOfMemoryError in my post 2 ways to solve OutOfMemoryError in Java. 40 | 41 | 4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. 42 | Another difference between stack and heap is that size of stack memory is VERY LESSER(VERY LESS) than size of 43 | heap memory in Java. 44 | 45 | 5) Variables stored in stacks are only visible to the owner Thread, while objects created in 46 | heap are visible to all thread. In other words stack memory is kind of private memory of Java Threads, 47 | while heap memory is shared among all threads. 48 | 49 | 50 | 51 | 52 | VERY IMPORTANT: 53 | Difference between heap and string pool memory: (Source: http://www.coderanch.com/t/390447/java/java/Difference-Heap-Pool) 54 | Video of 6 minutes to explain this: https://www.youtube.com/watch?v=WTOiuY7cNTo 55 | 56 | Heap: 57 | The heap is just the area of RAM that is allotted to the JVM by the operating system for runtime activity. 58 | As such it is the place that objects get created during a JVM session. 59 | 60 | Pool: 61 | Pool is a separate portion WITHIN the heap memory. This separate portion of heap memory is called "POOL" 62 | The 'pool' is just a special area of the heap memory that Java sets up to store all String literals. 63 | Imagine a box with a partition wall; on one side is the 'pool' on the other side the 'heap'. 64 | Everytime you use a string literal, it gets stored on the pool side, regular objects get stored on 65 | the heap side. 66 | 67 | -------------------------------------------------------------------------------- /Static vs Dynamic Class Loading in Java: -------------------------------------------------------------------------------- 1 | https://www.youtube.com/watch?v=GeJAxq5Qsho 2 | https://www.youtube.com/watch?v=lhv7PpjbQWs 3 | -------------------------------------------------------------------------------- /Synchronization concept in Java: -------------------------------------------------------------------------------- 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 | 75 | -------------------------------------------------------------------------------- /System class Java: -------------------------------------------------------------------------------- 1 | System class belongs to the lang package. All the methods of the system class are static. Hence all the methods 2 | of the System class can be called in any program using 3 | "System.exit(1)" OR "System.gc()" format. 4 | 5 | Some of the important methods are menthioned in the System class. Please go through the Java docs for their 6 | information 7 | 8 | System Class Java Docs -> http://docs.oracle.com/javase/7/docs/api/java/lang/System.html 9 | -------------------------------------------------------------------------------- /TCP Vs UDP: -------------------------------------------------------------------------------- 1 | http://www.diffen.com/difference/TCP_vs_UDP 2 | https://www.youtube.com/watch?v=Vdc8TCESIg8 3 | -------------------------------------------------------------------------------- /Testing: -------------------------------------------------------------------------------- 1 | Question 1: Your test randomly changes the comparison operators in your conditionals. This is which kind of testing? 2 | Mutation test 3 | Glass-box test 4 | Black-box test 5 | Fuzz test 6 | 7 | Source: http://www.careercup.com/question?id=14921914 8 | 9 | Mutation test: 10 | Fault-based Testing: directed towards “typical” faults that could occur in a program 11 | • Basic idea: – Take a program and test data generated for that program 12 | – Create a number of similar programs (mutants), each differing from the original in one small way, i.e., each 13 | possessing a fault • e.g., replace addition operator by multiplication operator 14 | – The original test data are then run through the mutants 15 | – If test data detect all differences in mutants, then the mutants are said to bedead, and the test set isadequate 16 | 17 | http://www.uio.no/studier/emner/matnat/ifi/INF4290/v10/undervisningsmateriale/INF4290-Mutest.pdf 18 | http://www.techopedia.com/definition/20905/mutation-testing 19 | 20 | Glass-box test(Also called clear box testing, open box testing): http://www.tutorialspoint.com/software_testing_dictionary/glass_box_testing.htm 21 | Black-box test: http://stackoverflow.com/questions/402161/black-box-vs-white-box-testing 22 | Fuzz test: http://en.wikipedia.org/wiki/Fuzz_testing 23 | 24 | Question 2: Which of the following guarantees that you have exhaustively unit-tested a piece of code? 25 | a. 100% C0 (statement) coverage 26 | b. 100% C1 (branch) coverage 27 | c. 100% C2 (path) coverage 28 | d. None of the above 29 | Question Source: http://www.careercup.com/question?id=14946838 30 | 31 | Answer: None of the above. Testing is hard. 32 | You could have tried every path, but not with every set of input values. 33 | -------------------------------------------------------------------------------- /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 | 5 | 6 | Process: 7 | 8 | An executing instance of a program is called a process. 9 | Some operating systems use the term ‘task‘ to refer to a program that is being executed. 10 | A process is always stored in the main memory also termed as the primary memory or random access memory. 11 | Therefore, a process is termed as an active entity. It disappears if the machine is rebooted. 12 | Several process may be associated with a same program. 13 | On a multiprocessor system, multiple processes can be executed in parallel. 14 | On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency. 15 | Example: Executing multiple instances of the ‘Calculator’ program. Each of the instances are termed as a process. 16 | Thread: 17 | 18 | A thread is a subset of the process. 19 | It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel (See kquest.co.cc/2010/03/operating-system for more info on the term ‘kernel’). 20 | Usually, a process has only one thread of control – one set of machine instructions executing at a time. 21 | A process may also be made up of multiple threads of execution that execute instructions concurrently. 22 | Multiple threads of control can exploit the true parallelism possible on multiprocessor systems. 23 | On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time. 24 | All the threads running within a process share the same address space, file descriptor, stack and other process related attributes. 25 | Since the threads of a process share the same memory, synchronizing the access to the shared data withing the process gains unprecedented importance. 26 | -------------------------------------------------------------------------------- /Throwable: -------------------------------------------------------------------------------- 1 | Question: What is the super class for Exception(which is a class) and Error(which is a class)? 2 | Ans: The super class or base class for Exception and Error is Throwable(which is a class). 3 | -------------------------------------------------------------------------------- /Time Complexity of predefined methods in JAVA: -------------------------------------------------------------------------------- 1 | For updated information, please refer the repository mentioned in the link: 2 | https://github.com/nkatre/TimeComplexityOfPredefinedMethodsInJava 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() and Collections.sort() static methods 42 | *************************************************************************************************** 43 | Source: http://stackoverflow.com/questions/4254122/what-is-the-time-complexity-of-this-sort-method?rq=1 44 | Solution: The time complexity of this predefined method of Arrays class and Collections class is nlgn 45 | 46 | *************************************************************************************************** 47 | III. Time Complexity of toCharArray() and toString() methods in JAVA 48 | *************************************************************************************************** 49 | Source: http://stackoverflow.com/questions/13079261/what-is-the-runtime-of-tochararray-and-tostring-in-java 50 | Solution: 51 | As far as String.toCharArray() goes, it's O(N), where N is the number of characters in the string, 52 | because each character must be copied into the output. 53 | 54 | *************************************************************************************************** 55 | IV. Time Complexity of reverse() method of StringBuilder and StringBuffer class in JAVA 56 | *************************************************************************************************** 57 | NOTE: reverse() method is an instance method of StringBuilder class AND 58 | reverse() method is also an instance synchronized method of StringBuffer class in JAVA 59 | 60 | PLEASE NOTE THAT reverse() method is NOT PRESENT in String class of JAVA. The reason being String class 61 | in JAVA is immutable. However, for some reason substring() method is present in String class even though String 62 | is immutable in JAVA. Also StringBuilder and StringBuffer classes each have substring() method. 63 | 64 | Source: http://stackoverflow.com/questions/19814067/time-complexity-of-stringbuilder-reverse-method 65 | Solution: It is O(n). It is impossible to revert a String in less than O(n) 66 | 67 | *************************************************************************************************** 68 | V. Time Complexity of indexOf() method of String class 69 | *************************************************************************************************** 70 | Source: http://stackoverflow.com/questions/12752274/java-indexofstring-str-method-complexity 71 | The complexity of Java's implementation of indexOf is O(m*n) where n and m are the length of the search string 72 | and pattern respectively. 73 | What you can do to improve complexity is to use e.g., the Boyer-More algorithm to intelligently skip comparing 74 | logical parts of the string which cannot match the pattern. 75 | 76 | 77 | *************************************************************************************************** 78 | V. Time Complexity of class ArrayList methods time complexity 79 | *************************************************************************************************** 80 | Source: http://stackoverflow.com/questions/6540511/time-complexity-for-java-arraylist 81 | The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. 82 | The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. O(n) because, 83 | once the array is full(i.e. ArrayList is full), the array is copied to different location which has high memory, 84 | this copying of all the elements due to insufficient space causes (n) operation. Hence on an average, 85 | the time complexity is O(n), but if this case is avoided then the time complexity is O(1), similar to array addition 86 | operation. 87 | All of the other operations run in linear time (roughly speaking). 88 | The constant factor is low compared to that for the LinkedList implementation. 89 | 90 | *************************************************************************************************** 91 | V. Time Complexity for Lists, Maps and Set Classes. (more specifically, ArrayList, HashSet and HashMap) methods 92 | *************************************************************************************************** 93 | Source: http://www.acnenomor.com/2331736p1/time-complexity-of-hashmap-methods 94 | remove: O(1) [method of List, Set, Map classes] 95 | size: O(1) [method of List, Set, Map classes] 96 | values: O(n) (on traversal through iterator) [method of Map class] 97 | contains: O(1) [method of HashSet] {uses hash function} 98 | contains: O(n) [method of ArrayList] {to understand this, please understand first how ArrayList works internally. 99 | ArrayList does not contain any hash method. Its actually an array as its name suggests} 100 | How does ArrayList work internally ? 101 | Ans: http://stackoverflow.com/questions/3467965/how-does-arraylist-work 102 | containsKey: O(1) [method of HashMap] 103 | {Source: http://stackoverflow.com/questions/8923251/what-is-the-time-complexity-of-hashmap-containskey-in-java} 104 | containsValue: O(n) [method of HashMap] {since hash function only exists for key and not value, 105 | hence it has to iterate through all elements of the HashMap to find the value. Hence O(n) operation 106 | Source: http://stackoverflow.com/questions/16757359/what-is-the-time-complexity-of-hashmap-containsvalue-in-java} 107 | 108 | VERY VERY HELPFUL TABLE OF TIME COMPLEXITY ANALYSIS: 109 | http://www.c-sharpcorner.com/UploadFile/0f68f2/comparative-analysis-of-list-hashset-and-sortedset/ 110 | 111 | I think that remove() will be the same complexity as get(), O(1), assuming we don't have a giant HashMap with equal 112 | hashCodes, etc etc... 113 | For size() i'd also assume O(1), since a HashSet, which also has no order, has a size() method with complexity O(1). 114 | The one i have no idea of is values() - I'm not sure whether this method will just somehow "copy" the HashMap, 115 | giving a time complexity of O(1), or if it will have to iterate over the HashMap, making the complexity equal 116 | to the amount of elements stored in the HashMap. 117 | 118 | *************************************************************************************************** 119 | VI. Time Complexity for different Collection Classes 120 | *************************************************************************************************** 121 | VERY VERY IMP Source: http://www.javaexperience.com/time-complexity-of-collection-classes/ 122 | 123 | Java ArrayList time complexity : 124 | 125 | Read/Search any element O(n). If you know the index then the complexity is O(1) 126 | Update : O(n) 127 | Delete at beginning: O(n) 128 | Delete in middle: O(n) 129 | Delete at end: O(n) 130 | Add at beginning: O(n) 131 | Add in middle: O(n) 132 | Add at end: O(n) 133 | 134 | Linked List time complexity : It has elements linked in one direction so as to provide ordered iteration 135 | of elements. 136 | 137 | Read/Search any element O(n) 138 | Update : O(n) 139 | Delete at beginning: O(1) 140 | Delete in middle: O(n) 141 | Delete at end: O(n) 142 | Add at beginning: O(1) 143 | Add in middle: O(n) 144 | Add at end: O(n) 145 | 146 | HashMap time complexity : The elements are placed randomly as per the hashcode. Here the assumption is 147 | that a good implementation of hashcode has been provided. 148 | 149 | Read/Search any element O(1) 150 | Update : O(1) 151 | Delete : O(1) 152 | Add : O(1) 153 | 154 | LinkedHashMap time complexity : The elements are placed randomly as with HashMap but are linked together 155 | to provide ordered iteration of elements. 156 | 157 | Read/Search any element O(1) 158 | Update : O(1) 159 | Delete : O(1) 160 | Add at beginning: O(1) 161 | Add in middle: O(n) 162 | Add at end: O(n) 163 | 164 | HashSet time complexity : The elements are distributed randomly in memory using their hashcode. Here also 165 | the assumption is that good hashcode which generated unique hashcode for different objects has been provided. 166 | 167 | Read/Search any element O(1) 168 | Update : O(1) 169 | Delete : O(1) 170 | Add : O(1) 171 | 172 | LinkedHashSet time complexity : It is same as HashSet with the addition of links between the elements of the Set. 173 | 174 | Read/Search any element O(1) 175 | Update : O(1) 176 | Delete : O(1) 177 | Add at beginning: O(1) 178 | Add in middle: O(n) 179 | Add at end: O(n) 180 | 181 | TreeMap time complexity : Provides natural sorting of elements. Uses equals, compare and compareTo methods 182 | to determine the sorting order. 183 | 184 | Read/Search any element O(log n) 185 | Update : O(log n) 186 | Delete : O(log n) 187 | Add : O(log n) 188 | 189 | TreeSet time complexity : Internally used an instances of TreeMap with the elements as key and a dummy 190 | value for all entries in the TreeMap. 191 | 192 | Read/Search any element O(log n) 193 | Update : O(log n) 194 | Delete : O(log n) 195 | Add : O(log n) 196 | 197 | *************************************************************************************************** 198 | VII. Time Complexity of charAt() and deleteCharAt() 199 | *************************************************************************************************** 200 | Question: 201 | I've been wondering about the implementation of charAt function for String/StringBuilder/StringBuffer 202 | in java what is the coomplexity of that ? also what about the deleteCharAt() in StringBuffer/StringBuilder ? 203 | Source: http://stackoverflow.com/questions/6461402/java-charat-and-deletecharat-performance 204 | Solution: 205 | The charAt method is O(1). 206 | The deleteCharAt method on StringBuilder and StringBuffer is O(N) on average, assuming you are deleting a 207 | random character from an N character StringBuffer / StringBuilder. (It has to move, on average, 208 | half of the remaining characters to fill up the "hole" left by the deleted character. 209 | There is no amortization over multiple operations; see below.) However, if you delete the last character, 210 | the cost will be O(1). 211 | There is no deleteCharAt method for String. 212 | For String, StringBuffer, and StringBuilder, charAt() is a constant-time operation. 213 | For StringBuffer and StringBuilder, deleteCharAt() is a linear-time operation. 214 | StringBuffer and StringBuilder have very similar performance characteristics. 215 | The primary difference is that the former is synchronized (so is thread-safe) while the latter is not. 216 | -------------------------------------------------------------------------------- /VERY VERY IMP THING IN PROGRAMMING: -------------------------------------------------------------------------------- 1 | Question: https://www.hackerrank.com/challenges/halloween-party 2 | Ans: 3 | When we store the answer in different datatype, always remember to typecast it 4 | 5 | 6 | WRONG ANS: 7 | 8 | import java.io.*; 9 | import java.util.*; 10 | import java.text.*; 11 | import java.math.*; 12 | import java.util.regex.*; 13 | 14 | public class Solution { 15 | 16 | public static void main(String[] args) { 17 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 18 | Scanner in = new Scanner(System.in); 19 | int n = in.nextInt(); 20 | in.nextLine(); 21 | for(int i=0;i 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 | -------------------------------------------------------------------------------- /Which is faster?: -------------------------------------------------------------------------------- 1 | Question: Among StringBuilder and StringBuffer, which is faster and why? 2 | Ans: StringBuilder, because it is not synchronized hence no synchronization overhead and hence it is faster 3 | than StringBuffer.StringBuffer is thread-safe and hence contains synchronized methods and hence the overhead 4 | and therefore slower in execution than StringBuilder. 5 | 6 | Question: Which is faster, ArrayList or Vector and why? 7 | Ans: ArrayList, because it is not synchronized hence no synchronization overhead and hence it is faster 8 | than Vector. Vector is thread-safe and hence contains synchronized methods and hence the overhead 9 | and therefore slower in execution than ArrayList. 10 | 11 | Question: Which is faster, Hashtable/HashMap OR Vector? 12 | Ans: Hashtable/HashMap, because it is not synchronized hence no synchronization overhead and hence it is faster 13 | than Vector. Vector is thread-safe and hence contains synchronized methods and hence the overhead 14 | and therefore slower in execution than Hashtable/HashMap. 15 | 16 | Question: Are Synchronized Methods Slower In Single Threaded Applications also? 17 | Source: http://stackoverflow.com/questions/973518/are-synchronized-methods-slower-in-single-threaded-applications 18 | Ans: Yes, single-theaded Java programs that use synchronization may be slightly slower than they 19 | would be without synchronization. For early Java releases, synchronization was expensive. 20 | For any modern release, however, uncontended synchronization is pretty cheap. I wouldn't worry about this. 21 | 22 | Note that Java 6 has and Java 7 is to have good optimizations around locking: 23 | 24 | Lock coarsening 25 | Lock elision 26 | Adaptive Spin locking 27 | Biased locking 28 | For more information, see the Java SE 6 Performance White Paper. 29 | Also note that uncontended synchronization appears to be more expensive on multi-core CPUs than 30 | on single-core CPUs, perhaps due to the Java Memory Model requirements of synchronization forcing local 31 | CPU caches to be shared with other CPUs, or some other memory barrier. 32 | For example, 33 | read Do Java 6 threading optimizations actually work? - Part II. 34 | (The Part I was not as insightful as the Part II.) 35 | 36 | 37 | Question: Why are synchronized methods said to be comparitively slow to non-synchronized methods in java? 38 | Ans: 39 | 40 | Source: http://stackoverflow.com/questions/1671089/why-are-synchronize-expensive-in-java 41 | 42 | It is expensive because if you are using threads, and a number of threads have to go through a 43 | synchronized section of code, only one of them may be executed at a time. 44 | 45 | It is like a bottleneck. 46 | 47 | It is even expensive when you use a single thread, because it has to check anyway if he is allowed to run. 48 | (Related Question: Are Synchronized Methods Slower In Single Threaded Applications also? 49 | Answer: Yes, explained in the line above this line and in the previous question as well. Have a look. 50 | If you reduce the use of synchronized segments your thread won't have to stop to see if they can run 51 | ( of course, they don't have to share data ) 52 | 53 | -------------------------------------------------------------------------------- /Working of Garbage Collector in Java: -------------------------------------------------------------------------------- 1 | http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html 2 | -------------------------------------------------------------------------------- /Working of JVM, Compiler and Interpreter: -------------------------------------------------------------------------------- 1 | https://www.youtube.com/watch?v=XjNwyXx2os8 2 | -------------------------------------------------------------------------------- /Working of TreeMap & TreeSet: -------------------------------------------------------------------------------- 1 | TreeMap 2 | How does TreeMap work in Java: http://javahungry.blogspot.com/2014/06/how-treemap-works-ten-treemap-java-interview-questions.html 3 | Time Complexity of TreeMap methods in Java: http://www.javaexperience.com/time-complexity-of-collection-classes/ 4 | 5 | TreeSet 6 | How does TreeSet work in Java: http://stackoverflow.com/questions/9549991/understanding-treemaps 7 | Time Complexity of TreeSet methods in Java: http://www.javaexperience.com/time-complexity-of-collection-classes/ 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /end of character marking in char array: -------------------------------------------------------------------------------- 1 | Question: 2 | Does java have '\0' to mark the end of String similar to char array in C ? 3 | Answer Source: http://stackoverflow.com/questions/17815755/end-of-string-character-in-java 4 | Answer : No, no such character is used to mark the end of string in Java. 5 | -------------------------------------------------------------------------------- /equals and hashcode method: -------------------------------------------------------------------------------- 1 | Importance of overriding equals and hashcode method -> http://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.html 2 | How HashMap works in Java -> http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html 3 | -------------------------------------------------------------------------------- /final finally finalize: -------------------------------------------------------------------------------- 1 | final - keyword 2 | finally - block written after try{} catch{} or only try{}. finally{} should have try{} or both try{} catch{} 3 | before it. It cannot exist alone. Complier will throw Syntax Error. Hence finally{} CANNOT exist alone. 4 | finalize - method called before System.gc() to free all the resources (i.e. references to objects are made null) 5 | 6 | final: 7 | final is a keyword. The variable decleared as final should be 8 | initialized only once and cannot be changed. Java classes 9 | declared as final cannot be extended. Methods declared as final 10 | cannot be overridden. 11 | 12 | finally: 13 | finally is a block. The finally block always executes when the 14 | try block exits. This ensures that the finally block is executed 15 | even if an unexpected exception occurs. But finally is useful for 16 | more than just exception handling - it allows the programmer to 17 | avoid having cleanup code accidentally bypassed by a return, 18 | continue, or break. Putting cleanup code in a finally block is 19 | always a good practice, even when no exceptions are anticipated. 20 | 21 | finalize: 22 | finalize is a method. Before an object is garbage collected, the 23 | runtime system calls its finalize() method. You can write system 24 | resources release code in finalize() method before getting garbage 25 | collected. 26 | -------------------------------------------------------------------------------- /final keyword allowed or not allowed on abstract ?: -------------------------------------------------------------------------------- 1 | Question: Can we declare abstract method as final? 2 | Ans: No, we can not declare abstract method as final. We have to 3 | provide implementation to abstract methods in subclasses. 4 | -------------------------------------------------------------------------------- /finally block execution Importance: -------------------------------------------------------------------------------- 1 | Read the below two IMP questions about finally block execution 2 | 3 | Question: Incase, there is a return at the end of try block, will execute finally block? 4 | Ans: Yes, the finally block will be executed even after writing return statement 5 | at the end of try block. It returns after executing finally block. 6 | 7 | 8 | Question: Does system.exit() in try block executes code in finally block? 9 | try{ 10 | System.out.println("I am in try block"); 11 | System.exit(1); 12 | } catch(Exception ex){ 13 | ex.printStackTrace(); 14 | } finally { 15 | System.out.println("I am in finally block!!!"); 16 | } 17 | Ans: It will not execute finally block. The program will be terminated 18 | after System.exit() statement. 19 | -------------------------------------------------------------------------------- /hashCode and equals method: -------------------------------------------------------------------------------- 1 | http://www.youtube.com/watch?v=T8UHuOVnKDM 2 | -------------------------------------------------------------------------------- /isAnagramOfAStringPalindrome: -------------------------------------------------------------------------------- 1 | LOGIC: 2 | Store the character count in an array of length 26. Loop through all the counts, to find if the odd occurence is greater 3 | than 1. Ideally if palindrome exists in then, the total odd occurences would be 0 or 1. Find this, using your own 4 | examples. Work with your own examples. 5 | 6 | 7 | 8 | import java.io.*; 9 | import java.util.*; 10 | import java.text.*; 11 | import java.math.*; 12 | import java.util.regex.*; 13 | 14 | public class Solution { 15 | 16 | public static void main(String[] args) { 17 | Scanner myScan = new Scanner(System.in); 18 | String inputString = myScan.nextLine(); 19 | 20 | String ans=""; 21 | boolean got = checkPalindrome(inputString); 22 | if(got==true) 23 | ans="YES"; 24 | else 25 | ans="NO"; 26 | // Assign ans a value of YES or NO, depending on whether or not inputString satisfies the required condition 27 | System.out.println(ans); 28 | myScan.close(); 29 | } 30 | public static boolean checkPalindrome(String input) 31 | { 32 | int [] count = new int[26]; 33 | for( int i = 0; i < input.length(); i++ ) 34 | { 35 | char ch = input.charAt(i); 36 | count[ch-'a']++; 37 | } 38 | int oddOccur = 0; 39 | for( int cnt:count ) 40 | { 41 | if( oddOccur > 1) 42 | return false; 43 | if( cnt%2 == 1 ) 44 | oddOccur++; 45 | } 46 | return true; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /package or import statement should be first: -------------------------------------------------------------------------------- 1 | Here's an example: 2 | If there is a package statement, that is the first line of your source code. 3 | 4 | 5 | 6 | package example; 7 | 8 | class ExampleClass{ 9 | 10 | // class body goes here.... 11 | 12 | } 13 | 14 | 15 | If there is an import statement, then it should follow your package statement and all the imports should start before a class definition. 16 | 17 | 18 | package example; 19 | 20 | import java.util.Date; 21 | import java.util.Collections; 22 | 23 | class ExampleClass{ 24 | 25 | // class body goes here.... 26 | 27 | } 28 | 29 | If there is an import statement and no package statement, then the import statement would be your first statement of the source code. 30 | 31 | 32 | 33 | import java.util.Date; 34 | 35 | class ExampleClass{ 36 | 37 | // class body goes here.... 38 | 39 | } 40 | 41 | If there is no package statement and there are no import statements, then obviously the class declaration would be the first line of your source code. 42 | 43 | 44 | class ExampleClass{ 45 | 46 | // class body goes here.... 47 | 48 | } 49 | 50 | 51 | Hope this makes it clear! 52 | -------------------------------------------------------------------------------- /private classes in Java: -------------------------------------------------------------------------------- 1 | Question: Can a class in java be private? 2 | Ans: We can not declare top level class(parent class) as private. Java allows 3 | only public and default modifier for top level classes(parent classes) in java. 4 | Inner classes can be private. 5 | -------------------------------------------------------------------------------- /shallow vs deep cloning of objects in Java: -------------------------------------------------------------------------------- 1 | http://www.java2novice.com/java_interview_questions/shallow-deep-cloning/ 2 | https://www.youtube.com/watch?v=BZmQ7KmoD_4 3 | https://www.youtube.com/watch?v=khOfttSm1rk 4 | -------------------------------------------------------------------------------- /sleep Vs wait: -------------------------------------------------------------------------------- 1 | sleep(): 2 | It is a static method on Thread class. It makes the current thread into the 3 | "Not Runnable" state for specified amount of time. During this time, the thread 4 | keeps the lock (monitors) it has acquired. 5 | 6 | wait(): 7 | It is a non-static method on Object class. It makes the current thread into the "Not Runnable" 8 | state. Wait is called on a object, not a thread. Before calling wait() method, the 9 | object should be synchronized, means the object should be inside synchronized block. 10 | The call to wait() releases the acquired lock. 11 | 12 | For details please see the following: 13 | Thread Java Docs -> http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html 14 | Object Java Docs -> http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html 15 | -------------------------------------------------------------------------------- /static members allowed or not allowed in non-static methods: -------------------------------------------------------------------------------- 1 | Question: Can non-static methods (Local classes) have static members? 2 | Ans: No, non-static member classes cannot have static members. Because, 3 | an instance of a non-static member class or local class must be 4 | created in the context of an instance of the enclosing class. You 5 | can declare constants, means static final variables. 6 | 7 | Example: 8 | class Demo { 9 | public void hello(){ 10 | static int n=10; 11 | System.out.println(n); 12 | 13 | } 14 | } 15 | class AbstractDemo{ 16 | public static void main(String[] args) { 17 | Demo d=new Demo(); 18 | d.hello(); 19 | } 20 | } 21 | 22 | Output: Compilation Error: Non static method hello() cannot have static member n=10 23 | -------------------------------------------------------------------------------- /static syncronization vs non-static synchronization: -------------------------------------------------------------------------------- 1 | Question: What is the difference between static synchronized and synchronized methods? 2 | Ans: Static synchronized methods synchronize on the class object. If one thread is executing a 3 | static synchronized method, all other threads trying to execute any static synchronized methods 4 | will be blocked. 5 | 6 | Non-static synchronized methods synchronize on this ie the instance of the class. If one 7 | thread is executing a synchronized method, all other threads trying to execute any synchronized 8 | methods will be blocked. 9 | 10 | 11 | 12 | BEST EXPLANATION: 13 | 14 | 15 | Question: 16 | What are the differences between using a static lock object (code A) 17 | and a non-static lock object (code B) for a synchronized block? 18 | How does it differ in practical applications? 19 | What are the pitfalls one would have that the other wouldn't? 20 | What are the criteria to determine which one to use? 21 | 22 | 23 | 24 | 25 | Code A 26 | 27 | public class MyClass1 { 28 | private static final Object lock = new Object(); 29 | public MyClass1() { 30 | //unsync 31 | synchronized(lock) { 32 | //sync 33 | } 34 | //unsync 35 | } 36 | } 37 | 38 | 39 | 40 | Code B 41 | 42 | public class MyClass2 { 43 | private final Object lock = new Object(); 44 | public MyClass2() { 45 | //unsync 46 | synchronized(lock) { 47 | //sync 48 | } 49 | //unsync 50 | } 51 | } 52 | Note 53 | 54 | The above code shows constructors, but you could talk about how the behavior is different 55 | in a static method and a non-static method too. Also, would it be advantageous to use a static 56 | lock when the synchronized block is modifying a static member variable? 57 | 58 | I already looked at answers in this question, but it's not clear enough what 59 | the different usage scenarios are. 60 | 61 | 62 | ANS: 63 | The difference is simple: if the locked-on object is in a static field, 64 | then all instances of MyClass* will share that lock 65 | (i.e. no two objects will be able to lock on that object at the same time). 66 | 67 | If the field is non-static, then each instance will have its own lock, 68 | so only calls of the method on the same object will lock each other. 69 | 70 | When you use a static lock object: 71 | 72 | thread 1 calls o1.foo() 73 | thread 2 calls o1.foo(), will have to wait for thread 1 to finish 74 | thread 3 calls o2.foo(), will also have to wait for thread 1 (and probably 2) to finish 75 | 76 | 77 | When you use a non-static lock object: 78 | 79 | thread 1 calls o1.foo() 80 | thread 2 calls o1.foo(), will have to wait for thread 1 to finish 81 | thread 3 calls o2.foo(), it can just continue, not minding thread 1 and 2 82 | 83 | 84 | 85 | Which one of those you'll need depends on what kind of data you try to protect with your 86 | synchronized block. 87 | 88 | As a rule of thumb, you want the lock-object to have the same static-ness than the 89 | operated-on value. So if you manipulate non-static values only, you'll want a 90 | non-static lock object. If you manipulate static values only, you'll want a static lock object. 91 | 92 | When you manipulate static and non-static values, then it'll become complicated. 93 | The easy way would be to just use a static lock object, but that might increase 94 | the size of the synchronized-block more than absolutely necessary and might need to 95 | more lock contention than desired. In those cases you might need a combination of 96 | static and non-static lock objects. 97 | 98 | In your particular case you use the lock in the constructor, which will only ever be 99 | executed once per instance, so a non-static lock-object doesn't make any sense here. 100 | 101 | 102 | 103 | 104 | 105 | 106 | ADDED EXPLANATION: 107 | 108 | The lock objects are different on the static method and non-static method. 109 | The static method uses the Class object as the lock (lock obj: MyClass.class), while 110 | the non-static method uses the instance object as the lock to which the invocation of the 111 | method at that time is bound (lock obj: this). 112 | 113 | For those who are not familiar static synchronized method locked on class object e.g. 114 | for string class its String.class while instance synchronized method locks on current instance 115 | of Object denoted by “this” keyword in Java. Since both of these object are different they have 116 | different lock so while one thread is executing static synchronized method , other thread in java 117 | doesn’t need to wait for that thread to return instead it will acquire separate lock denoted 118 | byte .class literal and enter into static synchronized method. This is even a popular multi-threading 119 | interview questions where interviewer asked on which lock a particular method gets locked, some 120 | time also appear in Java test papers. 121 | Source: http://javarevisited.blogspot.com/2012/03/mixing-static-and-non-static.html 122 | 123 | Source: http://stackoverflow.com/questions/1536064/what-is-the-difference-between-synchronized-and-static-synchronized 124 | 125 | The only difference that synchronized makes is that before the VM starts running that method, 126 | it has to acquire a monitor. For an instance method, the lock acquired is the one associated 127 | with the object you're calling the method on. For a static method, the lock acquired is associated 128 | with the type itself - so no other threads will be able to call any other synchronized static methods 129 | at the same time. 130 | 131 | In other words, this: 132 | 133 | class Test 134 | { 135 | static synchronized void Foo() { ... } 136 | 137 | synchronized void Bar() { ... } 138 | } 139 | is roughly equivalent to: 140 | 141 | class Test 142 | { 143 | static void Foo() 144 | { 145 | synchronized(Test.class) 146 | { 147 | ... 148 | } 149 | } 150 | 151 | void Bar() 152 | { 153 | synchronized(this) 154 | { 155 | ... 156 | } 157 | } 158 | } 159 | Generally I tend not to use synchronized methods at all - I prefer to explicitly synchronize on a private lock reference: 160 | 161 | private final Object lock = new Object(); 162 | 163 | ... 164 | 165 | void Bar() 166 | { 167 | synchronized(lock) 168 | { 169 | ... 170 | } 171 | } 172 | You haven't provided nearly enough information to determine whether your method should be a static or instance method, or whether it should be synchronized at all. Multithreading is a complex issue - I strongly suggest that you read up on it (through books, tutorials etc). 173 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /switch case: -------------------------------------------------------------------------------- 1 | Find out below switch statement output. 2 | 3 | 4 | public static void main(String a[]){ 5 | int price = 6; 6 | switch (price) { 7 | case 2: System.out.println("It is: 2"); 8 | default: System.out.println("It is: default"); 9 | case 5: System.out.println("It is: 5"); 10 | case 9: System.out.println("It is: 9"); 11 | } 12 | } 13 | 14 | 15 | Output: 16 | It is: default 17 | It is: 5 18 | It is: 9 19 | 20 | Explanation of Answer: Unless you write a break the code will continue to execute. 21 | -------------------------------------------------------------------------------- /toString can output Set,List and Map: -------------------------------------------------------------------------------- 1 | This is the proof that the Set, Map and List can output all the elements in them using the toString() method 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | 11 | 12 | public class Demo { 13 | public static void main(String[] args) { 14 | List list=new ArrayList(); 15 | Set set=new HashSet(); 16 | Map map=new HashMap(); 17 | for(int i=1;i<=10;i++){ 18 | list.add(i); 19 | set.add(i); 20 | map.put(i, i); 21 | } 22 | System.out.println(list.toString()); 23 | System.out.println(set.toString()); 24 | System.out.println(map.toString()); 25 | 26 | } 27 | } 28 | 29 | 30 | 31 | Output: 32 | 33 | 34 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // Output of list 35 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // Output of set 36 | {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10} // Output of map 37 | -------------------------------------------------------------------------------- /wait vs sleep vs yield method: -------------------------------------------------------------------------------- 1 | wait() is called in a synchronized method in java. This is what happens when synchronized methods are used in 2 | Java. (i.e. wait() and notify() methods are used by the threads) 3 | 4 | 5 | It all eventually makes its way down to the OS’s scheduler, which hands out timeslices to processes 6 | and threads. 7 | 8 | sleep(n) says “I’m done with my timeslice, and please don’t give me another one for at least n milliseconds.” 9 | The OS doesn’t even try to schedule the sleeping thread until requested time has passed. 10 | 11 | yield() says “I’m done with my timeslice, but I still have work to do.” The OS is free to immediately give 12 | the thread another timeslice, or to give some other thread or process the CPU the yielding thread just gave up. 13 | 14 | .wait() says “I’m done with my timeslice. Don’t give me another timeslice until someone calls notify().” 15 | As with sleep(), the OS won’t even try to schedule your task unless someone calls notify() 16 | (or one of a few other wakeup scenarios occurs). 17 | 18 | Threads also lose the remainder of their timeslice when they perform blocking IO and under a few other 19 | circumstances. If a thread works through the entire timeslice, the OS forcibly takes control roughly as 20 | if yield() had been called, so that other processes can run. 21 | 22 | You rarely need yield(), but if you have a compute-heavy app with logical task boundaries, inserting 23 | a yield() might improve system responsiveness (at the expense of time — context switches, even just to 24 | the OS and back, aren’t free). Measure and test against goals you care about, as always. 25 | 26 | State diagram of thread states -> http://codexplo.wordpress.com/2012/10/20/state-diagram-of-java-thread/ 27 | Source: http://www.logicaltrinkets.com/wordpress/?p=153 28 | 29 | 30 | How does locks work in Java explained: http://stackoverflow.com/questions/17368595/java-lock-concept-how-internally-works 31 | --------------------------------------------------------------------------------